next-api-handler icon indicating copy to clipboard operation
next-api-handler copied to clipboard

Middleware object type inference

Open MutabaziAlleluia opened this issue 3 years ago • 3 comments

  • I'm submitting a ... [x] feature request

  • Summary This handler is well designed and I am using it in more than 3 projects. Using TS, I am trying to infer the type of middleware without success;

const router = new RouterBuilder();
router.use(() => ...).get(req => req.middleware );

Is there a way that it can be handled? If not, I would suggest to add the ability of adding use in the builder constructor. That way the entire router can have access to the return type of each use middleware:

const router = new RouterBuilder({ use: [() => ...] });

MutabaziAlleluia avatar Apr 24 '23 15:04 MutabaziAlleluia

Currently I am handling it with (not so friendly when you have many routes and middlewares) hacks like this:

const abcMiddleware = async () => ({ abc: true });
type ABC = Awaited<ReturnType<typeof abcMiddleware>>;

router.use(abcMiddleware).get<{}, ABC>(
  async ( req, res ) => ({
    abc: req.middleware.abc,
  })
);

MutabaziAlleluia avatar Apr 24 '23 15:04 MutabaziAlleluia

hmm this is a good feature that we should be able to use with use & inject think its doable with current implementation, let me have a think

howard86 avatar Apr 27 '23 16:04 howard86

@MutabaziAlleluia I tried a few ways to tweak with typescript definition, but still no lucks

Feel free to open a PR?

howard86 avatar May 14 '23 15:05 howard86