Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.3k views
in Technique[技术] by (71.8m points)

java - Problem: Returning Flux of type ResponseEntity

I have the following fragment where I want to return a Flux from a ResponseEntity<Response>:

@GetMapping("/{id}")
public Mono<ResponseEntity<Response>> findByDocumentClient(@PathVariable("id") String document){
    return Mono.just(new ResponseEntity<>(new Response(technomechanicalService.findByDocumentClient(document), HttpStatus.OK.value(), null), 
                            HttpStatus.OK))
            .onErrorResume(error -> {
                return Mono.just(new ResponseEntity<>(new Response(null, HttpStatus.BAD_REQUEST.value(), error.getMessage()), 
                                        HttpStatus.BAD_REQUEST));
            });
}

The Response object is as follows:

public class Response{
    private Object body;
    private Integer status;
    private String descStatus;

    public Response(Object body, Integer status, String descStatus) {
        this.body = body;
        this.status = status;
        this.descStatus = descStatus;
    }
}

When consuming the Get method from postman, the service responds to the following:

{
    "body": {
        "scanAvailable": true,
        "prefetch": -1
    },
    "status": 200,
    "descStatus": null
}

Why does it generate this response? Why is the list of objects not responding?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Agree with @Toerktumlare's answer. Quite comprehensive.

@Juan David Báez Ramos based on your answer(better if it were a comment), seems like what you want is putting technomechanicalService.findByDocumentClient(document) result as body in a Response object.

If so you can use Flux API's collectList() operator.

Example code:

@GetMapping("/{id}")
public Mono<ResponseEntity<Response>> findByDocumentClient(@PathVariable("id") String document) {
    return technomechanicalService.findByDocumentClient(document)
        .collectList()
        .map(
            listOfDocuments -> {
              return new ResponseEntity<>(
                  new Response(listOfDocuments, HttpStatus.OK.value(), null), HttpStatus.OK);
            }
        )
        .onErrorResume(
            error -> {
              return Mono.just(new ResponseEntity<>(
                  new Response(null, HttpStatus.BAD_REQUEST.value(), error.getMessage()),
                  HttpStatus.BAD_REQUEST));
            }
        );
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...