繁体   English   中英

有没有更好的方法通过 REST API 提供过滤功能?

[英]Is there a better way to provide filtering feature through REST API?

  @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);
  }

前三个参数用于规范过滤目的。 rest 用于页面请求。 我想知道是否有更好的方法来做到这一点。 controller 中有很多代码,即使我想将处理移至服务层,该方法也必须接受一长串参数,我不想这样做。 虽然这个方法只接受七个参数,但还有其他路由接受十多个参数。

我知道一种方法是接受所有这些参数作为Map<String, String> ,但是处理它不是有点乏味吗?

我的方式是使用请求 class。
优点是您可以更改参数而不更改 controller 和服务的方法签名(假设您也将该请求 object 传递给服务)。 Controller 方法示例:

public UserDataResponse getUserData(@RequestBody UserDataRequest userDataRequest) 

其中 UserDataRequest 是一个带有 getter 和 setter 的简单 class 。

class UserDataRequest {
  private String paramA;
  private String paramB;

  public String getParamA() {
    return paramA;
  }
}

等等

Spring MVC 可以直接将Pageable (或Sort )作为 controller 参数,并且 Spring 数据可以接受一个作为查询参数。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM