Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Exposing link on collection entity in spring data REST

Using spring data REST I have exposed a ProjectRepository that supports listing projects and performing CRUD operations on them. When I go to http://localhost:8080/projects/ I get the list of projects as I expect.

What I am trying to do is add a custom action to the _links section of the JSON response for the Project Collection.

For example, I'd like the call to http://localhost:8080/projects/ to return something like this:

{
  "_links" : {
    "self" : {
      "href" : "http://localhost:8080/projects/{?page,size,sort}",
      "templated" : true
    },
    "search" : {
      "href" : "http://localhost:8080/projects/search"
    },
    "customAction" : {
       "href" : "http://localhost:8080/projects/customAction"
    }
  },
  "page" : {
    "size" : 20,
    "totalElements" : 0,
    "totalPages" : 0,
    "number" : 0
  }
}

Where customAction is defined in some controller.

I've tried creating the following class:

public class ProjectCollectionResourceProcessor implements ResourceProcessor<Resource<Collection<Project>>> {

    @Override
    public Resource<Collection<Project>> process(Resource<Collection<Project>> listResource) {
        // code to add the links to customAction here
        return listResource;
    }

}

and adding adding the following Bean to my applications configuration:

@Bean
public ProjectCollectionResourceProcessor projectCollectionResourceProcessor() {
    return new ProjectCollectionResourceProcessor();
}

But process(...) doesn't ever seem to get called. What is the correct way to add links to Collections of resources?

like image 252
thorben.jakobsen Avatar asked Jun 17 '14 22:06

thorben.jakobsen


2 Answers

The collection resources render an instance of Resources<Resource<Project>>, not Resource<Collection<Project>>. So if you change the generic typing in your ResourceProcessor implementation accordingly that should work as you expect it.

like image 163
Oliver Drotbohm Avatar answered Nov 19 '22 05:11

Oliver Drotbohm


I had the same issue. What worked for me was:

public class ProjectsResourceProcessor implements ResourceProcessor<PagedResources<Resource<Project>>> {

    private final @NonNull EntityLinks entityLinks;

    @Override
    public PagedResources<Resource<Project>> process(PagedResources<Resource<Project>> pagedResources) {

       ...

        return pagedResources;
    }
}
like image 23
Goran Gloncak Avatar answered Nov 19 '22 04:11

Goran Gloncak