Reactive - 改进 Mono 语法

Reactive - Improve Mono syntax

我有这段代码可以正常工作:

return isBlacklistedToken(refreshToken, Boolean.TRUE).flatMap(isBlacklisted -> {
    if (isBlacklisted)
        return Mono.error(new UnauthorizedException(format("The user %s has already logged out.", username)));
    else
        return isBlacklistedToken(accessToken, Boolean.FALSE).flatMap(isABlacklisted -> {
            if (isABlacklisted)
                return Mono.error(new UnauthorizedException(format("The user %s has already logged out.", username)));
            else
                return blacklistTokens(username, refreshToken, accessToken);
        });
});

总结一下:

这种语法虽然有效,但似乎有点草率。有办法改善吗?我写了这段代码,虽然它抛出异常,但最后一部分(将令牌列入黑名单)总是执行 - 也许我对反应式编程的了解有点不足。

return isBlacklistedToken(refreshToken, Boolean.TRUE)
                .flatMap(isBlacklisted -> isBlacklisted ? Mono.error(new UnauthorizedException(format("The user %s has already logged out.", username))) : Mono.empty())
                .then(isBlacklistedToken(accessToken, Boolean.FALSE))
                .flatMap(isBlacklisted -> isBlacklisted ? Mono.error(new UnauthorizedException(format("The user %s has already logged out.", username))) : Mono.empty())
                .then(blacklistTokens(username, refreshToken, accessToken));

编辑:添加 isBlacklistedToken 方法

private Mono<Boolean> isBlacklistedToken(final String token, final Boolean type) {

        return blacklistService.isBlacklisted(token, type);
    }

和相应的 blacklistService 调用(只是一个存储库调用,非常简单)

public Mono<Boolean> isBlacklisted(final String token, final Boolean isRefresh) {
        return Mono.just(this.blacklistRepository.existsBlacklistByTokenAndIsRefresh(token, isRefresh));
    }

我建议如下:

return isBlacklistedToken(refreshToken, Boolean.TRUE)                 
    .filter(isBlacklisted -> !isBlacklisted)                 
    .flatMap(isBlacklisted -> isBlacklistedToken(accessToken, Boolean.FALSE))                 
    .filter(isBlacklisted -> !isBlacklisted)                 
    .flatMap(isBlacklisted -> blacklistTokens(username, refreshToken, accessToken))                 
    .switchIfEmpty(Mono.error(new UnauthorizedException(format("The user %s has already logged out.", username))));

抱歉,如果有一些编译错误,但我在 Kotlin 中尝试过,需要将其转换为 Java,这变得越来越不容易了。