Spring HATEOAS embedded resource support

前端 未结 8 899
别那么骄傲
别那么骄傲 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:25

    Usually HATEOAS requires to create a POJO that represents the REST output and extends HATEOAS provided ResourceSupport. It is possible do this without creating the extra POJO and use the Resource, Resources and Link classes directly as shown in the code below :

    @RestController
    class CustomerController {
    
        List customers;
    
        public CustomerController() {
            customers = new LinkedList<>();
            customers.add(new Customer(1, "Peter", "Test"));
            customers.add(new Customer(2, "Peter", "Test2"));
        }
    
        @RequestMapping(value = "/customers", method = RequestMethod.GET, produces = "application/hal+json")
        public Resources getCustomers() {
    
            List links = new LinkedList<>();
            links.add(linkTo(methodOn(CustomerController.class).getCustomers()).withSelfRel());
            List resources = customerToResource(customers.toArray(new Customer[0]));
    
            return new Resources<>(resources, links);
    
        }
    
        @RequestMapping(value = "/customer/{id}", method = RequestMethod.GET, produces = "application/hal+json")
        public Resources getCustomer(@PathVariable int id) {
    
            Link link = linkTo(methodOn(CustomerController.class).getCustomer(id)).withSelfRel();
    
            Optional customer = customers.stream().filter(customer1 -> customer1.getId() == id).findFirst();
    
            List resources = customerToResource(customer.get());
    
            return new Resources(resources, link);
    
        }
    
        private List customerToResource(Customer... customers) {
    
            List resources = new ArrayList<>(customers.length);
    
            for (Customer customer : customers) {
                Link selfLink = linkTo(methodOn(CustomerController.class).getCustomer(customer.getId())).withSelfRel();
                resources.add(new Resource(customer, selfLink));
            }
    
            return resources;
        }
    }
    

提交回复
热议问题