HATEOAS on Spring Flux/Mono response

后端 未结 2 1161
没有蜡笔的小新
没有蜡笔的小新 2020-12-19 01:33

I\'ve been using Spring HATEOAS following the guidelines:

https://spring.io/guides/gs/rest-hateoas/#initial

package hello;

import static org.springf         


        
相关标签:
2条回答
  • 2020-12-19 02:33

    I think this project does not support (yet?) the new reactive support in Spring Framework. Your best bet is to reach out to the maintainers and contribute to the project (creating an issue and explaining what you're trying to achieve is a start!).

    0 讨论(0)
  • 2020-12-19 02:36

    Update as there is support to use HATEOAS with Spring Web Flux.

    public class Person extends ResourceSupport
    {
        public Person(Long uid, String name, String age) {
            this.uid = uid;
            this.name = name;
            this.age = age;
        }
    
        private Long uid;
        private String name;
        private String age;
    
        public Long getUid() {
            return uid;
        }
    
        public void setUid(Long uid) {
            this.uid = uid;
        }
    
        public String getName() {
            return name;
        }
    
        public void setName(String name) {
            this.name = name;
        }
    
        public String getAge() {
            return age;
        }
    
        public void setAge(String age) {
            this.age = age;
        }
    }
    

    Using the above Person in Controller as follows

    @GetMapping("/all")
        public Flux getAllPerson() {
            Flux<List<Person>> data = Flux.just(persons);
            return data.map(x ->  mapPersonsRes(x));
        }
    
        private List<Resource<Person>> mapPersonsRes(List<Person> persons) {
        List<Resource<Person>> resources = persons.stream()
                .map(x -> new Resource<>(x,
                        linkTo(methodOn(PersonController.class).getPerson(x.getUid())).withSelfRel(),
                        linkTo(methodOn(PersonController.class).getAllPerson()).withRel("person")))
                .collect(Collectors.toList());
        return resources;
    }
    

    Or if you want for one person, you can also use Mono

    @GetMapping("/{id}")
    public Mono<Resource<Person>> getPerson(@PathVariable("id") Long id){
        Mono<Person> data = Mono.justOrEmpty(persons.stream().filter(x -> x.getUid().equals(id)).findFirst());
        Mono person = data.map(x -> {
            x.add(linkTo(methodOn(PersonController.class).getPerson(id)).withSelfRel());
            return x;
        });
        return person;
    }
    

    This is simple use of .map function provided by Flux/Mono. I hope this will be helpful for later viewers.

    0 讨论(0)
提交回复
热议问题