简体   繁体   中英

difference between two ways of applying validation pipe to nest.js

I found the code to apply validation pipe in nest.js. There are two different ways to apply validation pipe globally. I can't figure out the difference between those. What is it? Thanks in advance.

method 1

// app.module.ts

import { APP_PIPE } from '@nestjs/core';

// ...

@Module({
  controllers: [AppController],
  providers: [
    // here --------
    {
      provide: APP_PIPE,
      useValue: new ValidationPipe({}),
    },
  ]
})
export class AppModule implements NestModule {
  configure(consumer: MiddlewareConsumer): void {
    consumer.apply(LoggerMiddleware).forRoutes('*');
  }
}

method 2

// https://docs.nestjs.com/techniques/validation#auto-validation

// main.ts

async function bootstrap() {
  const app = await NestFactory.create(AppModule); 
  app.useGlobalPipes(new ValidationPipe({})); // here --------
  await app.listen(3000);
}
bootstrap();

When we are applying a global validation pipe in main.ts we bind the validation pipe throughout the application. But it does miss out on the modules registered from outside the context of the application. On the other hand, when we apply a validation pipe in the module scope the pipe binds on only the routes for that module. This becomes pretty useful when you want to bind specific pipes to a module.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM