如何将 Flux<MyObject> 包装在 ResponseEntity 中

use*_*934 8 reactive-programming project-reactor spring-webflux

我需要我的端点以以下 json 格式返回数据:

{
  "code": "SUCCESS",
  "message": "SUCCESS",
  "errors": null,
  "data": []
}
Run Code Online (Sandbox Code Playgroud)

这是我的控制器代码:

@GetMapping(value = "/productSubcategories", produces = MediaType.APPLICATION_JSON_VALUE)
    public Flux<MyDTO> getMyObjects() {

        return myObjectService.getAll()
                .map(myObject -> modelMapper.map(productSubcategory, MyObject.class));
    }
Run Code Online (Sandbox Code Playgroud)

将所有 MyDTO 对象包装在 json 响应的“数据”部分中的最佳方法是什么?

小智 5

我不确定你想要实现什么,但我认为你需要collectList()

@GetMapping(value = "/productSubcategories", produces = MediaType.APPLICATION_JSON_VALUE)
    public Mono<ResponseEntity> getMyObjects() {

        return myObjectService.getAll()
                .map(myObject -> modelMapper.map(productSubcategory, MyObject.class)) // here your have Flux<MyObject>
                .map(obj -> modelMapper.map(obj, MyDTO.class)) // lets assume that here is conversion from MyObject to MyDTO - Flux<MyDTO>
                .collectList() // now you got Mono<List<MyDTO>>
                .map(dtos -> ResponseEntity.status(HttpStatus.OK).body(dtos));
    }
Run Code Online (Sandbox Code Playgroud)