instantcommerce / next-api-decorators

Collection of decorators to create typed Next.js API routes, with easy request validation and transformation.
https://next-api-decorators.vercel.app
MIT License
409 stars 29 forks source link

Is it possbile to change or access decorator variables? #538

Closed fendyk closed 1 year ago

fendyk commented 1 year ago

Let's say I have a list function like this:

@Get()
async list() {
    await db.users.findMany();
}

And now, I need to add a header with 'X-total-Count'. How would I approach this using a decorator? For example, I currently use the following:

@Get()
async list(@Res() res: NextApiResponse) {
    const items = await db.user.findMany();
    setTotalCountHeader(res, items.length) // translates to: res.setHeader('X-Total-Count', amount)
    return items;
}

This is a workaround and it works as aspected, but could I use it with a decorator? The only thing I can think of is the following:

@Get()
@SetHeader('X-Total-Count', '2') // Value needs to be pulled from somewhere in the function below
async list(@Res() res: NextApiResponse) {
    const items = await db.user.findMany();
    return items;
}

Is this just not possbile with decorators? Let me know, thanks!