kwhitley / itty-router

A little router.
MIT License
1.71k stars 77 forks source link

feat: Add custom request types #136

Closed jahands closed 1 year ago

jahands commented 1 year ago

This allows strict typing of requests in handlers by passing a generic to the router. Added examples in the tests

Users should prefer to use this over taking advantage of GenericTraps that don't have type info

Methodology

I started by adding a generic RequestType in RouteHandler, and then added the generic to everything that started getting TS errors because of this change. No functionality changes.

hmnd commented 1 year ago

@kwhitley any chance this could be merged or something similar implemented? Using itty with ES Module Workers, and it's annoying having to explicitly type env and context in every single handler.

eidam commented 1 year ago

oh this is pretty neat! 🤞

hmnd commented 1 year ago

While this PR is a good start, I've noticed a number of gaps that are still not fixed by it, unfortunately.

Notably:

I'll take a stab at fixing those if I get a chance.

kwhitley commented 1 year ago

Sorry for dropping this one @jahands! I eventually just started over this weekend and re-wrote a lot of the typings (with the help of GPT4) to allow for a kind of split scenario:

  1. You can pass generics at the Router level - this forces all routes to be "on rail", with the specified RequestType and Args (2nd generic)>
  2. By not passing in generics to the Router, the inner Route type is switched, allowing per-route overrides (via generics or just casting handler args directly) with the same <RequestType, Args> signature.

Check it out here and let me know what you think! https://itty.dev/itty-router/typescript

jahands commented 1 year ago

That looks great! Thanks!