From 03ad4bd0882f966e099d9510c1e0d0c4d294b275 Mon Sep 17 00:00:00 2001 From: Tim Nieradzik Date: Mon, 8 Jul 2019 16:31:38 +0300 Subject: [PATCH] Route: Do not add ampersand if optional parameter is None --- shared/src/main/scala/trail/Route.scala | 11 ++++++----- shared/src/test/scala/trail/UrlTests.scala | 7 +++++++ 2 files changed, 13 insertions(+), 5 deletions(-) diff --git a/shared/src/main/scala/trail/Route.scala b/shared/src/main/scala/trail/Route.scala index 0c7d4bd..3bc690c 100644 --- a/shared/src/main/scala/trail/Route.scala +++ b/shared/src/main/scala/trail/Route.scala @@ -138,11 +138,12 @@ object Route { case class ParamRoute[A, P](route: Route[A], param: Param[P]) extends Route[(A, P)] { override def url(value: (A, P)): String = { val base = route.url(value._1) - val encodedParam = - param.codec.encode(value._2).map(v => param.name + "=" + URI.encode(v)) - .getOrElse("") - val delimiter = if (base.contains("?")) "&" else "?" - base + delimiter + encodedParam + param.codec.encode(value._2) + .map(v => param.name + "=" + URI.encode(v)) + .fold(base) { encodedParam => + val delimiter = if (base.contains("?")) "&" else "?" + base + delimiter + encodedParam + } } override def parseInternal(path: Path): Option[((A, P), Path)] = for { diff --git a/shared/src/test/scala/trail/UrlTests.scala b/shared/src/test/scala/trail/UrlTests.scala index e25c078..bd50856 100644 --- a/shared/src/test/scala/trail/UrlTests.scala +++ b/shared/src/test/scala/trail/UrlTests.scala @@ -132,4 +132,11 @@ class UrlTests2 extends FunSpec with Matchers { assert(url == "/list?upload=true") } + + it("url() should work with optional parameter set to None") { + val route = Root / "disk" / "view" & Param[Long]("disk") & Param[Option[Long]]("folder") + val url = route((48L, None)) + + assert(url == "/disk/view?disk=48") + } }