@nestjs/common#ValidationPipe TypeScript Examples
The following examples show how to use
@nestjs/common#ValidationPipe.
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: test_utils.ts From nestjs-angular-starter with MIT License | 7 votes |
/**
* Returns an already existing instance of nest app, or creates a new one
* which will be used for other tests as well.
*/
export async function getNestApp(): Promise<INestApplication> {
if (nestApp) return nestApp;
const moduleFixture: TestingModule = await Test.createTestingModule({
imports: [AppModule],
}).compile();
nestApp = moduleFixture.createNestApplication();
// Add validation and transform pipe
nestApp.useGlobalPipes(
new ValidationPipe({
transform: true,
}),
);
await nestApp.init();
return nestApp;
}
Example #2
Source File: main.ts From nestjs-api-example with MIT License | 6 votes |
async function bootstrap() {
const app = await NestFactory.create(AppModule);
const configService = app.get<ConfigService>(ConfigService);
app.useGlobalPipes(
new ValidationPipe({
transform: true,
whitelist: true,
}),
);
app.use(helmet());
app.enableCors();
setupSwagger(app);
const port = configService.get('APP_PORT');
await app.listen(port);
console.info(`Server listening on port ${port}`);
}
Example #3
Source File: _main.ts From nest-js-boilerplate with MIT License | 6 votes |
async function bootstrap() {
const app = await NestFactory.create(AppModule);
app.useGlobalPipes(new ValidationPipe({
exceptionFactory: (errors: ValidationError[]) => new ValidationExceptions(errors),
}));
app.useGlobalFilters(new AllExceptionsFilter());
const configService = app.get(ConfigService);
const port = configService.get<number>('SERVER_POR') || 3000;
const options = new DocumentBuilder()
.setTitle('Api v1')
.setDescription('The boilerplate API for nestjs devs')
.setVersion('1.0')
.addBearerAuth({ in: 'header', type: 'http' })
.build();
const document = SwaggerModule.createDocument(app, options);
SwaggerModule.setup('api', app, document);
await app.listen(port, async () => {
console.log(`The server is running on ${port} port: http://localhost:${port}/api`);
});
}
Example #4
Source File: main.ts From domain-driven-hexagon with MIT License | 6 votes |
async function bootstrap(): Promise<void> {
const app = await NestFactory.create(AppModule);
const options = new DocumentBuilder().build();
const document = SwaggerModule.createDocument(app, options);
SwaggerModule.setup('docs', app, document);
app.useGlobalPipes(new ValidationPipe());
app.useGlobalInterceptors(new ExceptionInterceptor());
app.enableShutdownHooks();
await app.listen(3000);
}
Example #5
Source File: account.controller.ts From uniauth-backend with MIT License | 6 votes |
/**
* OAUTH FLOW HANDLERS :: Displayed only when invoded mid-way auth flow
*/
/**
* to display login form on client-initiated-auth
*/
@Get('o/login')
@UsePipes(
new ValidationPipe({
disableErrorMessages: false,
}),
)
async showLoginPageAsAuth(@Res() res: Response, @Query() incomingAuthDto: IncomingAuthDto) {
const { client_id } = incomingAuthDto;
try {
const applicationDetails = await this.accountService.validateAccessRequest(incomingAuthDto);
return res.render('account/o/login', { app: applicationDetails, project_name: appData.Name });
} catch (e) {
this.logger.error(`${e.message} for ${client_id}`);
return res.render('error', e.response);
}
}
Example #6
Source File: app.utils.ts From nest-js-quiz-manager with MIT License | 6 votes |
VALIDATION_PIPE = new ValidationPipe({
errorHttpStatusCode: HttpStatus.UNPROCESSABLE_ENTITY,
})
Example #7
Source File: main.ts From amplication with Apache License 2.0 | 6 votes |
async function main() {
const app = await NestFactory.create(AppModule, { cors: true });
app.setGlobalPrefix("api");
app.useGlobalPipes(
new ValidationPipe({
transform: true,
})
);
const document = SwaggerModule.createDocument(app, swaggerDocumentOptions);
/** check if there is Public decorator for each path (action) and its method (findMany / findOne) on each controller */
Object.values((document as OpenAPIObject).paths).forEach((path: any) => {
Object.values(path).forEach((method: any) => {
if (
Array.isArray(method.security) &&
method.security.includes("isPublic")
) {
method.security = [];
}
});
});
SwaggerModule.setup(swaggerPath, app, document, swaggerSetupOptions);
void app.listen(PORT);
return app;
}
Example #8
Source File: global-validation.pipe.ts From aqualink-app with MIT License | 6 votes |
/**
* Custom Validation pipe that extends the options available for the global validation pipe. This is needed to allow
* for things like overriding auto transforms.
*/
@Injectable()
export class GlobalValidationPipe extends ValidationPipe {
skipTransformIds: string[];
constructor(options?: ValidationPipeOptions & CustomOptions) {
super(options);
this.skipTransformIds = (options && options.skipTransformIds) || [];
}
async transform(value: any, metadata: ArgumentMetadata) {
const originalTransform = this.isTransformEnabled;
// Check if we should skip transforms for this param
if (
metadata &&
metadata.type === 'param' &&
metadata.data &&
this.skipTransformIds.includes(metadata.data)
) {
this.isTransformEnabled = false;
}
try {
return super.transform(value, metadata);
} finally {
this.isTransformEnabled = originalTransform;
}
}
}
Example #9
Source File: main.ts From nestjs-crud-prisma with MIT License | 6 votes |
(async () => {
const app = await NestFactory.create<NestExpressApplication>(AppModule, {
bodyParser: true
});
app.setBaseViewsDir(path.resolve(rootPath, 'views'));
app.setViewEngine('ejs');
app.useGlobalPipes(new ValidationPipe());
app.useStaticAssets(path.resolve(rootPath, 'public'));
app.useGlobalFilters(new HttpExceptionFilter());
if (env.SWAGGER === '1') {
const options = new DocumentBuilder()
.setTitle(pkg.name)
.setDescription(pkg.description)
.setVersion('1.0')
.build();
const document = SwaggerModule.createDocument(app, options);
SwaggerModule.setup('api', app, document);
}
if (env.CORS === '1') app.enableCors();
await app
.listen(await getPort({ port: Number(env.PORT || 3000) }))
.catch(logger.error);
if (module.hot) {
module.hot.accept();
module.hot.dispose(() => app.close());
}
})();
Example #10
Source File: main.ts From edu-server with MIT License | 6 votes |
async function bootstrap() {
const app = await NestFactory.create(AppModule);
// setup swagger-ui
const document = SwaggerModule.createDocument(app, swaggerConfig);
SwaggerModule.setup('api', app, document, customOptions);
// Firebase Initialisation
admin.initializeApp(firebaseAccountCredentials);
app.enableCors();
app.use(helmet());
// The Cors handling middleware
app.use((req: Request, res: Response, next: NextFunction) => {
res.set('Access-Control-Allow-Origin', '*');
res.set('Access-Control-Allow-Headers', '*');
res.set('Access-Control-Allow-Methods', '*');
if (req.method === 'OPTIONS') {
res.status(200).end();
return;
}
next();
});
app.useGlobalPipes(new ValidationPipe());
const PORT = process.env.PORT || 5000;
await app.listen(PORT);
console.log('App is listening on port:', PORT);
}
Example #11
Source File: test.controller.ts From nestjs-form-data with MIT License | 6 votes |
@Post('single-file')
@UsePipes(ValidationPipe)
@FormDataRequest()
@HttpCode(HttpStatus.OK)
uploadSingleFile(@Body() singleFileDto: UploadSingleFileDto) {
return {
filename: singleFileDto.file.originalName,
mimetype: singleFileDto.file.mimetype,
};
}
Example #12
Source File: main.ts From nestjs-rest-sample with GNU General Public License v3.0 | 6 votes |
async function bootstrap() {
const app = await NestFactory.create(AppModule);
// enable shutdown hooks explicitly.
app.enableShutdownHooks();
app.useGlobalPipes(new ValidationPipe());
app.enableCors();
//app.useLogger();
await app.listen(3000);
}
Example #13
Source File: index.ts From aws-nestjs-starter with The Unlicense | 6 votes |
bootstrapServer = async (): Promise<Handler> => {
const expressApp = express();
const app = await NestFactory.create(
AppModule,
new ExpressAdapter(expressApp),
);
app.useGlobalPipes(new ValidationPipe({ forbidUnknownValues: true }));
app.enableCors();
await app.init();
return serverlessExpress({
app: expressApp,
});
}
Example #14
Source File: main.ts From pandaid with MIT License | 6 votes |
async function bootstrap() {
const app = await NestFactory.create(AppModule, {
logger: new PinoLoggerService(logger)
})
app.setGlobalPrefix('api')
app.enableCors() // TODO remove for production
app.useGlobalPipes(new ValidationPipe({ whitelist: true, forbidNonWhitelisted: true }))
const options = new DocumentBuilder()
.setTitle('PandAid')
.setDescription('The PandAid API description')
.setVersion('1.0')
.addBearerAuth()
.build()
const document = SwaggerModule.createDocument(app, options)
SwaggerModule.setup('swagger', app, document)
const port = process.env.PORT || 3001
logger.info(`Listening on port ${port}`)
await app.listen(port)
}
Example #15
Source File: main.ts From life-helper-backend with MIT License | 6 votes |
async function bootstrap() {
const app = await NestFactory.create<NestExpressApplication>(AppModule, { cors: true })
// 添加全局自动验证管道
app.useGlobalPipes(
new ValidationPipe({
/** 负载对象自动转换 */
transform: true,
transformOptions: { enableImplicitConversion: true },
/** 自动过滤未知参数 */
whitelist: true,
})
)
// 关闭 `ETag` 响应头
app.set('etag', false)
// 设置反向代理,获取客户端 IP 地址
app.set('trust proxy', PROXY_NUMBER)
// 关闭 `X-Powered-By` 响应头
app.set('x-powered-by', false)
// 挂载 Swagger 插件
setupSwagger(app)
await app.listen(PORT, '0.0.0.0')
}
Example #16
Source File: blocks.controller.ts From ironfish-api with Mozilla Public License 2.0 | 6 votes |
@ApiExcludeEndpoint()
@Post()
@UseGuards(ApiKeyGuard)
async bulkUpsert(
@Body(
new ValidationPipe({
errorHttpStatusCode: HttpStatus.UNPROCESSABLE_ENTITY,
transform: true,
}),
)
upsertBlocksDto: UpsertBlocksDto,
): Promise<List<SerializedBlock>> {
const blocks = await this.blocksTransactionsLoader.bulkUpsert(
upsertBlocksDto,
);
return {
object: 'list',
data: blocks.map((block) =>
serializedBlockFromRecordWithTransactions(block),
),
};
}
Example #17
Source File: main.ts From coronatest with GNU Affero General Public License v3.0 | 6 votes |
async function bootstrap() {
const app = await NestFactory.create<NestExpressApplication>(AppModule);
const options = new DocumentBuilder()
.setTitle('Coronatest')
.setDescription('Coronatest API')
.setVersion('1.0')
.addBearerAuth()
.build();
const document = SwaggerModule.createDocument(app, options);
SwaggerModule.setup('docs', app, document);
app.disable('x-powered-by');
app.useGlobalPipes(new ValidationPipe({ whitelist: true }));
app.enableCors({
origin: true,
credentials: true
});
app.setGlobalPrefix('api');
await app.listen(3000);
}
Example #18
Source File: admins.controller.ts From mamori-i-japan-api with BSD 2-Clause "Simplified" License | 6 votes |
// TODO @yashmurty : Investigate pagination for this later.
@UsePipes(new ValidationPipe(VALIDATION_PIPE_OPTIONS))
@ApiOperation({ summary: 'Get all admin users' })
@ApiOkResponse({ type: [Admin] })
@Get('/users')
async getAdminUsers(@Request() req, @Query() query: PaginationParamsDto): Promise<Admin[]> {
const requestAdminUser: RequestAdminUser = req.user
return this.adminsService.findAllAdminUsers(requestAdminUser, query.limit, query.offset)
}
Example #19
Source File: main.ts From nestjs-starter-rest-api with MIT License | 6 votes |
async function bootstrap() {
const app = await NestFactory.create(AppModule);
app.setGlobalPrefix('api/v1');
app.useGlobalPipes(new ValidationPipe(VALIDATION_PIPE_OPTIONS));
app.use(RequestIdMiddleware);
app.enableCors();
/** Swagger configuration*/
const options = new DocumentBuilder()
.setTitle('Nestjs API starter')
.setDescription('Nestjs API description')
.setVersion('1.0')
.addBearerAuth()
.build();
const document = SwaggerModule.createDocument(app, options);
SwaggerModule.setup('swagger', app, document);
const configService = app.get(ConfigService);
const port = configService.get<number>('port');
await app.listen(port);
}
Example #20
Source File: main.ts From api with GNU Affero General Public License v3.0 | 6 votes |
void (async () => {
const options: NestApplicationOptions = {
bufferLogs: true,
}
const app = await NestFactory.create(AppModule, options)
app.useLogger(app.get(Logger))
app.useGlobalPipes(new ValidationPipe({
disableErrorMessages: false,
transform: true,
}))
app.enableCors({origin: '*'})
app.getHttpAdapter().options('*', cors())
await app.listen(process.env.PORT || 4100);
})()
Example #21
Source File: main.ts From bank-server with MIT License | 6 votes |
async function bootstrap(): Promise<void> {
initializeTransactionalContext();
patchTypeORMRepositoryWithBaseRepository();
const app = await NestFactory.create<NestExpressApplication>(
AppModule,
new ExpressAdapter(),
{ cors: true },
);
app.enable('trust proxy');
app.use(helmet());
app.use(RateLimit({ windowMs: 15 * 60 * 1000, max: 200 }));
app.use(compression());
app.use(morgan('combined'));
app.setGlobalPrefix('bank');
const reflector = app.get(Reflector);
app.useGlobalInterceptors(new ClassSerializerInterceptor(reflector));
app.useGlobalFilters(
new HttpExceptionFilter(reflector),
new QueryFailedFilter(reflector),
);
app.useGlobalPipes(
new ValidationPipe({
whitelist: true,
transform: true,
dismissDefaultMessages: true,
validationError: { target: false },
}),
);
setupSwagger(app);
const configService = app.get(ConfigService);
await app.listen(configService.get('PORT'));
}
Example #22
Source File: main.ts From MyAPI with MIT License | 6 votes |
async function bootstrap() {
const app = await NestFactory.create<NestExpressApplication>(AppModule, {
logger: process.env.NODE_ENV === PROD_ENV ? createLogger() : ['error', 'warn', 'debug']
})
// BASIC CONFIGURATION
app.useStaticAssets(join(__dirname, 'public'))
app.setBaseViewsDir(join(__dirname, 'views'))
app.setViewEngine('ejs')
// PARSE REQUESTS
app.use(urlencoded({ extended: true }))
app.use(json({
limit: '10mb'
}))
app.useGlobalPipes(
new ValidationPipe({
transform: true,
whitelist: true,
forbidNonWhitelisted: true
})
)
// SECURITY
setupSecurity(app)
// OPEN API
setupSwagger(app)
// Register the proxy’s IP address (load balancer or reverse proxy)
app.set('trust proxy', function (ip: string) {
if (ip === '127.0.0.1') return true // trusted IPs
else return false
})
await app.listen(process.env.PORT || 3000)
}
Example #23
Source File: bootstrap.ts From office-hours with GNU General Public License v3.0 | 6 votes |
// Global settings that should be true in prod and in integration tests
export function addGlobalsToApp(app: INestApplication): void {
app.useGlobalPipes(
new ValidationPipe({
whitelist: true,
forbidNonWhitelisted: true,
transform: true,
}),
);
app.useGlobalPipes(new StripUndefinedPipe());
app.use(cookieParser());
}
Example #24
Source File: main.ts From nestjs-angular-starter with MIT License | 6 votes |
async function bootstrap() {
// Create the app and allow cors and HTTPS support (if configured)
const app = await NestFactory.create(AppModule, {
cors: config.CORS_OPTIONS,
// Will work only if SSH is configured on the related environment config, if not, normal HTTP will be used
httpsOptions: getHttpsOptionsFromConfig(),
});
// Use '/api' for general prefix
app.setGlobalPrefix('api');
// Allow validation and transform of params
app.useGlobalPipes(
new ValidationPipe({
transform: true,
}),
);
// If we are running on production, mount angular
if (config.ANGULAR.MOUNT) {
// Get the express app
const expressApp = app
.getHttpAdapter()
.getInstance() as express.Application;
if (config.ANGULAR.USE_SSR) mountAngularSSR(expressApp);
else mountAngular(expressApp);
}
// Start listening
await app.listen(process.env.PORT || 3000);
}
Example #25
Source File: main.ts From tatum-blockchain-connector with MIT License | 6 votes |
(async function () {
const app = await NestFactory.create(AppModule);
app.useGlobalPipes(
new ValidationPipe({
transform: true,
forbidUnknownValues: false,
validationError: { target: true, value: true },
}),
);
await app.listen(3000);
})();
Example #26
Source File: main.ts From NextJS-NestJS-GraphQL-Starter with MIT License | 6 votes |
async function bootstrap() {
const app = await NestFactory.create(AppModule);
app.use(cookieParser());
app.use(helmet());
Sentry.init({
dsn: SENTRY_DSN,
environment: ENV,
});
app.useGlobalPipes(
new ValidationPipe({
disableErrorMessages: true,
}),
);
Logger.log(`Starting server in ${ENV} mode`);
await app.listen(5000);
}
Example #27
Source File: validation.pipe.ts From nestjs-starter with MIT License | 6 votes |
export class CustomValidationPipe extends ValidationPipe {
private readonly logger = new Logger(CustomValidationPipe.name);
public async transform(value, metadata: ArgumentMetadata) {
try {
return await super.transform(value, metadata);
} catch (e) {
if (e instanceof BadRequestException) {
const response: any = e.getResponse(); // TODO remove any
const messages = response.message
.map(message =>
message.constraints ? Object.values(message.constraints) : message,
)
.flat();
this.logger.error(JSON.stringify(messages));
throw new BadRequestException(messages);
}
}
}
}
Example #28
Source File: _mysql-main.ts From nest-js-boilerplate with MIT License | 5 votes |
async function bootstrap() {
const app = await NestFactory.create(AppModule);
const configService = app.get(ConfigService);
app.useGlobalPipes(new ValidationPipe());
app.useGlobalFilters(new AllExceptionsFilter());
app.use(
session({
secret: configService.get<string>('PASSPORT_SESSION_SECRET') as string,
resave: false,
saveUninitialized: false,
store: new MySQLStore({
host: configService.get<string>('MYSQL_HOST'),
port: configService.get<number>('MYSQL_PORT') as unknown as number,
user: configService.get<string>('MYSQL_ROOT_USER'),
password: configService.get<string>('MYSQL_PASSWORD'),
database: configService.get<string>('MYSQL_DB'),
}),
}),
);
app.use(passport.initialize());
app.use(passport.session());
const options = new DocumentBuilder()
.setTitle('Api v1')
.setDescription('The boilerplate API for nestjs devs')
.setVersion('1.0')
.addCookieAuth('connect.sid')
.build();
const document = SwaggerModule.createDocument(app, options);
SwaggerModule.setup('api', app, document);
const port = configService.get<number>('SERVER_POR') || 3000;
await app.listen(port, async () => {
console.log(`The server is running on ${port} port: http://localhost:${port}/api`);
});
}
Example #29
Source File: tag.controller.ts From whispr with MIT License | 5 votes |
@Post()
@HttpCode(201)
@UsePipes(new ValidationPipe({ whitelist: true }))
async createTag(@Body() tag: TagInputType): Promise<ITag> {
return this.tagService.create(tag);
}