typesafe-routes icon indicating copy to clipboard operation
typesafe-routes copied to clipboard

Testing against arbitrary URLs

Open ajselvig opened this issue 2 years ago • 2 comments

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!

ajselvig avatar Apr 09 '22 23:04 ajselvig

@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.

anilanar avatar Feb 16 '23 08:02 anilanar

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

ajselvig avatar Feb 16 '23 18:02 ajselvig