Enable validation
This commit is contained in:
parent
ab5bb50d7b
commit
fd2f2091ee
1 changed files with 27 additions and 1 deletions
28
src/main.ts
28
src/main.ts
|
|
@ -1,6 +1,7 @@
|
||||||
import { NestFactory } from '@nestjs/core';
|
import { NestFactory } from '@nestjs/core';
|
||||||
import { AppModule } from './app.module';
|
import { AppModule } from './app.module';
|
||||||
import { Logger } from '@nestjs/common';
|
import { BadRequestException, Logger, ValidationPipe } from '@nestjs/common';
|
||||||
|
import { ValidationError } from 'class-validator';
|
||||||
|
|
||||||
async function bootstrap() {
|
async function bootstrap() {
|
||||||
const app = await NestFactory.create(AppModule);
|
const app = await NestFactory.create(AppModule);
|
||||||
|
|
@ -17,6 +18,31 @@ async function bootstrap() {
|
||||||
credentials: true,
|
credentials: true,
|
||||||
origin,
|
origin,
|
||||||
});
|
});
|
||||||
|
app.useGlobalPipes(
|
||||||
|
new ValidationPipe({
|
||||||
|
transform: true,
|
||||||
|
// https://stackoverflow.com/questions/75581669/customize-error-message-in-nest-js-using-class-validator
|
||||||
|
exceptionFactory: (validationErrors: ValidationError[] = []) => {
|
||||||
|
const errors = validationErrors.map((error) => ({
|
||||||
|
error: Object.values(error.constraints).join(', '),
|
||||||
|
}));
|
||||||
|
|
||||||
|
let errorMessage: string;
|
||||||
|
errors.forEach((value, index) => {
|
||||||
|
if (index == 0) {
|
||||||
|
errorMessage = value.error;
|
||||||
|
} else {
|
||||||
|
errorMessage = errorMessage.concat(', ', value.error);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
return new BadRequestException({
|
||||||
|
status: 'Validation Error',
|
||||||
|
message: errorMessage,
|
||||||
|
});
|
||||||
|
},
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
|
||||||
await app.listen(process.env.PORT);
|
await app.listen(process.env.PORT);
|
||||||
}
|
}
|
||||||
|
|
|
||||||
Loading…
Add table
Add a link
Reference in a new issue