How to Wrap Flux<MyObject> in a ResponseEntity
Asked Answered
C

1

8

I need my endpoint to return data in follow json format:

{
  "code": "SUCCESS",
  "message": "SUCCESS",
  "errors": null,
  "data": []
}

Here is my controller code:

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

        return myObjectService.getAll()
                .map(myObject -> modelMapper.map(productSubcategory, MyObject.class));
    }

What is the best way to put wrap all the MyDTO objects in the "data" section of json response?

Chancey answered 1/9, 2019 at 6:16 Comment(1)
Please provide actual behaviour and MyDto, MyObject codeOmaromara
O
5

I am not sure what you want to achieve but I think you need 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));
    }
Omaromara answered 1/9, 2019 at 8:46 Comment(1)
This is a mix of reactive and non reactive. The real signature of the method here is Mono<ResponseEntity<List<MyDTO>>>, List<MyDTO> should be a Flux for this to be reactive. This code also forces the method to wait for all elements, as collectList does not emit till all elements are collected. Also the MediaType should be MediaType.APPLICATION_STREAM_JSON_VALUE, this would "foce" the List to be Flux. Just a side note for future readers.Weakfish

© 2022 - 2024 — McMap. All rights reserved.