I'm a junior developer and started my first job as a developer and have a question regarding DTO and Model.
Consider this code snippet
@Override
public ResponseEntity<List<PostalCodeLocationModel>> findPostcalCodeLocationPairs(final PostalCodeLocationSearchModel model) {
final String postalCode= model.getPostalCode();
final String location = model.getLocation();
final List<PostalCodeLocationModel> listOfPostalCodeLocationPairs = service.findPostalCodeLocationPairs(plz, ort).stream()
.map(mapper::dtoToModel)
.toList();
return ResponseEntity.ok(listOfPostalCodeLocationPairs);
}
Or
@Override
public ResponseEntity<UserReadModel> getUserData(final String name) {
UserDTO dto = service.getUser(user);
UserReadModel iserReadModel = mapper.dtoToModel(dto);
return ResponseEntity.ok(userReadModel);
}
A similar approach is used in the project I am working on. I am a bit confused because what I have learned is, that in this layer where the Controller is, always map to DTO in the end and send the DTO but here, the service is returning a DTO which is then mapped to the model and return. Is this approach correct?
I always did like that in the past and one of my old projects:
@ApiOperation(value = "Get Enterprises within Radius", notes = "Retrieves enterprises within the given radius from a geographical point")
@GetMapping("/within-radius")
public ResponseEntity<List<EnterpriseDto>> getObjectsWithinRadius(@RequestParam double lat, @RequestParam double lng, @RequestParam double radius) {
List<Enterprise> enterprises = enterpriseService.getEnterprisesWithinRadius(lat, lng, radius);
List<EnterpriseDto> enterpriseDtos = enterpriseMapper.toDtos(enterprises);
return new ResponseEntity<>(enterpriseDtos, HttpStatus.OK);
}
Here I use the service with the parameters and get back an Enterprise object and map it to a DTO which I will return.
service.methods? Is it the case of duplicate conversion, e.g. UserReadModel -> UserDTO -> UserReadModel?