Looking to build an API that lets the client specify what fields they want projected from the internal Domain object to the external Domain resource
DB --> Foo Entity --> Foo Mapper --> Foo Resource
Client sends a request parameter called fieldsToProject
e.g.
fieldsToProject: ["id", "name", "description", "basePrice", "unitPrice", "manufacturer"]
I wrote a very crude method but it works like so
public FooResource toProjectedFooResource(Foo foo, List<String> fieldsToProject) {
FooResource resource = new FooResource();
if (fieldsToProject.contains("id")) {
resource.setId(foo.getId());
}
if (fieldsToProject.contains("name")) {
resource.setName(foo.getName());
}
if (fieldsToProject.contains("basePrice")) {
resource.setBasePrice(foo.getBasePrice());
}
if (fieldsToProject.contains("unitPrice")) {
resource.setUnitPrice(foo.getUnitPrice());
}
//etc.
return resource;
}
Is there a neater or cooler way to do this without having a 400 line function with all these if statements?
Also if the client sends the fields with incorrect spelling or case then the solution should just ignore it, not throw an exception.
Note I am using Spring Boot 2.3 with Spring Hateoas + Rest
Aucun commentaire:
Enregistrer un commentaire