Reputation: 44
I would like to write a REST API that return HTTP 400 when I try to create an already existing entity or when I try to update an non existing entity.
@Post
fun create(@Body entity: @Valid Entity): HttpResponse<Entity> {
val optional = entityService.find(entity)
if(optional.isPresent) {
return HttpResponse.badRequest()
}
return HttpResponse.created(entityService.save(entity))
}
How can I do that using non blocking endpoint with RXJava2 and Micronaut, I can only find examples with switchIfEmpty
@Post
@Status(HttpStatus.CREATED)
fun createMeal(@Body entity: @Valid Entity): Single<Entity> {
return entityService.find(entity)
.switchIfEmpty(entityService.save(entity))
.map{success -> entity}
}
but this code always return HTTP 200 even if nothing is saved, I don't think it's a good practice.
Thanks
Upvotes: 0
Views: 363
Reputation: 44
Finally I do something like this :
fun update(name: String, entity: Entity): Single<Entity> {
val observable = BehaviorSubject.create<Entity>()
entitysRepository.find(name)
.subscribe(
{
entity.name = name
update(entity, observable)
},
{ observable.onError(RuntimeException("Entity : $name doesn't exist")) }
)
return observable.singleOrError()
}
fun save(entity: Entity): Single<Entity> {
val observable = BehaviorSubject.create<Entity>()
entitysRepository.find(entity.name)
.subscribe(
{ observable.onError(RuntimeException("Entity : ${entity.name} already exist")) },
{ save(entity, observable) }
)
return observable.singleOrError()
}
Don't really know if it's a good practice or not.
Upvotes: 0
Reputation: 12228
You would use map
to convert the entity to a bad request response since if it exists that is what you want to return. You could also use switchIfEmpty to save the entity which would only occur if the entity is not found. Ensure you wrap that code inside Flowable.defer
to prevent the logic from executing no matter what. In your reactive example above the save will occur on every execution.
return entityService.find(entity)
.map(entity -> HttpResponse.badRequest())
.switchIfEmpty(Flowable.defer() -> {
//return a publisher that emits HttpResponse.created(entity)
})
Upvotes: 0