Created
May 4, 2024 00:03
-
-
Save illusi03/143e9ec603564f2c0ec1d634efe6df15 to your computer and use it in GitHub Desktop.
Article Medium - Enhanced validation in Nest.js - STEP-4
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { NestFactory } from '@nestjs/core'; | |
import { AppModule } from './app.module'; | |
import { ValidationPipe } from '@nestjs/common'; | |
import { | |
ValidationFilter, | |
exceptionFactory, | |
} from './exceptions/validation.filter'; | |
async function bootstrap() { | |
const app = await NestFactory.create(AppModule); | |
app.useGlobalPipes(new ValidationPipe()); | |
app.useGlobalFilters(new ValidationFilter()); | |
app.useGlobalPipes( | |
new ValidationPipe({ | |
skipMissingProperties: false, // If Null/Undefined Value , still validated | |
transform: true, // Transform plain object to DTO Type/Classes | |
exceptionFactory, | |
}), | |
); | |
await app.listen(3000); | |
} | |
bootstrap(); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { | |
ArgumentsHost, | |
BadRequestException, | |
Catch, | |
ExceptionFilter, | |
ValidationError, | |
} from '@nestjs/common'; | |
export class ValidationException extends BadRequestException { | |
public messageErrors; | |
public validationErrors; | |
constructor(validationErrors: any, messageErrors?: any) { | |
super(); | |
this.messageErrors = messageErrors; | |
this.validationErrors = validationErrors; | |
} | |
} | |
@Catch(ValidationException) | |
export class ValidationFilter implements ExceptionFilter { | |
catch(exception: ValidationException, host: ArgumentsHost): any { | |
const ctx = host.switchToHttp(); | |
const response = ctx.getResponse(); | |
return response.status(400).json({ | |
message: exception.messageErrors, | |
error: 'Bad Request', | |
statusCode: 400, | |
data: exception.validationErrors, | |
}); | |
} | |
} | |
export const exceptionFactory = (errors: ValidationError[]) => { | |
const errorValidation = {}; | |
let errorMessages = []; | |
const parseErrorMessage = (errObject) => { | |
const propertyKey = errObject.property; | |
const messages = Object.values(errObject?.constraints); | |
errorValidation[`${propertyKey}`] = [...messages]; | |
errorMessages.push(messages); // Default property message error | |
return true; | |
}; | |
errors.forEach((err) => { | |
parseErrorMessage(err); | |
}); | |
errorMessages = errorMessages.flat(1); // Default property message error | |
return new ValidationException(errorValidation, errorMessages); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment