Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extend Spring Data Rest index resource links

I'm mapping all my api endpoints under the base url /api/. Now I want to expose all the available endpoints by using spring-data-rest via HATEOAS so that a client application can process these information. By default this seems to work out of the box, as a GET /api/ returns all found Spring repositories and their respective url like this:

{
  "_links" : {
    "news" : {
      "href" : "http://localhost:8080/api/news{?page,size,sort,projection}",
      "templated" : true
    }
  }
}

However, I would like to add some custom links to other resources. I tried this:

@RequestMapping("/api")
public class AppController {

  @RequestMapping("/")
  public ResponseEntity<ResourceSupport> getEndpoints () {
      ResourceSupport resource = new ResourceSupport();

      resource.add(linkTo(UserController.class).withRel("users"));

      return new ResponseEntity<>(resource, HttpStatus.OK);
  }
}

But this actually overwrites everything. So my question is how can I extend the standard output of spring-data-rest for the base resource with some custom links?

like image 679
kenda Avatar asked Feb 03 '17 15:02

kenda


1 Answers

I assume you are using spring-data-rest.

To add links to your service's index resource you have to write a ResourceProcessor<RepositoryLinksResource>

This processor will be invoked when the index resource is generated and you can use it to add links to the index resource.

Here is an example:

/**
 * Adds custom controller links to the index resource
 */
@Component
public class RepositoryLinksResourceProcessor implements ResourceProcessor<RepositoryLinksResource> {

    @Override
    public RepositoryLinksResource process(RepositoryLinksResource resource) {
        resource.add(linkTo(UserController.class).withRel("users"));
        return resource;
    }
}
like image 155
Mathias Dpunkt Avatar answered Sep 21 '22 14:09

Mathias Dpunkt