如何在通过 id API 查找时,使用 spring webFlux 发送 HTTP 状态为 200 的正文或 HTTP 状态为 204 的空正文?

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

即使使用此代码,当我查找一个不存在的人的 ID 时,我也会收到 200 的空响应。如何根据 personManager.findById 结果设置不同的状态?我来自命令式背景,也许这很愚蠢,但我没有找到任何关于如何做的共识,即使是在官方文档上也是如此

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())

问题是 .body 总是 return 一个 Mono 填充了一个 ServerResponse,所以它永远不会切换为空。我真的不知道这是否语法正确,但我设法做了我想做的事情:

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

以及与 Flux 相同的行为(在本例中为 findAll):

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