我想知道是否有可能在单一操作中进行过滤和转换,我不太喜欢andThen
...
示例:
class AuthAction @Inject()(val userService: UserService)(implicit val executionContext: ExecutionContext) extends ActionFilter[Request] {
override protected def filter[A](request: Request[A]): Future[Option[Result]] = {
if (request.headers.hasHeader("Authorization")) {
val token = UUID.fromString(request.headers.get("Authorization").get)
userService.getUserByToken(token).map{ _ =>
// I would like to include the user in the request.
None
}
} else {
Future.successful(Some(Unauthorized(Json.obj(
"error" -> "no_token_provided"
))))
}
}
}
是否可以在单个操作中执行过滤和转换,或者是否必须使用andThen
。
答案 0 :(得分:0)
ActionRefiner
可以按如下方式在单个操作中启用过滤和转换:
case class User(name: String, id: String)
class UserAuthRequest[A](val user: Option[User], request: Request[A])
extends WrappedRequest[A](request)
class AuthActionRefiner @Inject()(val parser: BodyParser[AnyContent])(implicit val executionContext: ExecutionContext)
extends ActionBuilder[UserAuthRequest, AnyContent]
with ActionRefiner[Request, UserAuthRequest] {
override protected def refine[A](request: Request[A]): Future[Either[Result, UserAuthRequest[A]]] = {
if (request.headers.hasHeader("Authorization")) {
val token = UUID.fromString(request.headers.get("Authorization").get)
val userOpt: Option[User] = userService.getUserByToken(token)
Future.successful(Right(new UserAuthRequest[A](userOpt, request)))
} else {
Future.successful(Left((Results.Unauthorized(Json.obj("error" -> "no_token_provided")))))
}
}
}