0

I have this piece of code:

@PostMapping(value = {"/store"})
public Mono<ResponseEntity<StoreResponse>> store(@RequestPart("file") Mono<FilePart> file,
                                                 @RequestPart("publicationId") String publicationId,
                                                 @RequestPart("visible") String visible) throws Exception {
    return file
            .doOnNext(this::checkFile)
            .flatMap((f) -> this.saveFileToDatabase(UUID.fromString(publicationId),
                    f.filename(),
                    Boolean.parseBoolean(visible)))
            .then(Mono.just(ResponseEntity.ok().body(new StoreResponse("", "", "Working",
                    null))))
            .onErrorReturn(ResponseEntity.internalServerError().body(new StoreResponse("Not Working",
                    "", "Working", null)));
}

Question 1:
Strange thing with this is that this works as long as i use flatMap on the Mono.
When i switch to map instead of flatMap then it does not work (the file will not be written to a database this.saveFileToDatabase (via spring-data-r2dbc)).
Why is this the way it is?

Question 2:
When i want to do another operation (save file to a minio container) after the saving to database - how can i chain this into the given code? Another then()?

Thomas Lang
  • 1,285
  • 17
  • 35
  • 1
    Best use for `.then` is if you get a `Mono` of type `void` back as far as I know, maybe you confuse it with promises if you know that. your code could be the following (without your questions, these are answered in the answer below) `.flatMap(...).map(unused -> ResponseEntity.ok()...` – BrianM Dec 11 '21 at 23:06

1 Answers1

1

When I switch to map instead of flatMap then it does not work

map operator is designed to perform 1 to 1 synchronous operations like a simple object mapping. On the other hand, flatMap is used for asynchronous I/O operations like as in your case. See map vs flatMap in Reactor

When i want to do another operation after the saving to database

You could use a second flatmap like this:

 .flatMap(file -> this.saveFileToDatabase(...).map(reponse -> file))
 .flatMap(file -> this.saveFileToContainer(...))
lkatiforis
  • 5,703
  • 2
  • 16
  • 35