Given the following Function
implementations...
Get User Credentials From Master Database
private Function<Long, Optional<UserCredentials>>
getUserCredentialsFromMaster() {
return userId -> Optional.ofNullable(userId)
.flatMap(masterUserRepository::findById)
.map(User::getCredentials);
}
Get User Credentials From Secondary Database
private Function<Long, Optional<UserCredentials>>
getUserCredentialsFromSecondary() {
return userId -> Optional.ofNullable(userId)
.flatMap(secondaryUserRepository::findById)
.map(User::getCredentials);
}
I need to execute either getUserCredentialsFromMaster
or getUserCredentialsFromSecondary
depending on where userId
comes from.
Here below is my attempt:
Consider domain class UserProfile
public class UserProfile {
Long id;
Long internalUserId; // if internalUserId is null then externalUserId is not
Long externalUserId; // and vice-versa
}
Attempt to obtain UserCredentials
:
final UserProfile userProfile = userProfileRepository.findById(userProvileId);
final UserCredentials userCredentials =
Optional.ofNullable(userProfile.internalUserId)
.flatMap(getUserCredentialsFromMaster())
.orElse(
Optional.ofNullable(userProfile.externalUserId)
.flatMap(getUserCredentialsFromSecondary())
.orElseThrow(UserCredentialsNotFound::new));
internalUserId
is not null
but the statements above always throw UserCredentialsNotFound
. I've tried to rewrite getUserCredentialsFromMaster
and getUserCredentialsFromSecondary
as plain Java methods invoked from an if-then-else block, and it worked as expected.
Am I missing something?