播放变换和过滤动作

时间:2018-04-11 18:21:22

标签: scala filter playframework action playframework-2.6

我想知道是否有可能在单一操作中进行过滤和转换,我不太喜欢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

1 个答案:

答案 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")))))
    }
  }
}