Search code examples
kotlinspring-webfluxhttp-status-codes

How to, on a find by id API, send body with HTTP status 200 or empty body with HTTP status 204 using spring webFlux?


Even with this code I get an emtpy response with 200 when I look for an non existing person's id. How can I set different statuses based on personManager.findById result? I come from an imperative background, and maybe this is silly, but I didn't find any consensus on how to do it, even on official docs

fun get(request: ServerRequest): Mono<ServerResponse> =
    ServerResponse
        .ok().contentType(MediaType.APPLICATION_JSON)
        .body(
            BodyInserters.fromPublisher(
                personManager.findById(request.pathVariable("id").toInt()),
                Person::class.java
            )
        ).switchIfEmpty(ServerResponse.noContent().build())

Solution

  • The problem was that .body always return a Mono filled with a ServerResponse, so it would never switch to empty. I really don't know if this is syntactic right, but I managed to do what I wanted with:

    personManager.findById(request.pathVariable("id").toInt()).flatMap {
        ServerResponse.ok().contentType(MediaType.APPLICATION_JSON).bodyValue(it)
    }.switchIfEmpty(ServerResponse.noContent().build())
    

    and the same behavior to Flux(in this case, findAll):

    with(personManager.findAll()) {
        this.hasElements().flatMap {
            if (it) ServerResponse.ok().bodyValue(this)
            else ServerResponse.noContent().build()
        }
    }