Reputation: 5411
I'm trying to use reactive pattern REST service using spring boot. I have setup the code and it's working to save item in Cassandara database. Now I have the following requirement to write in reactive way:
If item is not found in database save the item. If Item is present throw exception.
I have been trying to figure out how do such logic in reactive manner. Since I'm beginner in this field, it's hard to get the concept. Following is my approach:
@Override
public Mono<String> createItem(ItemCreateParam itemCreateParam) {
//This check if item exits in database.
Mono<Boolean> byName = reactiveItemRepository.existsById(itemCreateParam.getName());
//This save the item and return the id (i.e name)
return Mono.just(itemCreateParam)
.flatMap(item -> convert(item))
.log()
.flatMap(t -> reactiveTemplateRepository.save(t))
.map(t-> t.getName());
}
How to combine these two in a reactive way?
Upvotes: 0
Views: 1820
Reputation: 2750
Just check the result of existsWithId()
. This is how I would implement that:
@Override
public Mono<String> createItem(ItemCreateParam itemCreateParam) {
return reactiveItemRepository.existsById(itemCreateParam.getName())
.doOnNext(exists -> {
if (exists) {
throw new AppException(ErrorCode.ITEM_EXISTS);
}
})
.flatMap(exists -> convert(item))
.flatMap(converted -> reactiveTemplateRepository.save(converted))
.map(saved -> saved.getName());
}
Note that AppException
type could be anything else, but it should extend RuntimeException
.
Upvotes: 3