@GetMapping
public ResponseEntity<Page<CsatSurveyModel>> getAllSurveys(
@RequestParam(required = false) String teamName,
@RequestParam(required = false) String customerName,
@RequestParam(required = false) Integer year,
@RequestParam(defaultValue = "id") String orderBy,
@RequestParam(defaultValue = "DESC") Direction direction,
@RequestParam(defaultValue = AppConstant.DEFAULT_PAGE) int page,
@RequestParam(defaultValue = AppConstant.DEFAULT_PAGE_SIZE) int size) {
Sort sort = Sort.by(direction, orderBy);
Pageable pageRequest = PageRequest.of(page, size, sort);
Specification<CsatSurvey> csatSurveySpecification = Specification.where(null);
if (Objects.nonNull(teamName)) {
csatSurveySpecification = csatSurveySpecification.and(CsatSurvey.teamNameSpec(teamName));
}
if (Objects.nonNull(customerName)) {
csatSurveySpecification =
csatSurveySpecification.and(CsatSurvey.customerNameSpec(customerName));
}
if (Objects.nonNull(year)) {
csatSurveySpecification = csatSurveySpecification.and(CsatSurvey.yearSpec(year));
}
UserModel loggedInUser = sessionUtils.getLoggedInUser();
List<Team> teams =
UserRole.ADMIN.equals(loggedInUser.getRole())
? Collections.emptyList()
: loggedInUser.getTeams();
Page<CsatSurveyModel> csatSurveyModels =
csatService.getAllSurveysForTeams(teams, csatSurveySpecification, pageRequest);
return ResponseEntity.ok(csatSurveyModels);
}
The first three parameters are used for filtering purposes with specifications. The rest is for page requests. I was wondering if there's a better way to do this. There's a lot of code in the controller, and even if I want to move the processing to the service layer, the method would have to accept a long list of parameters, which I don't want to do. Although this method only accepts seven parameters, there are other routes that accept more than ten parameters.
I understand that one way is to accept all these params as Map<String, String>
, but isn't it a bit tedious to process that?
CodePudding user response:
My way is using a request class.
The advantage is you can change the params without changing the method signature both for the controller and the service (assuming you pass that request object to the service as well).
Example of a Controller method:
public UserDataResponse getUserData(@RequestBody UserDataRequest userDataRequest)
Where UserDataRequest is a simple class with getters and setters.
class UserDataRequest {
private String paramA;
private String paramB;
public String getParamA() {
return paramA;
}
}
etc.
CodePudding user response:
Spring MVC can take a Pageable
(or a Sort
) as a controller parameter directly, and Spring Data can accept one as a query parameter.