// create a hash from clear password
return hashPassword(password, pbkdf2Values)
// search for email/hash pair in db
.flatMap { database.findUserByCredentials(email, it) }
.map {
// if user is registered, check for existing auth token
when (val existingToken = database.token(it, userAgent)) {
is Either.Left -> createToken(jwtValues, it, userAgent) // no token -> create a new one
is Either.Right -> existingToken.value // token exists -> return it
}
}
I tried to use
either.eager{}
or
fold(ifLeft, ifRight)
but I didn’t find any solution more convincing 😕
s
simon.vergauwen
02/24/2022, 8:46 AM
Code style is always a bit subjective but I always prefer
either
blocks.
Copy code
either.eager {
val cred = hashPassword(password, pbkdf2Values).bind()
val user = database.findUserByCredentials(email, cred).bind()
database.token(user, userAgent)
.handleError { createToken(jwtValues, user, userAgent) }
.bind()
}
simon.vergauwen
02/24/2022, 8:46 AM
You can compose`handleError` with
database.token
to provide a fallback function before you
bind
the value.
simon.vergauwen
02/24/2022, 8:47 AM
Or
handleErrorWith
if
createToken
returns another
Either
.
j
jean
02/24/2022, 10:01 AM
I was not aware of
handleError
and indeed that make the either block a bit better. Thanks 🙂