I have custom simple endpoint that returns some object (record in my case). I would like to validate correctness of returned output data (i.e., output DTO does have all fields set to non null values for example).
Where is the best place to perform such a validation? Is it possible to correct returned values in validator (i.e. changing value null for field "last access of resource" to "Resource was not accessed yet" for example)
Sample illustrative code:
public record SomeDTO(String nameOfUser, String lastAccessedInfo, List<SomeDTO> recursiveIsFun) {
}
@GetMapping(value = "/somethingEndpoint", produces = MediaType.APPLICATION_JSON_VALUE)
public SomeDTO getSomething(HttpServletRequest request) throws IOException, InterruptedException {
final String baseUrl = ServletUriComponentsBuilder.fromRequestUri(request)
.replacePath(null)
.build()
.toUriString();
return new SomeDTO("user accessed at " baseUrl, null, Collections.emptyList());
}
CodePudding user response:
If it should have default values whenever it's null, then I would prefer to do it in the object itself, like:
@GetMapping(value = "/somethingEndpoint", produces = MediaType.APPLICATION_JSON_VALUE)
public SomeDTO getSomething(HttpServletRequest request) throws IOException, InterruptedException {
final String baseUrl = ServletUriComponentsBuilder.fromRequestUri(request)
.replacePath(null)
.build()
.toUriString();
return new SomeDTO("user accessed at " baseUrl, null, Collections.emptyList())
.handleNullValues();
}
public record SomeDTO(String nameOfUser, String lastAccessedInfo, List<SomeDTO> recursiveIsFun) {
public SomeDTO handleNullValues(){
if(lastAccessedInfo == null){
lastAccessedInfo = "default value";
}
return this;
}
}