调用Play中的常用函数

Invoking common functions in Play

我在 Play Framework 中有以下操作:

  def action = Action { request =>

    common1() // this is common to all the actions

    // some functions specific to the action

    var json = common2()  // this is common to all the actions

    Ok(json)
  }

我的应用程序中有很多操作。我的问题是 common1common2 在所有操作中都被调用,我不想重复调用。处理这种情况的好做法是什么?

Http 过滤器

如果每个操作都会调用某些内容,您可能需要查看过滤器:https://www.playframework.com/documentation/2.5.x/ScalaHttpFilters

上面的例子link:

class LoggingFilter @Inject() (implicit val mat: Materializer, ec: ExecutionContext) extends Filter {

  def apply(nextFilter: RequestHeader => Future[Result])
           (requestHeader: RequestHeader): Future[Result] = {

    val startTime = System.currentTimeMillis

    nextFilter(requestHeader).map { result =>

      val endTime = System.currentTimeMillis
      val requestTime = endTime - startTime

      Logger.info(s"${requestHeader.method} ${requestHeader.uri} took ${requestTime}ms and returned ${result.header.status}")

      result.withHeaders("Request-Time" -> requestTime.toString)
    }
  }
}

动作组合:

如果你有一些东西想要 运行 某些代码用于某些操作,创建你自己的 ActionFittlers、ActionRefiners 等:https://www.playframework.com/documentation/2.5.x/ScalaActionsComposition

上面的例子link:

object LoggingAction extends ActionBuilder[Request] {
  def invokeBlock[A](request: Request[A], block: (Request[A]) => Future[Result]) = {
    Logger.info("Calling action")
    block(request)
  }
}

用法:

def index = LoggingAction {
  Ok("Hello World")
}