Is there a better approach to this code? ```// cre...
# arrow
j
Is there a better approach to this code?
Copy code
// 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
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()
}
You can compose`handleError` with
database.token
to provide a fallback function before you
bind
the value.
Or
handleErrorWith
if
createToken
returns another
Either
.
j
I was not aware of
handleError
and indeed that make the either block a bit better. Thanks 🙂
👍 1
s
Oh this is nice, I wasn't aware of it also.