kwhitley / itty-router

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

Default to the router request type in each Route #99

Closed jacwright closed 1 year ago

jacwright commented 2 years ago

Currently, if we have a custom request object (such as one with an optional user on it, or with params) we must prefix each route like this:

router.get<MyCustomRequest>('/endpoint, req => {
  console.log(req.user);
});

// or

router.get('/endpoint, (req: MyCustomRequest) => {
  console.log(req.user);
});

This change will allow routes to be typed to the request (while still allowing individual routes to still add another type):

interface MyCustomRequest extends Request {
  user?: User;
}

interface MyExtraCustomRequest extends MyCustomRequest {
  authed: boolean;
}

const router = Router<MyCustomRequest>();

router.get('/endpoint', req => {
  console.log(req.user);
});

router.get<MyExtraCustomRequest>('/secure/endpoint', req => {
  console.log(req.authed);
});
kwhitley commented 2 years ago

Thanks!

Now for the most important question (because I'm not much of a TS guy myself)...

jacwright commented 1 year ago

These shouldn't be breaking changes.

jacwright commented 1 year ago

Could we merge this? It would be nice to have.

kwhitley commented 1 year ago

Leaving this open for now based on the discussion, but the entire project has migrated to TS in the v3 conversion.

Current method for doing this is listed here: https://www.npmjs.com/package/itty-router#typescript

kwhitley commented 1 year ago

Closing this, as v3.x brings itty to a TS-first lib, so the types file is no longer with us (RIP).

Let's open a new updated issue if this persists, but as of right now the way to do this is:

import {
  Router,               // the router itself
  IRequest,             // lightweight/generic Request type
} from './itty-router'

// declare a custom Request type to allow request injection from middleware
type RequestWithAuthors = {
  authors?: string[]
} & IRequest

const router = Router()

router
  .get('/authors', withAuthors, (request: RequestWithAuthors) => {
    return request.authors?.[0]
  })