Home > database >  Spring Boot number of DTOs for external clients
Spring Boot number of DTOs for external clients

Time:09-24

I have 2 external clients, Client A and Client B that need Order data stored in MongoDB, and I'm trying to understand the proper way to structure a Spring Boot project to give these two clients what they need. They both need similar data except Client A wants a little more data.

My thought:

  1. Create 2 controllers, one for Client A and Client B. The Client A controller will return OrderDTO_A and Client B controller will return OrderDTO_B.
  2. Create 2 services that both inject the Order repository to grab Order data
  3. In each service, I will make a call for the Order data using the repository, map the results to the appropriate DTO, and return the DTO to the controller.

Does this sound right? This feels weird to me because I have my Order domain models that get saved to the database. I have a set of DTO models for Client A, and I have a set of DTO models for Client B.

What if I have a Client C? Based on this, I'd have another set of DTOs for Client C. Is this right? It just feels wrong because I have a lot of DTOs that look very similar, but plus or minus a few fields for the specific client.

CodePudding user response:

Given that Client A just needs a little bit more data I would not go with the Controller/Service per Client approach. Stick with one that provides the data that Client A needs. Client B can ignore the part of the data they don't need.

If this is not desirable because the amount of data is large, then you may consider providing a GraphQL endpoint. With GraphQL it is the client that decides which attributes it wants to receive.

Yet another approach could be JSON Views, but I would avoid it if possible because it can very easily become very hard to maintain.

CodePudding user response:

The boundary of domain can help us to judge do we need a new DTO.

If the little bit more data Client A want belong to the same domain Client B already used, we should reuse the same DTO, rather than creating a new one. The DTO is the composition of domain objects to fit in different use cases.

Check this article's advice about the common mistake when using DTO, I found it is very helpful. cheers.

  • Related