提供休息请求:如何避免代码重复

时间:2014-02-22 15:48:09

标签: lift

在我的电梯应用程序的其余部分,我经常有这样的代码:

object UserRest extends RestHelper {
    serve("user" :: Nil prefix {
        case Req("remove-item" :: itemId :: Nil, "json", PostRequest) => {
            User.currentUser.map{ u =>
              //doing some things and returning message
              "Ready, all right."
            }.getOrElse("You must be logged in to perform this operation.")
         }: JValue

        case Req("update-item" :: itemId :: Nil, "json", PostRequest) => {
            User.currentUser.map{ u =>
              //doing some things and returning message
              "Ready, all right."
            }.getOrElse("You must be logged in to perform this operation.")
         }: JValue
    }
}

正如您在每个用户操作中看到的那样,我有这段代码:

User.currentUser.map{ u =>
    //...
}.getOrElse("You must be logged in to perform this operation.")

我的问题是 - 我是否有办法将这段代码放在一个地方,以避免为每个请求重复这些代码?

2 个答案:

答案 0 :(得分:1)

您可以编写一个函数来为您处理拆箱对象。这样的事情应该会有所帮助:

def unbox[A](t:Box[A])(a: A => JValue) = { 
  val msg = "You must be logged in to perform this operation."
  t.map { u => a(u) }.getOrElse(JString(msg)) 
}

然后,您只需将其称为:

unbox(User.current){ u:User => 
   //doing something
   JString("Ready, all right.")
}

答案 1 :(得分:1)

如果您只是为了身份验证而执行此操作,则应该能够使用受保护的LiftRules.dispatch调用。 Simply Lift中详细介绍here

您也可以使用LiftRules.httpAuthProtectedResource(UserRest),但我对此并不十分肯定。