1

嗨,我在 Lift 中为我的 api 使用以下内容:

case "api" :: "all" :: _ Get req => for {
    val after <- req.param("after")
    val before <- req.param("before")
    val limit <- req.param("limit")
} yield JsonResponse(json(ResponseLimitAfterBefore(limit.toInt,
                                                   after.toString,
                                                   before.toString)))

我的问题是,如果缺少三个参数中的任何一个,它就会出错。如果缺少任何参数,任何人都可以帮助我如何为它们中的任何一个赋值吗?例如,如果 after 不在 url 中,那么如何为 after 分配默认值?

谢谢,-法兰

4

1 回答 1

2

If seems you do not understand how for comprehensions work within Scala. Consider the following:

scala> val x: Option[String] = Some("X")
x: Option[String] = Some(X)

scala> val y: Option[String] = None
y: Option[String] = None

scala> for(xx <- x; yy <- y) yield yy
res0: Option[String] = None

scala> for(yy <- y; xx <- x) yield xx
res1: Option[String] = None

Notice that even though xx has a value, the result is None. Given that req.param gives you a Box[String] (which is similar to an Option[String]), you could just do something like this (if you want a response whatever params are passed):

JsonResponse(json(
ResponseLimitAfterBefore(
  limit.map(_.toInt).openOr(0), 
  after.openOr("after default"), 
  before.openOr("another default")
)))

Or, if you just want to provide a default response overall, rather than a paramterised default response:

(for { 
  after <- req.param("after")
  before <- req.param("before") 
  limit <- req.param("limit") 
} yield JsonResponse(json(ResponseLimitAfterBefore(
  limit.toInt, after, before)))
) openOr BadRequestResponse()

I would suggest playing with both LiftResponse subtypes more and also getting a firm grasp on what for comprehensions actually do.

Hope that helps.

于 2011-08-04T11:32:56.510 回答