Search code examples
javaspringspring-bootspring-webfluxopenapi-generator

Why need to then Mono.empty() in the default implementation of generated Open API Spring code?


Here is the default implementation of an API generated by the openapi-generator-maven-plugin using Spring Boot as library:

default Mono<ResponseEntity<Void>> testAPI(
    @Parameter(hidden = true) final ServerWebExchange exchange
) {
    Mono<Void> result = Mono.empty();
    exchange.getResponse().setStatusCode(HttpStatus.NOT_IMPLEMENTED);
    return result.then(Mono.empty());
}

Being new to this, there are several things I don't understand:

  1. There are two Mono.empty(), one being the result, one inside the then(Mono.empty()), why is it done like that?
  2. Why can't it just returns one? e.g. return Mono.empty();
  3. Or better yet, remove also the pass in exchange and just do:
return Mono.just(ResponseEntity.status(HttpStatus.NOT_IMPLEMENTED).build());

Solution

  • The default implementation is more like a template that gives you a hint how to complete this API controller. For an API controller usually you need to create a response in at least two steps: first fetch data from some source and then make it a valid response. The template code can give you a start point to write such code. For example, I can write the following code using the template:

    public class UsersApiController implements UsersApi {
        @Override
        public Mono<ResponseEntity<String>> usersGet(
                @Parameter(hidden = true) final ServerWebExchange exchange
        ) {
            var client = WebClient.create("http://calapi.inadiutorium.cz/");
            Mono<String> result = client.get().uri("/api/v0/en/calendars/general-en/today").retrieve().bodyToMono(String.class);
            return result.map(rep -> ResponseEntity.status(HttpStatus.OK).body(rep));
        }
    }
    

    The first Mono.empty becomes the WebClient that gets data from another API, and the second Mono.empty is replaced by a map operation that transforms the API result to ResponseEntity object. If the generator only generates a Mono.empty, newcomers may feel difficult to start writing the controller.