如何在spring boot中区分同名不同查询参数的edpoints

2ekbmq32  于 2021-07-03  发布在  Java
关注(0)|答案(1)|浏览(281)

我是spring boot的新手,尝试使用一些资源创建rest api,我有以下几点:
获取所有现有规则:

@GetMapping("/rules")
    @ResponseStatus(HttpStatus.OK)
    @ApiOperation(value = "Get all the existing rules", response = RuleViewModel.class) //Swagger documentation
    public  ResponseEntity<Page<RuleViewModel>> get(@PageableDefault(page = 0, size = 25) Pageable pageable) {
        Page<Rule> rulesEntity = ruleService.findByDeletedIsSend(false, pageable);
        Page<RuleViewModel> ruleViewModels =  rulesEntity.map(mapper::ruleViewModelMapper);
        return new ResponseEntity<>(ruleViewModels, HttpStatus.OK);
    }

使用不同的参数筛选所有现有规则

@GetMapping(value = "/rules")
@ResponseStatus(HttpStatus.OK)
@ApiOperation(value = "Get a specific rule by filter", response = RuleViewModel.class)
public ResponseEntity<Page<RuleViewModel>> getByFilter(
        @RequestParam(name = "id", required = false) Optional<String> ruleId,
        @RequestParam(name = "description", required = false) Optional<String> description,
        @RequestParam(name = "types", required = false) Optional<List<Boolean>> types,
        @RequestParam(name = "layers", required = false) Optional<List<Layer>> layers,
        @RequestParam(name = "groups", required = false) Optional<List<Category>> groups,
        Pageable pageable
) {
    Page<Rule> rulesEntities = ruleService
            .filterRule(
                    types.orElse(Arrays.asList(true, false)),
                    layers.orElse(layerService.findByIsActive(true)),
                    groups.orElse(categoryService.findByIsActive(true)),
                    description.orElse(""),
                    ruleId.orElse(""),
                    false,
                    pageable
            );
    Page<RuleViewModel> ruleViewModels = rulesEntities.map(mapper::ruleViewModelMapper);
    return ruleViewModels.getSize() > 0 ? new ResponseEntity<>(ruleViewModels, HttpStatus.OK) : new ResponseEntity<>(HttpStatus.NOT_FOUND);
}

如您所见,路径是相同的(“/rules”),但对于过滤器,它添加了所有可选参数。
我遇到的问题是,当我想将筛选器参数用作:

http://localhost:5656/v1/rules?id=7be4336d-6495-5b71-9bc2-a97c9da5ede2

它总是得到所有的规则端点。
我的解决方法是将“搜索”路径添加到uri中,如下所示:
http://localhost:5656/v1/rules/search?id=7be4336d-6495-5b71-9bc2-a97c9da5ede2
因此请求得到了正确的Map,但我认为这违反了其余的最佳实践。
你能告诉我实现这个目标的正确方法吗?。提前谢谢。

watbbzwu

watbbzwu1#

既然这两个方法的返回类型相同,getbyfilter方法的所有参数都是可选的,为什么不删除getbyfilter方法并将这些参数作为可选参数添加到get方法中呢?如果传入任何可选参数,get方法就可以执行过滤逻辑,否则返回完整的响应而不进行任何过滤。

相关问题