我有一个自定义的简单端点,它返回一些对象(在我的情况下是记录)。我想验证返回的输出数据的正确性(例如,输出DTO确实将所有字段设置为非空值)。
执行这种验证的最佳位置是哪里?是否有可能纠正验证器中的返回值(即更改字段"资源的最后访问"的值为null;到"尚未访问资源"例如)
示例代码: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());
}
如果它在为null时应该有默认值,那么我更愿意在对象本身中这样做,如:
@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;
}
}