Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add links to root resource in Spring Data REST?

How to expose an external resource (not managed through a repository) in the root listing of resources of Spring Data REST? I defined a controller following the pattern in Restbucks

like image 937
Stackee007 Avatar asked Apr 17 '14 14:04

Stackee007


2 Answers

This can be done by implementing ResourceProcessor<RepositoryLinksResource>.

Following code snippet adds "/others" to the root listing

@Controller
@ExposesResourceFor(Other.class)
@RequestMapping("/others")
public class CustomRootController implements
        ResourceProcessor<RepositoryLinksResource> {

    @ResponseBody
    @RequestMapping(method = RequestMethod.GET)
    public ResponseEntity<Resources<Resource<Other>>> listEntities(
            Pageable pageable) throws ResourceNotFoundException {
            //... do what needs to be done
    }

    @Override
    public RepositoryLinksResource process(RepositoryLinksResource resource) {
        resource.add(ControllerLinkBuilder.linkTo(CustomRootController.class).withRel("others"));

        return resource;
    }
}

should add

{
    "rel": "others",
    "href": "http://localhost:8080/api/others"
}

to your root listing links

like image 194
Stackee007 Avatar answered Oct 29 '22 13:10

Stackee007


I have been searching for an answer to the same issue, but the key is: I don't have a controller. My url points to something created in an auth filter. What worked for me is to create a RootController that doesn't have any methods, and use it for building links in the ResourceProcessor implementation.

@RestController
@RequestMapping("/")
public class RootController {}

Then the link is inserted using the empty controller.

@Component
public class AuthLinkProcessor implements ResourceProcessor<RepositoryLinksResource> {

    @Override
    public RepositoryLinksResource process(RepositoryLinksResource resource) {
        resource.add(
                linkTo(RootController.class)
                .slash("auth/login")
                .withRel("auth-login"));
        return resource;
    }
}
like image 39
Ld00d Avatar answered Oct 29 '22 15:10

Ld00d