kagomez
11/01/2023, 10:03 PMkagomez
11/01/2023, 10:06 PMuserRepository.userBy(id)
.collect { users ->
if (users.isEmpty()) {
call.respond(
status = HttpStatusCode.NotFound,
message = CallResponse(error = true, message = "User not found")
)
} else {
call.respond(status = HttpStatusCode.OK, message = users)
}
}
The database Flow
fun obtainUser(id: String): Flow<List<User>> = flow { emit(userCollection.find(filter = Filters.eq(IdField, id)).toList()) }
if I don't conver it toList it won't let me handle the error which is going to be 404 (which is fine), but I'm building all errors to send the CallResponse
object as part of the response
I tried with the catch operator and was ignored and even wrapping the routing with a try catch didn't do the work eitherkagomez
11/01/2023, 10:06 PMuserRepository.userBy(id)
.catch { TODO() }
.collect { user ->
call.respond(status = HttpStatusCode.OK, message = users)
}
Geovanny Mendoza
11/02/2023, 2:46 AMfun Routing.userRoutes(userRepository: UserRepository) {
get("/users/{id}") {
val userId = call.parameters["id"]
if (userId != null) {
userRepository.obtainUser(userId)
.collect { users ->
if (users.isEmpty()) {
call.respond(
status = HttpStatusCode.NotFound,
message = CallResponse(error = true, message = "User not found")
)
} else {
call.respond(status = HttpStatusCode.OK, message = users)
}
}
} else {
call.respond(HttpStatusCode.BadRequest, "Invalid user ID")
}
}
}
kagomez
11/02/2023, 7:00 PMval id: String = call.parameters["id"] ?: return@get call.respond(
status = HttpStatusCode.BadRequest,
message = CallResponse(error = true, message = "Id parameter not found")
)
Geovanny Mendoza
11/02/2023, 7:26 PMfun Routing.userRoutes(userRepository: UserRepository) {
get("/users/{id}") {
val id: String = call.parameters["id"] ?: return@get call.respond(
status = HttpStatusCode.BadRequest,
message = CallResponse(error = true, message = "Id parameter not found")
)
userRepository.obtainUser(id)
.collect { users ->
if (users.isEmpty()) {
call.respond(
status = HttpStatusCode.NotFound,
message = CallResponse(error = true, message = "User not found")
)
} else {
call.respond(status = HttpStatusCode.OK, message = users)
}
}
}
}