Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 724
Marcel Overdijk Avatar asked Nov 13 '14 22:11

Marcel Overdijk


1 Answers

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));
}
like image 199
Marcel Overdijk Avatar answered Nov 08 '22 17:11

Marcel Overdijk