While designing a new application using spring boot. I wanted to have rest end point for finding all entities with a filter like below
GET http://foo.com/entities?firstName=test&lastName=test2
The implementation looks like below.
@RequestMapping(value = /entities, method = RequestMethod.GET)
public List<Entity> getAll(@RequestParam(value = "firstName", required = false) String firstName, @RequestParam(value = "lastName", required = false) String lastName) {
if (firstName != null && lastName != null) {
return entityRepository.findByFirstNameAndLastName(firstName, lastName);
} else if (firstName != null) {
return entityRepository.findByFirstName(firstName);
} else if (lastName != null) {
return entityRepository.findByLastName(lastName);
} else {
return StreamSupport.stream(entityRepository.findAll().spliterator(), false).collect(Collectors.toList());
}
}
As we can see this gets a little out of hand if we have to add new parameters. What is the easiest way to mitigate this. Or should i change the design. I thought this was the standart practice?
Note. The repository is a CRUDRepository with the added methods.