Spring HATEOAS embedded resource support

前端 未结 8 876
别那么骄傲
别那么骄傲 2020-12-07 14:12

I want to use the HAL format for my REST API to include embedded resources. I\'m using Spring HATEOAS for my APIs and Spring HATEOAS seems to support embedded resources; how

8条回答
  •  失恋的感觉
    2020-12-07 14:45

    Pre HATEOAS 1.0.0M1: I couldn't find an official way to do this...here's what we did

    public abstract class HALResource extends ResourceSupport {
    
        private final Map embedded = new HashMap();
    
        @JsonInclude(Include.NON_EMPTY)
        @JsonProperty("_embedded")
        public Map getEmbeddedResources() {
            return embedded;
        }
    
        public void embedResource(String relationship, ResourceSupport resource) {
    
            embedded.put(relationship, resource);
        }  
    }
    

    then made our resources extend HALResource

    UPDATE: in HATEOAS 1.0.0M1 the EntityModel (and really anything extending RepresentationalModel) this is natively supported now as long as the embedded resource is exposed via a getContent (or however you make jackson serialize a content property). like:

        public class Result extends RepresentationalModel {
            private final List content;
    
            public Result(
    
                List content
            ){
    
                this.content = content;
            }
    
            public List getContent() {
                return content;
            }
        };
    
        EmbeddedWrappers wrappers = new EmbeddedWrappers(false);
        List elements = new ArrayList<>();
    
        elements.add(wrappers.wrap(new Product("Product1a"), LinkRelation.of("all")));
        elements.add(wrappers.wrap(new Product("Product2a"), LinkRelation.of("purchased")));
        elements.add(wrappers.wrap(new Product("Product1b"), LinkRelation.of("all")));
    
        return new Result(elements);
    
    
    
    

    you'll get

    {
     _embedded: {
       purchased: {
        name: "Product2a"
       },
      all: [
       {
        name: "Product1a"
       },
       {
        name: "Product1b"
       }
      ]
     }
    }
    

    提交回复
    热议问题