user1601401
user1601401

Reputation: 732

How to add custom search link to Spring Data Rest

I am trying to create a custom search for my users repository. I have a custom restcontroller for it

@BasePathAwareController
@RequestMapping("/users")
@MultipartConfig(fileSizeThreshold = 20971520)
public class UserController implements ResourceProcessor<Resource<User>>,{

    @Autowired
    UserRepository userReposiotry;

    @Autowired
    private EntityLinks entityLinks;


    @RequestMapping(value = "/search/getAvatar", method = RequestMethod.GET, produces = "image/jpg")
    public ResponseEntity<InputStreamResource> downloadImage(@RequestParam("username") String username)
            throws IOException {

        ClassPathResource file = new ClassPathResource("uploads/" + username+ "/avatar.jpg");

        return ResponseEntity
                .ok()
                .contentLength(file.contentLength())
                .contentType(
                        MediaType.parseMediaType("application/octet-stream"))
                .body(new InputStreamResource(file.getInputStream()));
    }

    @Override
    public Resource<User> process(Resource<User> resource) {
        LinkBuilder lb = entityLinks.linkFor(User.class);
        resource.add(new Link(lb.toString()));

        **// How can I add the search/getAvatar to the user search resource?**

        return resource;
    }
}

The first issue is that I get a 404 when trying to call /users/search/getAvatar?username=Tailor

The second is that how can I add this to the users search links?

Thank you

Upvotes: 1

Views: 2700

Answers (1)

Marc Tarin
Marc Tarin

Reputation: 3169

To add a search link, you need to extend RepositorySearchesResource as illustrated here:

As pointed out in the comments, be sure to check the domain type so as to add search link only for relevant repository.

Upvotes: 2

Related Questions