1

I have a method to register a user:

public Mono<Either<AppError, UserDTO> > registerUser(RegisterUserDTO dto) {
Mono<Either<AppError, Mono<UserDTO> > > result = userFactory
        .create(dto.username(), dto.password(), UserRole.COMMON)
        .map(it -> it
                .map(user -> reactiveUserRepository
                        .add(user)
                        .map(User::toDTO)
                )
        );
   return result;
}

Create method from UserFactory returns Mono<Either<AppError, User> > and add method from ReactiveUserRepository returns Mono< User >. Of course, it doesn't compile, because i need Mono<Either<AppError, UserDTO> > instead of Mono<Either<AppError, Mono< UserDTO > > >. How i can do that?

Update: It's a solution from other forum:

public Mono<Either<AppError, UserDTO> > registerUser(RegisterUserDTO dto) {
return userFactory
        .create(dto.username(), dto.password(), UserRole.COMMON)
        .flatMap(it -> it
                .map(user -> reactiveUserRepository
                        .add(user)
                        .map(u -> Either.<AppError, UserDTO>right(u.toDTO() ) )
                )
                .mapLeft(error -> Mono.just(Either.<AppError, UserDTO>left(error) ) )
                .getOrElseGet(error -> error)
        );
}

Anybody has better idea or it's best one? (It looks horrible, i know)

Sampeteq
  • 123
  • 8
  • to summarize the solution - you need to use `flatMap` instead of `map`. Also, you don't really need `map` before `reactiveUserRepository.add. Not sure you could change the contract but I would return `Mono` and error signal (`Mono.error`) in case of error. – Alex Aug 10 '22 at 05:02

0 Answers0