Frage

In the rest part of my lift application I often have code like this:

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
    }
}

As you can see for every user operation I have this piece of code:

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

My question is - do I have a way to put this piece of code to one place to avoid repeating it for every request?

War es hilfreich?

Lösung

You could write a function to handle unboxing objects for you. Something like this should help:

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)) 
}

Then, you'd just call it like :

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

Andere Tipps

If you are just doing this for the purposes of authentication, you should be able to use guarded LiftRules.dispatch calls. Described in Simply Lift and in more detail here.

You may also just be able to use LiftRules.httpAuthProtectedResource(UserRest), but I'm not really sure about that.

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top