From 0c1ebbd786ff97e525025a1aaed59dd4d5b512ca Mon Sep 17 00:00:00 2001 From: Li Haoyi Date: Thu, 9 Aug 2018 00:39:48 +0800 Subject: Allow for optional query params --- cask/src/cask/endpoints/WebEndpoints.scala | 6 ++++++ readme.md | 6 +++--- 2 files changed, 9 insertions(+), 3 deletions(-) diff --git a/cask/src/cask/endpoints/WebEndpoints.scala b/cask/src/cask/endpoints/WebEndpoints.scala index 70d16e0..2125b4d 100644 --- a/cask/src/cask/endpoints/WebEndpoints.scala +++ b/cask/src/cask/endpoints/WebEndpoints.scala @@ -58,6 +58,12 @@ object QueryParamReader{ v.map(x => implicitly[QueryParamReader[T]].read(ctx, label, Seq(x))) } } + implicit def OptionParam[T: QueryParamReader] = new QueryParamReader[Option[T]]{ + def arity = 1 + def read(ctx: cask.model.ParamContext, label: String, v: Seq[String]): Option[T] = { + v.headOption.map(x => implicitly[QueryParamReader[T]].read(ctx, label, Seq(x))) + } + } implicit def paramReader[T: ParamReader] = new QueryParamReader[T] { override def arity = 0 diff --git a/readme.md b/readme.md index 88f2523..b791c8d 100644 --- a/readme.md +++ b/readme.md @@ -172,9 +172,9 @@ object VariableRoutes extends cask.MainRoutes{ You can bind variables to endpoints by declaring them as parameters: these are either taken from a path-segment matcher of the same name (e.g. `postId` above), or from query-parameters of the same name (e.g. `param` above). You can make -`param` take a `: String` to match `?param=hello`, an `: Int` for `?param=123` -or a `Seq[String]` (as above) for repeated params such as -`?param=hello¶m=world`. +`param` take a `: String` to match `?param=hello`, an `: Int` for `?param=123` a +`Seq[T]` (as above) for repeated params such as `?param=hello¶m=world`, or +`: Option[T]` for cases where the `?param=hello` is optional. If you need to capture the entire sub-path of the request, you can set the flag `subpath=true` and ask for a `: cask.Subpath` (the name of the param doesn't -- cgit v1.2.3