title: Pagination with Spring-Data : PageRequest leaking into REST Controller
body: <p>I'm working on a REST API based on Spring-Boot with a MongoDB database. The application uses a Controller > Service > Repository approach. I'm currently working on implementing a paginated endpoint:</p>
  
  <pre><code>/api/clients?range={offset}-{limit}
  
  eg. /api/clients?range=0-25 (retrieves entities 0-24)
  </code></pre>
  
  <p>My problem is that, in order to build a 'Content Range' response and in order to distinguish between 200 'OK' and 206 'Partial Content' responses (depending on whether the request retrieves all the entities or not), I need to retrieve info like the total number of entities from a Page object. So I'm building a PageRequest in the Controller which gets passed to the Service and through to the Repository. I end up with something along these lines :</p>
  
  <pre><code>@ResponseBody
  @GetMapping(params = { "range" })
  public ResponseEntity&lt;?&gt; getAllClients(
          final @RequestParam(value = "range", required = false) QueryRange queryRange,
          final HttpServletResponse response) {
  
      response.addHeader(HttpHeaders.ACCEPT_RANGES, "client " + MAX_CLIENTS);
  
      if (queryRange.getCount() &gt; 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&lt;Client&gt; clients = clientService.getAllClients(request);
  
      final HttpStatus status = (queryRange.getOffset() == 0 &amp;&amp; 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&lt;&gt;(clients, status);
  }
  </code></pre>
  
  <p>How could one structure this in order to prevent such leaking ?</p>
  
  <p>Any ideas?</p>