user1955934
user1955934

Reputation: 3495

How to Wrap Flux<MyObject> in a ResponseEntity

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?

Upvotes: 8

Views: 2300

Answers (1)

mslowiak
mslowiak

Reputation: 1838

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));
    }

Upvotes: 5

Related Questions