Lin*_*_98 4 functional-programming scala for-comprehension
考虑以下嵌套的平面图结构:
val isValid: F[Boolean] = userRepository.isValid(username, password)
isValid.flatMap(valid =>
if (valid) {
userRepository.getClaims(username).flatMap(claims => {
val token = JWTRefreshService.createToken(claims)
Created(token)
}
)
} else {
Unauthorized(headers.`WWW-Authenticate`(NonEmptyList.of(Challenge(scheme = "Bearer", realm =
"Access to authorize a request"))))
}
)
Run Code Online (Sandbox Code Playgroud)
哪里F是F[_] : Sync。
我怎样才能把这个结构改写成 for-comprehension。我无法弄清楚如何在不创建嵌套 for-comprehension 的情况下重写 if else 子句。
我会用这样的东西:
for {
isValid <- userRepository.isValid(username, password)
validation <- if (isValid) createToken(username)
else
Unauthorized(
headers.`WWW-Authenticate`(
NonEmptyList.of(Challenge(scheme = "Bearer", realm = "Access to authorize a request"))
)
)
} yield validation
def createToken[F: Sync](username: String): F[YourADT] = for {
claims <- userRepository.getClaims(username)
token <- JWTRefreshService.createToken(claims)
} yield Created(token)
Run Code Online (Sandbox Code Playgroud)