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

Unclear how to pass options to the ValidationPipe #563

Closed stefanoborini closed 1 year ago

stefanoborini commented 1 year ago

From the documentation, it's unclear how you are supposed to pass validation pipe configuration options. I am trying to prevent the received document to pass validation when it contains keys that I don't expect. Example


class CreateProductInput {
  @IsNotEmpty()
  url: string | undefined;
}

class ProductHandler {
  @Post()
  @HttpCode(201)
  public async create_product(@Body(new ValidationPipe(options = {forbidNonWhitelisted: true, forbidUnknownValues: true})) body: CreateProductInput) {
}
}

The above code does not work: error - ReferenceError: options is not defined.

I also tried without new, with no result:

public async create_product(@Body(ValidationPipe({forbidNonWhitelisted: true, forbidUnknownValues: true})) body: CreateProductInput) {

The type hinting seems to say I should pass the options at construction:

(alias) ValidationPipe(options?: ValidationPipeOptions | undefined): ParameterPipe<any, unknown>
stefanoborini commented 1 year ago

Moreover, how can one set it globally for all validations?

ggurkal commented 1 year ago

Hi @stefanoborini

Your second example is the correct one:

public async create_product(@Body(ValidationPipe({ forbidNonWhitelisted: true, forbidUnknownValues: true })) body: CreateProductInput) {

The fact that it doesn't work is most probably not related to next-api-decorators but how you construct your class and how you configure class-validator and/or class-transformer.

If you are sure the problem is related to next-api-decorators, please provide a minimum reproducible repo and feel free to reopen the issue.


Moreover, how can one set it globally for all validations?

Unfortunately it's not possible to set validation options globally, as Next.js handles the routing. Your safest bet would be assigning the options to a global variable and pass it to each ValidationPipe instance.