lukeed / trouter

:fish: A fast, small-but-mighty, familiar fish...errr, router*
MIT License
634 stars 23 forks source link

Suggested pattern for handling arbitrary query params? #17

Closed TimNZ closed 3 years ago

TimNZ commented 3 years ago

Pass base url, stripped of "#" and "?" ?

lukeed commented 3 years ago

Hi, can you post a snippet of what you're trying to do? Not 100% sure I understand the question.

My guess is that you're looking for a wildcard route?

TimNZ commented 3 years ago

What's the usage pattern you recommend for matching a route but ignoring all query param and hash e.g. router.add('GET','/api/event') router.find('/api/event?a=1#abc') will not match .

It doesn't seem right to to use or add a wildcard to handle query/hash params scenarios.

It's been ages since I used express, but it seems express routers and similar explicitly handle query and hash value parsing and are excluded from route matching.

lukeed commented 3 years ago

Ah, understood now.

You decide what gets passed into find(). The method doesn't have much wiggle room, but you can decide to pass the full URL or just the pathname segment as the url value. Trouter doesn't take a stand on it because it can be used in different contexts (Node.js, service worker, etc), all of which have different parsing mechanics and possibly different matching requirements.

You can see how Polka does this (Express-like framework, extends Trouter directly) here. I parse the URL ahead of time, and then use the pathname segment only for matching the route(s).

I'm using @polka/url for the URL parser itself, but you could use something as simple as new URL() if that's enough for your use case.

TimNZ commented 3 years ago

That's what I thought. Thanks for saving me an hour or 2 writing my own router 👍

lukeed commented 3 years ago

Haha, you're welcome~!