Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Exposing hypermedia links on collection even it's empty using Spring Data Rest

First at all I read the previous question: Exposing link on collection entity in spring data REST

But the issue still persist without trick.

Indeed if I want to expose a link for a collections resources I'm using the following code:

@Component
public class FooProcessor implements ResourceProcessor<PagedResources<Resource<Foo>>> {

    private final FooLinks fooLinks;

    @Inject
    public FooProcessor(FooLinks fooLinks) {
        this.FooLinks = fooLinks;
    }

    @Override
    public PagedResources<Resource<Foo>> process(PagedResources<Resource<Foo>> resource) {
        resource.add(fooLinks.getMyCustomLink());
        return resource;
    }
}

That works correctly except when collection is empty...

The only way to works is to replace my following code by:

@Component
public class FooProcessor implements ResourceProcessor<PagedResources> {

    private final FooLinks fooLinks;

    @Inject
    public FooProcessor(FooLinks fooLinks) {
        this.FooLinks = fooLinks;
    }

    @Override
    public PagedResources process(PagedResources resource) {
        resource.add(fooLinks.getMyCustomLink());
        return resource;
    }
}

But by doing that the link will be exposed for all collections.

I can create condition for exposing only for what I want but I don't think is clean.

like image 334
Kakawait Avatar asked Apr 16 '15 07:04

Kakawait


1 Answers

I think spring does some magic there trying to discover the type of the collection - on an empty collection you cannot tell which type it is of - so spring-data-rest cannot determine which ResourceProcessor to use.

I think I have seen in org.springframework.data.rest.webmvc.ResourceProcessorHandlerMethodReturnValueHandler.ResourcesProcessorWrapper#isValueTypeMatch that they try to determine the type by looking at the first element in the collection and otherwise just stop processing:

if (content.isEmpty()) {
    return false;
} 

So I think you cannot solve this using spring-data-rest. For your controller you could fall back to writing a custom controller and use spring hateoas and implement your own ResourceAssemblerSupport to see the link also on empty collections.

like image 131
Mathias Dpunkt Avatar answered Oct 24 '22 10:10

Mathias Dpunkt