kruschid / typesafe-routes

Spices up your favorite routing library by adding type safety to plain string-based route definitions.
https://kruschid.github.io/typesafe-routes/
MIT License
102 stars 8 forks source link

Testing against arbitrary URLs #19

Open ajselvig opened 2 years ago

ajselvig commented 2 years ago

Hello, this may be out of the scope of this library, but the core type-safe route declarations look great and I'd like to integrate it into my custom frontend framework. The one hurdle I'm currently stuck on is the ability to define a set of routes and test them against arbitrary (runtime) URLs.

The current parseParams API seems to be focused on parsing an already semi-parsed set of key/value pairs. This makes sense for compile-time routing but I'd like to extend the functionality to runtime routing using arbitrary URLs. I would imagine the API would look something like this:

const fooRoute = route("/foo/:id", {
     id: stringParser
}, {})

let res = fooRoute.parseUrl("/foo/bar")
// {"id": "bar"}

res = fooRoute.parseUrl("/hello/world")
// null or throw?

Is there existing functionality for this that I'm overlooking or is this something that seems like a reasonable extension to the API? I'm happy to investigate implementing it myself if you're open to PRs but the internals looks a little... dense at first glance.

Let me know your thoughts and thanks for the work on this excellent library!

anilanar commented 1 year ago

@ajselvig Considering these routing templates are called path-to-regexp strings, isn't https://github.com/pillarjs/path-to-regexp what you are looking for? It basically takes a string template and produces a regexp with which you can use match or test to parse/validate arbitrary urls.

ajselvig commented 1 year ago

Yeah, I ended up keeping a separate regexp around and doing the parsing against that, but there's a decent amount of boilerplate that goes with it (mainly around validating required params): https://github.com/Terrier-Tech/tuff/blob/master/src/routing.ts#L68