BE/src/main.ts
2025-03-31 11:29:15 +05:30

82 lines
2.5 KiB
TypeScript

import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';
import { BadRequestException, ValidationError, ValidationPipe } from '@nestjs/common';
import { SwaggerModule, DocumentBuilder } from '@nestjs/swagger';
import { SwaggerDocumentOptions } from '@nestjs/swagger';
async function bootstrap() {
const app = await NestFactory.create(AppModule, {
cors: {
"origin": "*",
"methods": "GET,HEAD,PUT,PATCH,POST,DELETE",
"preflightContinue": false,
"optionsSuccessStatus": 204
}
});
function extractConstraints(validationErrors: ValidationError[]) {
const constraints: { [key: string]: string }[] = [];
function traverse(errors: ValidationError[]) {
// console.log(errors);
// console.log("--------------");
for (const error of errors) {
// If the error has constraints, add them to the list
// console.log(error);
// console.log("--------------");
if (error.constraints) {
constraints.push(error.constraints);
}
// // If there are children, recursively traverse them
if (error.children && error.children.length > 0) {
traverse(error.children);
}
}
}
traverse(validationErrors);
return constraints;
}
const customExceptionFactory = (validationErrors: ValidationError[]) => {
let res = extractConstraints(validationErrors);
let newResult = res.map(x => {
const errorMessage = x[Object.keys(x)[0]];
return { message: errorMessage };
}).filter(Boolean);
return new BadRequestException({ message: 'Validation failed', errors: newResult });
};
app.useGlobalPipes(new ValidationPipe({
transform: true,
exceptionFactory: customExceptionFactory,
whitelist: true,
stopAtFirstError: true,
forbidNonWhitelisted: true,
}));
// app.useGlobalPipes(new ValidationPipe({ exceptionFactory:customExceptionFactory, whitelist: true, forbidNonWhitelisted: true, transform: true }));
const config = new DocumentBuilder()
.setTitle('API')
.setDescription('API description')
.setVersion('1.0')
.addServer("http://localhost:3000", "Development Server 1")
.addServer("https://dev.alphaomegainfosys.com/test-api", "Development Server 2")
.build();
const options: SwaggerDocumentOptions = {
autoTagControllers: false,
};
const documentFactory = () => SwaggerModule.createDocument(app, config, options);
SwaggerModule.setup('api', app, documentFactory);
await app.listen(process.env.PORT ?? 3000);
}
bootstrap();