1
votes
public interface RefreshTokenReactiveRepository extends ReactiveCrudRepository<RefreshToken, Long> {

Mono<RefreshToken> findByValue(String value);

}

The next metod is in the TokenService class.

public Mono<TokenPair> exchangeRefreshToken(String refreshTokenValue) {
  return refreshTokenReactiveRepository.findByValue(refreshTokenValue)
    .zipWhen(
        previousRefreshToken ->
            refreshTokenReactiveRepository.deleteById(previousRefreshToken.getId())
                .then(Mono.just("")),
        (previousRefreshToken, deleteResult) -> previousRefreshToken
    )
    .map(RefreshToken::getAccount)
    .flatMap(this::generateTokenPair);
 }

I want to execute refreshTokenReactiveRepository.deleteById(previousRefreshToken.getId()) side operation which depends on previous mono result(Mono<RefreshToken>) and returns Mono<Void>. Then I want zipWhen return Mono<RefreshToken>.

I achieved this only by using then to replace returning Mono<Void> value:

refreshTokenReactiveRepository.deleteById(previousRefreshToken.getId())
                    .then(Mono.just(""))  

So, are there any more clear ways to achieve this goal? What is the alternative for zipWhen in this case?

1

1 Answers

2
votes

If you don't need the return value of the deleteById method, you don't need to use zip; here you're just interested in deleting the previous token from the repository if it was there, and returning it. Something like this should work:

public Mono<TokenPair> exchangeRefreshToken(String refreshTokenValue) {
    return refreshTokenReactiveRepository.findByValue(refreshTokenValue)
            .flatMap(previousRefreshToken ->
                refreshTokenReactiveRepository
                        .deleteById(previousRefreshToken.getId())
                        .thenReturn(previousRefreshToken.getAccount())
            )
            .flatMap(this::generateTokenPair);
}

You could make this simpler by adding a deleteByValue method on your repository; you'd delete the token in the datastore and get it back in a single database query.