1
votes

I am using Spring Boot 2.2.6, Kotlin and coroutines to implement a simple reactive rest API. I am trying to use the functional style.

How can I change the following code to return the 404 HTTP response if the repository returns an empty Mono<Task> (Task is a simple class of mine domain model)?

suspend fun findOne(request: ServerRequest): ServerResponse {
    val id = request.pathVariable("id")
    val task = repository.findById(id)
    return ServerResponse
            .ok()
            .json()
            .bodyAndAwait(task.asFlow())
}

Pay attention that I am using coroutines. I need an instance of Flow. Examples like this do not apply.

Thanks a lot.

1

1 Answers

2
votes

I think the real question is how to transform a Mono into a suspended result.

Please take a look here.

Actually, this approach is being used in the example that you are looking. Check here

Update (add the code)

suspend fun findOne(req: ServerRequest): ServerResponse {
        val id  = req.pathVariable("id").toInt()
        return taskRepo.findById(id)
                .flatMap { task->ServerResponse.ok().json().body<Task>(task) }
                .switchIfEmpty { ServerResponse.notFound().build() }
                .awaitSingle()

    } 

Update 2 Created a small demo project here.