mercredi 13 octobre 2021

How to design and validate access to a sub-resource in a jax-rs REST API avoiding code duplication?

Specifications

I'm currently developing a JavaEE app using JAX-RS and in the process of exposing various resources I'm faced with the following design dilemma that I haven't found a proper answer to.
Two entities, Customer and Address, are interconnected with the One-To-One, Total Participation relationship, meaning one Address per Customer. Deriving from these I created a resource CustomerResource that exposes various endpoints relating to the Customer entity that lead to basic CRUD operations. Some of these endpoints are:

  • POST (/customers/create)
  • GET (/customers/get)
  • GET (/customers/get/{id})
  • PUT (/customers/update/{id})
  • DELETE (/customers/delete/{id}

The problem arises when I create the second resource AddressResource which will handle endpoints relating to operations for the Address entity. This entity cannot exist without a Customer and as such I came to the decision to convey that using nested URI scheme, as opposed to using QueryParams. Now, as you can imagine, some of the endpoints that the AddressResource exposes are:

  • POST (/customers/{id}/address/create)
  • GET (/customers/{id}/address/get)
  • PUT (/customers/{id}/address/update)
  • DELETE (/customers/{id}/address/delete)

I'm faced with validating IF the Customer ID exists and then continuing on to the actual operation that the endpoint entails. Looking the app design from a top down viewpoint, right after the Resource classes come the Service classes. For each Resource class there is a Service class which carry out any necessary business logic and call for the DAO classes to reflect all the necessary changes to the physical DB and the persistence context. So, any validation happens on the Service layer. The thing is that the AddressService class will have to make a call to check if the Customer exists using the CustomerDao class, which queries the database for the given customerId and returns its findings. If the customer exists then the AddressDao gets called to perform the corresponding query on the DB relating to the Address entities.

So, in a sense, I want to avoid the coupling of the Service classes passing calls to multiple Dao classes, as well as, avoid any duplicate code that validation for multiple resources might lead to.

This is due to the fact that I want to introduce a new One-To-Many resource that also requires validation on the customerId level and this would entail its Service class also calling the CustomerDao. I'm aware of the N+1 query problem and I'm keeping the nested resource depth at a maximum of 2. The validation would have to be performed regardless of the URI design as it derives from the Total Participation rule.

Sry for the long and maybe oversimplified explanation of the problem and thank you all in advance!

Aucun commentaire:

Enregistrer un commentaire