Skip to content

Instantly share code, notes, and snippets.

@YEMEAC YEMEAC/ReactiveIf.java
Last active Oct 16, 2018

Embed
What would you like to do?
Wanted to throw an exception using Reactive Spring only if a service call had results, also a good trick to add your on function directly in a map
private Mono<UserDto> validateUserNameAvailable(UserDto user) {
Mono<Boolean> result = securityClient.getByUserName(user.getUserName()).hasElement();
return result.flatMap(value -> {
if (value) {
throw new UserAlreadyExistsException(
String.format("User {} already exists", user.getUserName()));
}
return Mono.just(user);
});
}
/* IMO is okay and a good pattern return what
were validating like in the examples, this way we keep the calls dependent between them (making the next calls not execeute until the validation is passed) and we return what we got in the validation as a confirmation that this data is valid. Otherwise if we use doNext or then spring will try to optimatize the calls and execute them in paralel creating for example a user that diesnt pass the validation.
*/
public Mono<UserDto> createUser(UserDto request) {
return validateUserNameAvailable(request)
.then(createIndividual(request))
}
private Mono<UserDto> validateUserNameAvailable(UserDto user) {
return securityClient.getByUserName(user.getUsername())
.hasElement()
.flatMap(value -> {
if (value) {
return Mono.error(UserValidationException.forUsernameAlreadyExist());
}
return Mono.just(user);
});
}
/*Las version: we are creating a new user and we want to validate before that doesnt exist anyone with that username in the system*/
private Mono<UserDto> validateUserNameAvailable(UserDto user) {
return securityClient.getByUserName(user.getUsername())
.switchIfEmpty(Mono.just(user))
.flatMap(Mono.error(UserValidationException.forUsernameAlreadyExist()));
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.