Extend Spring Data Rest index resource links
Asked Answered
R

2

5

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?

Reed answered 3/2, 2017 at 15:9 Comment(1)
you are using spring-data-rest aren't you?Phylactery
P
7

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;
    }
}
Phylactery answered 3/2, 2017 at 15:42 Comment(1)
This looks promising! I'll try it on monday :)Reed
D
0

under Spring Boot Version 2.4.4, you can

@Component
public class RepositoryLinksResourceProcessor extends ProfileResourceProcessor {

    /**
     * Creates a new {@link ProfileResourceProcessor} with the given {@link RepositoryRestConfiguration}.
     *
     * @param configuration must not be {@literal null}.
     */
    public RepositoryLinksResourceProcessor(RepositoryRestConfiguration configuration) {
        super(configuration);
    }

    @Override
    public RepositoryLinksResource process(RepositoryLinksResource resource) {
        return super.process(resource);
    }
}
Dismiss answered 7/4, 2021 at 2:59 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.