2
votes

I would like to compose a reactor chain that would basically do as follows:

  1. Validate a submitted User properties such as the length of the firstName, lastName or validity of the email. I would use the validator below.
  2. Validate that the submitted email is not already used by someone else. I would use a reactive repository for that purpose.
  3. Save the User if all above validation checks pass.

User:

@Builder
@Data
@AllArgsConstructor
@NoArgsConstructor
public class User {

    @Id
    private Integer id;
    private String firstName;
    private String lastName;
    private String email;
}

Reactive repository:

public interface UserRepository extends ReactiveCrudRepository<User, Long> {

    @Query("select id, first_name, last_name, email from user u where u.email = :email")
    Mono<User> findByEmail(String email);
}

Validator:

@Component
public class UserValidator implements Validator {

    private final static String EMAIL = "email";
    private static final String FIRST_NAME = "firstName";
    private static final String LAST_NAME = "lastName";

    @Override
    public boolean supports(Class<?> clazz) {
        return User.class.equals(clazz);
    }

    @Override
    public void validate(Object target, Errors errors) {
        User user = (User) target;

        rejectIfEmptyOrWhitespace(errors, EMAIL, "email.required");
        rejectIfEmptyOrWhitespace(errors, FIRST_NAME, "firstName.required");
        rejectIfEmptyOrWhitespace(errors, LAST_NAME, "lastName.required");

        validateFirstName(errors, user.getFirstName());
        validateLastName(errors, user.getLastName());
        validateEmail(errors, user.getEmail());
    }

    private void validateEmail(Errors errors, String email) {
        EmailValidator emailValidator = EmailValidator.getInstance();
        if (!emailValidator.isValid(email)) {
            errors.rejectValue(EMAIL, "email.invalid");
        }
    }

    private void validateFirstName(Errors errors, String firstName) {
        if (firstName.length() < 2) {
            errors.rejectValue(FIRST_NAME, "firstName.min");
        }
    }

    private void validateLastName(Errors errors, String lastName) {
        if (lastName.length() < 2) {
            errors.rejectValue(LAST_NAME, "lastName.min");
        }
    }
}

Handler method:

public Mono<ServerResponse> saveUser(ServerRequest serverRequest) {
    return serverRequest.bodyToMono(User.class)
        // Use validator here
        .flatMap(this::createUserIfEmailNotExists);
}

Helper method:

private Mono<ServerResponse> createUserIfEmailNotExists(User user) {
    return userRepository.findByEmail(user.getEmail())
        .flatMap(existingUser ->
            status(BAD_REQUEST).contentType(APPLICATION_JSON)
                .body(BodyInserters.fromObject("User already exists."))
        )
        .switchIfEmpty(
            userRepository.save(user)
                .flatMap(newUser -> status(CREATED).contentType(APPLICATION_JSON)
                    .body(BodyInserters.fromObject(newUser)))
        );
}

I am not sure how to go about achieving this from a reactive point of view. Ideally there would be 3 steps in the reactive chain mapping to the points above.

Here is what I have tried but I am having trouble with the method arguments and return types breaking the flow of the sequence...

private Mono<ServerResponse> validateUser(User user) {
    Errors errors = new BeanPropertyBindingResult(user, User.class.getName());
    userValidator.validate(user, errors);
    if (errors.hasErrors()) {
        return status(BAD_REQUEST).contentType(APPLICATION_JSON)
            .body(BodyInserters.fromObject(errors.getAllErrors()));
    } else {
        return Mono.empty();
    }
}

Can someone please help?

1
I find it difficult to think in terms of functional reactive programming and therefore I would be very grateful for pointers and tips on how to acquire a reactive mindset: tutorials, links or tips. - balteo
To add information to my own comment above, I found a very interesting source of reactive programming recipes: learnrxjs.io/recipes. It is very useful to have a list of real-world usage of rx operators. Enjoy. - balteo
I have posted a tentative solution to my problem here: stackoverflow.com/a/58102913/536299. There is less nesting than the solution suggested below. Thanks very much anyway to @mslowiak for his reply. - balteo

1 Answers

1
votes

How about this way?

private Mono<ServerResponse> validateUser(User user) {
    return Mono.just(new BeanPropertyBindingResult(user, User.class.getName()))
        .doOnNext(err -> userValidator.validate(user, err))
        .filter(AbstractBindingResult::hasErrors)
        .flatMap(err ->
            status(BAD_REQUEST)
                .contentType(APPLICATION_JSON)
                .body(BodyInserters.fromObject(err.getAllErrors()))
        );
}

private Mono<ServerResponse> createUserIfEmailNotExists(User user) {
    return userRepository.findByEmail(user.getEmail())
        .flatMap(existingUser ->
            status(BAD_REQUEST).contentType(APPLICATION_JSON)
                .body(BodyInserters.fromObject("User already exists."))
        )
        .switchIfEmpty(
            validateUser(user)
                .switchIfEmpty(
                    userRepository.save(user)
                        .flatMap(newUser -> status(CREATED).contentType(APPLICATION_JSON)
                            .body(BodyInserters.fromObject(newUser)))
                )
        );
}