sparsetech / trail

Routing library for the Scala platform
82 stars 8 forks source link

no "empty" (zero) path segment #28

Closed aappddeevv closed 5 years ago

aappddeevv commented 5 years ago

I need to create a different root based on whether I am running against a dev server or a prod server. The base url is different. But there does not seem to be a way to define a zero path segment so I can form the proper root.

// dev server, root has no content after the location's origin
// http://devserver/users
val root = Root / Arg[String]
// but on prod server, http://prodserver/api/v2.0/users
val root  = Root / someString / Arg[String]
// so ideally, I would have
val root = Root / maybeSegment.getOrElse(Zero) / Arg[String]]

Is there any way to handle this? The SPA client needs to handle this in the SPA's router. If the HList is statically defined, I'm not sure how I would be able to do this.

tindzk commented 5 years ago

Thanks for the issue, @aappddeevv! I agree this is a useful feature. It revealed some insufficiencies in Trail's current design. Ideally, static path elements should not be encoded in the type parameter at all, only the placeholders (like Arg[String] or Fragment[Int]).

I have explored some ways to simplify the design and found a way to model the current functionality with tuples instead of HLists. Could you try out #29 and let me know your thoughts?

With the changes, you could express conditional routes as follows:

class Routes(isProduction: Boolean) {
  val root  = if (isProduction) Root / "api" / "v2.0" else Root
  val users = root / "users" / Arg[String]
}

val devRoutes  = new Routes(isProduction = false)
val prodRoutes = new Routes(isProduction = true)

assert(devRoutes.users.parse("/users/test").contains("test"))
assert(prodRoutes.users.parse("/api/v2.0/users/test").contains("test"))
aappddeevv commented 5 years ago

Do I need to try this with a local build? Or did you push something out to the repos?

Whoops, just saw the tag.

aappddeevv commented 5 years ago

So far its working. Ideally you could always change the server routing but that's not always possible e.g. static website server.

tindzk commented 5 years ago

Great, thanks for testing!