Search code examples
hateoasspring-hateoashalhypermedia

Spring HATEOAS with Traverson


I'm using spring-hateoas:0.18.0.RELEASE with spring-boot:1.2.5.RELEASE

For calling my Web Service and going through HAL links i'm using Traverson Client (API for client side service traversal inspired by the Traverson JavaScript library)

Spring Hateoas Traverson Documentation

It's new for working with Hypermedia and HateoasRest

My question is when do I need to use PagedResources and Resource?

Example I found here Traverson Client examples :

 final PagedResources<Resource<Customer>> resources = traverson
            .follow("customers","search","findByFirstName")
            .withTemplateParameters(parameters)
            .toObject(new TypeReferences.PagedResourcesType<Resource<Customer>>(){});

The code I wrote is :

ParameterizedTypeReference<Resource<ProjectJSON>> resourceParameterizedTypeReference = new
                ParameterizedTypeReference<Resource<ProjectJSON>>() {};

Resource<ProjectJSON> projectJSONResource = traverson
            .follow("projects")
            .follow("$._embedded.projects[0]._links.self.href")
            .toObject(resourceParameterizedTypeReference);

I know it's not the same thing, but what is the best practice with resources when calling Traverson.toObject() method?


Solution

  • It's simple: you use PagedResources when you are returning lots of items, and you use Resource when you are returning a single item. So when returning many Customer objects you might want to paginate them, and you'd use PagedResources<Resource<Customer>>. For a single customer it'd be Resource<Customer>.

    The Resource just wraps the domain object and adds links to it. If you don't need links now and you know you don't need the links in the future either, you could go without the Resource as well.

    The PagedResources adds page metadata for selecting the page number and page size. It also allows the server to send the information on the total number of pages and the total number of items. You could ask a paged resource to send you page 2 with page size of 5, and you'd get items 6, 7, 8, 9 and 10.