next-connect
next-connect copied to clipboard
Defining custom properties/types per handler in v1?
I wanted to upgrade to v1 but I'm having some trouble replicating a pattern that I currently use with v0.
From the original README:
In each handler, you can also define custom properties to
req
andres
(such asreq.user
orres.cookie
) like so:interface ExtendedRequest { user: string; } interface ExtendedResponse { cookie(name: string, value: string): void; } handler.post<ExtendedRequest, ExtendedResponse>((req, res) => { req.user = "Anakin"; res.cookie("sid", "8108"); });
Example, inspired by https://github.com/hoangvvo/next-connect/issues/124#issuecomment-779809556:
export default nc<NextApiRequest, NextApiResponse>() .use<{ team?: Team | null; user?: User | null }>(async (req, res, next) => { if (req.method !== "POST") return next(); const [user, team] = await Promise.all(getUser(req.cookies), getTeam(req.query.teamId)); req.user = user; req.team = team; next(); }) .get((req, res) => { console.log(req.user); // No console.log(req.team); // No }) .post<{ team: Team | null; user: User | null }>((req, res) => { console.log(req.user); console.log(req.team); });
This allowed us to have both .get
and .post
with different types in the same file. The main takeaway being:
Basically whatever generics provided per handler get merged with the ones provided when creating the instance.
However with v1 this no longer seems to be the case? Am I missing something or perhaps this can be accomplished a different way?
this should be cosidered, I found this a helpfull and desirable feature, pls add this support on future updates