如何在访问请求体时撰写动作?

时间:2017-05-23 15:34:29

标签: scala playframework playframework-2.0

有没有办法组合动作,同时在每个动作中访问身体到不同的部分? 所以,例如,如果我有一个看起来像这样的json:

{
   "compayId": 123,
   "reason": "some_reason",
   "date": "2017-01-01",
   "roles": ["1", "2"]
}

我想访问" companyId"和"原因"在审计行动中,在访问"日期"和#34;角色"在实际行动中。 所以我创造了这样的东西,当然没有用......

trait Audit { def auditDao: AuditDao
 def audit[A](action: Action[A]) = Action.async(action.parser) { implicit request => {
   action(request).flatMap( r => 
       Json.toJson(request.body.asInstanceOf[RawBuffer].asBytes().get.toArray).validate[AuditLog].fold( //The instanceOf is ugly, and will not work, it's just for the example
           errors => errorsToFutureResult(errors)(request),
           audit => auditDao.save(audit).map(_ => r)
       )
   }
  }
}

然后使用审计方法包装我的端点:

def get() = audit(Action.async(BodyParsers.parse.raw) { (request: Request[RawBuffer]) =>
 Json.toJson(request.body.asBytes().get.toArray).validate[Roles].fold( 
           errors => errorsToFutureResult(errors)(request),
           roles => //Do stuff with the roles...
       )
})

有办法吗? 谢谢!

0 个答案:

没有答案