【问题标题】:Scala/Implicit/Playframework/Action: Wrapping Action FunctionScala/Implicit/Playframework/Action:包装动作函数
【发布时间】:2014-07-06 03:52:15
【问题描述】:

这完全是一个 Scala 问题,但它是在 PlayFramework Action 的上下文中:

Action 采用 (play.api.mvc.Request => play.api.mvc.Result) 形式。然后你会传递一个像这样的块:

{ request =>
  Ok(views.html.index("Your new application is ready."))
}

现在我已经定义了一个具有相同签名的函数。一个有隐式请求,一个没有隐式请求。

  def WithUser2(request: Request[AnyContent])(block: (Request[AnyContent]) => Result):Result = {
    block(request)
  }
  def WithUser3(block: (Request[AnyContent]) => Result)(implicit request: Request[AnyContent]):Result = {
    block(request)
  }

我现在这样称呼它(2 个版本):

  def index2 = Action { implicit request => WithUser2(request) { request =>
      Ok(views.html.index("Your new application is ready. " ))
  }}

  def index3 = Action ( implicit request => WithUser3 { request =>
      Ok(views.html.index("Your new application is ready. " ))
  })

有没有办法直接将我的函数附加到 Action 上?我的意思是没有在 WithUserX 之前放置 implicit request => 以便我的函数直接替换 Action 之后的完整块?现在我的函数在块内,我认为这就是我需要转发请求的问题。所以我需要一种方法来摆脱我的功能周围的障碍。

【问题讨论】:

    标签: scala playframework functional-programming


    【解决方案1】:

    这不是 100% 清楚你想要做什么,因为WithUserX 基本上没有什么特别的。看来您正在尝试创建自己的 Action,为此我们有 Action Composition

    如果您要像这样定义一个新的Action

    object WithUser extends ActionBuilder[Request] {
        def invokeBlock[A](request: Request[A], block: (Request[A]) => Future[Result]) = {
            // Do something special maybe?
            block(request)
        }
    }
    

    你可以这样使用它:

    def index = WithUser { request =>
        ...
        Ok("Ok!")
    }
    

    这比在不需要时尝试将其填充到股票 Action 中要好得多。

    【讨论】:

    • 我已经使用带有 WrappedRequest 的 ActionBuilder 来创建自己的操作。它有效,但我没有设法将其他参数传递给我的新 UserAction。此外,我对 Scala 还是很陌生,寻找所有需要的信息总是一场斗争。如果您不是 Scala 专业人士并且了解框架的源代码,那么 Play Framework 站点上的信息通常是不够的。所以这个地方可能不是最好的,但它对我所做的事情更加透明。
    • 我发帖的主要原因是问我是否可以用我的函数替换操作块,而不是从块内调用我的函数。或者,如果有办法摆脱第一个 request => 以缩短代码。我的意思是我的函数与块中的匿名函数具有相同的签名。
    • @bebo 您仍然必须将请求传递给您的函数,所以不,您将无法删除它。这就是为什么我建议将您的函数改为自定义Action,并用它完全替换控制器函数。
    • 有没有办法给ActionBuilder中的invokeBlock传递一个额外的参数?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-01-03
    • 2017-09-18
    • 1970-01-01
    • 2017-09-16
    • 1970-01-01
    • 2018-02-23
    • 2016-08-26
    相关资源
    最近更新 更多