Play - ActionFunction

ActionFunction 其实是对request的处理

  • 自定义请求类型
  • 提取或者处理请求的各种参数

https://www.playframework.com/documentation/2.5.x/ScalaActionsComposition


import play.api.mvc._

class UserRequest[A](val username: Option[String], request: Request[A]) extends WrappedRequest[A](request)

object UserAction extends
ActionBuilder[UserRequest] with ActionTransformer[Request, UserRequest] {
def transform[A](request: Request[A]) = Future.successful {
new UserRequest(request.session.get("username"), request)
}
}

class ItemRequest[A](val item: Item, request: UserRequest[A]) extends WrappedRequest[A](request) {
def username = request.username
}

def ItemAction(itemId: String) = new ActionRefiner[UserRequest, ItemRequest] {
def refine[A](input: UserRequest[A]) = Future.successful {
ItemDao.findById(itemId)
.map(new ItemRequest(_, input))
.toRight(NotFound)
}
}

object PermissionCheckAction extends ActionFilter[ItemRequest] {
def filter[A](input: ItemRequest[A]) = Future.successful {
if (!input.item.accessibleByUser(input.username))
Some(Forbidden)
else
None
}
}

UserAction

对传入的request 获取session 并且转换为UserRequest 类型

ItemAction

传入UserRequest 类型
通过id(基本都是路由来的) DB查询后 构成ItemRequest
在构成ItemRequest 过程中 会得到username 属性

PermissionCheckAction

输入ItemRequest 然后检验 如果xxx 报错 xxx 继续

用法

def tagItem(itemId: String, tag: String) =
(UserAction andThen ItemAction(itemId) andThen PermissionCheckAction) { request =>
request.item.addTag(tag)
Ok("User " + request.username + " tagged " + request.item.id)
}

andThen 对多个Action Function 进行连接处理 就是中间件的的感觉