terça-feira, 22 de outubro de 2019

What is the final solution to reuse code in JAX-RS resources?

Back in 2008 I was in college and had to finish my graduation thesis, which was about mashing Web applications. At that time that great news was REST and it was in WAR with SOAP! I came across Roy Fielding famous dissertation, read RESTful Web Services, the book that speed up truly REST APIs (we had data update with GET back then!) in the WEB and then I stated calling myself a RESTAFarian.

Figure 5-3: The client-stateless-server style
"Stateless architectures will never work" - said some SOAP lover 10 years ago 
And I was also a Java programmer! However, back then create REST services for Java was not easy. We had to use servlets and JAX-RS was still in its early days and we already had Restlet! However, JAX-RS was the best solution: annotation based, truly REST language and more. I decided to use Jersey and Spring for my thesis. (the only time I used it, after I felt in love with RESTEasy and have been using it since then).

I liked JAX-RS since 10 years ago I have to repeat code, like check nullable entities and return 404, create entities and build the URI, check if parent resources are found before getting the list of child resources and so on... The basic solution is distribute WebApplicationException throws, then create an exception mapper to create a suitable response when such exception is caught... That's not elegant nor easy to maintain.

Well, at this point, if you came here looking for a solution, well, I don't have it. I mean, I try different approaches, see all these bad ideas I had:


The list would go on, but I want to quickly introduce the new approach I am working one, see this GIST:




The methods from RESTUtils classes allow us to verify a given object and then run some code that will verify a given entity and do other action to build the response. For example, the method checkEntityAndUpdate is useful when you are updating an object, but first you must verify if it is not null (more specifically because PanacheEntity.findById returns null), if it is null 404 is returned, otherwise the consumer propsUpdate can be used to update some of attached object, and this is very important. This is easy to read and helpful, but still we need to repeat some code. With Quarkus and Panache I started an abstract class which was supposed to transform entities operations into suitable HTTP responses, letting us focus on HTTP mapping to our resource methods, but I faced a bug and gave up for now.

The question on this post title remains: What is the final solution to reuse code in JAX-RS resources? What do you use to avoid repeating code? An utility class? A magical framework? Please let me know!




Nenhum comentário:

Postar um comentário