How to add custom query parameters to next/previous links in paged hateoas result?
Asked Answered
G

1

5

I have the following controller methods:

@RequestMapping(method = GET, produces = APPLICATION_JSON_VALUE)
@Transactional(readOnly = true)
public ResponseEntity list(Pageable pageable, PagedResourcesAssembler pagedResourcesAssembler) {
    Page<Customer> customers = customerRepository.findAll(pageable);
    return ResponseEntity.ok().body(pagedResourcesAssembler.toResource(customers, customerResourceAssembler));
}

@RequestMapping(value = "/search", method = GET, produces = APPLICATION_JSON_VALUE)
@Transactional(readOnly = true)
public ResponseEntity search(@RequestParam("q") String q, Pageable pageable, PagedResourcesAssembler pagedResourcesAssembler) {
    Specification spec = where(..some specs..);
    Page<Customer> customers = customerRepository.findAll(spec, pageable);
    return ResponseEntity.ok().body(pagedResourcesAssembler.toResource(customers, customerResourceAssembler));
}

The first method returns all customer resources as pages.

The second one also returns paged results but has the option to provide a q query parameter to filter.

The JSON HATEOAS response from the search method contains a next page link like:

{
     "rel": "next",
     "href": "http://localhost:8080/api/customers/search?page=1&size=10{&sort}"
}

The problem is here the q query parameter is lost.

Should I use the PagedResourcesAssembler differently here?

Godwin answered 13/11, 2014 at 22:24 Comment(0)
G
9

I think I found the solution by creating a link manually; see example below.

@RequestMapping(value = "/search", method = GET, produces = APPLICATION_JSON_VALUE)
@Transactional(readOnly = true)
public ResponseEntity search(@RequestParam("q") String q, Pageable pageable, PagedResourcesAssembler pagedResourcesAssembler) {

    // create link to search method with q; pass link as 3th param to paged resource assembler's toResource method
    Link link = linkTo(methodOn(CustomerController.class).search(q, pageable, pagedResourcesAssembler)).withSelfRel();

    Specification spec = where(..some specs..);
    Page<Customer> customers = customerRepository.findAll(spec, pageable);
    return ResponseEntity.ok().body(pagedResourcesAssembler.toResource(customers, customerResourceAssembler, link));
}
Godwin answered 14/11, 2014 at 18:55 Comment(2)
that expands the self..does it deal with the next/prev?Photoemission
Yes @ChrisDaMour it doesGodwin

© 2022 - 2024 — McMap. All rights reserved.