使用Spring-Data进行分页:PageRequest泄漏到REST Controller中

时间:2019-03-28 15:38:28

标签: mongodb rest spring-boot spring-data

我正在使用基于Spring-Boot的REST API和MongoDB数据库。该应用程序使用Controller> Service> Repository方法。我目前正在实施分页端点:

/api/clients?range={offset}-{limit}

eg. /api/clients?range=0-25 (retrieves entities 0-24)

我的问题是,为了构建“内容范围”响应并区分200个“确定”响应和206个“部分内容”响应(取决于请求是否检索所有实体),我需要从Page对象中检索信息,例如实体总数。因此,我在Controller中构建了一个PageRequest,它被传递给Service并传递给Repository。我最终得到了类似的东西:

@ResponseBody
@GetMapping(params = { "range" })
public ResponseEntity<?> getAllClients(
        final @RequestParam(value = "range", required = false) QueryRange queryRange,
        final HttpServletResponse response) {

    response.addHeader(HttpHeaders.ACCEPT_RANGES, "client " + MAX_CLIENTS);

    if (queryRange.getCount() > MAX_CLIENTS) {
        throw new ForbiddenRangeException("client", MAX_CLIENTS);
    }

    Integer offset = queryRange.getOffset();
    Integer limit = queryRange.getLimit();

    Integer count = limit - offset;
    Integer page = offset != 0 ? offset / count : 0;

    PageRequest request = PageRequest.of(page, count);

    final Page<Client> clients = clientService.getAllClients(request);

    final HttpStatus status = (queryRange.getOffset() == 0 && clients.isLast())
            ? HttpStatus.OK
            : HttpStatus.PARTIAL_CONTENT;

    final String contentRange = String.format("%d-%d/%d",
            queryRange.getOffset(),
            queryRange.getOffset() + clients.getContent().size() - 1,
                clients.getTotalElements());

    response.addHeader(HttpHeaders.CONTENT_RANGE, contentRange);

    return new ResponseEntity<>(clients, status);
}

如何防止这种结构泄漏?

有什么想法吗?

0 个答案:

没有答案