如何在Play中创建自定义操作! 2.0框架?

时间:2012-08-24 05:34:54

标签: scala playframework-2.0

我想在游戏中制作一个自定义play.api.mvc.Action

  1. 将解析并返回请求中的一些自定义数据(例如访问令牌或协议缓冲区)
  2. 可与其他行为链接
  3. 例如:

    def something = DecodeAccessToken { token: AccessToken => 
      Action {
        // do something with token
        Ok
      }
    }
    

    如果令牌不存在,DecodeAccessToken操作应该提前返回UnauthorizedBadRequest

2 个答案:

答案 0 :(得分:1)

这不是approach recommended in the Play! documentation,但我会将其写成:

def DecodeAccessToken(body: AccessToken => Result)(implicit request: Request[_]): Result = {
  val token: AccessToken = // deserialize token from request
  body(token)
}

def something = Action { implicit request =>
  DecodeAccessToken { token: AccessToken =>
    Ok
  }
}

答案 1 :(得分:0)

您可以按如下方式使用基本模板:

trait DecodeAccessToken[A] extends Action[A]
object DecodeAccessToken {
  def apply[A](bodyParser: BodyParser[A])(block: AccessToken=>Request[A] => Result) = new DecodeAccessToken[A] {
    def parser = bodyParser
    def apply(req: Request[A]) = {
      val token: AccessToken = //deserialize token from request

      // If there is a problem with the token, do not call `block` below
      // Instead just return Results.BadRequest

      block(token)(req)
    }
  }
  def apply(block: AccessToken => Request[AnyContent] => Result): Action[AnyContent] = {
    DecodeAccessToken(BodyParsers.parse.anyContent)(block)
  }
}