Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Defining custom properties/types per handler in v1? #235

Open
codsane opened this issue Aug 25, 2023 · 1 comment
Open

Defining custom properties/types per handler in v1? #235

codsane opened this issue Aug 25, 2023 · 1 comment

Comments

@codsane
Copy link

codsane commented Aug 25, 2023

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 and res (such as req.user or res.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 #124 (comment):

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?

@AlanDiazCochair
Copy link

this should be cosidered, I found this a helpfull and desirable feature, pls add this support on future updates

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants