我想在游戏中制作一个自定义play.api.mvc.Action
:
例如:
def something = DecodeAccessToken { token: AccessToken =>
Action {
// do something with token
Ok
}
}
如果令牌不存在,DecodeAccessToken
操作应该提前返回Unauthorized
或BadRequest
。
答案 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)
}
}