2012-08-24 104 views
1

我想提出一個自定義play.api.mvc.Action在玩就是:如何在Play中創建自定義操作! 2.0框架?

  1. 將解析和請求返回一些自定義的數據(如訪問令牌,或協議緩衝區)
  2. 可以與其他動作
  3. 被鏈接

例如:

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

如果令牌不存在,則DecodeAccessToken動作壽ld提早返回UnauthorizedBadRequest

回答

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) 
    } 
} 
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 
    } 
}