Last active
May 4, 2024 01:10
-
-
Save illusi03/03bf943a0dd958b1771c239430da4833 to your computer and use it in GitHub Desktop.
Article Medium - Enhanced validation in Nest.js - STEP-5
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 { Type } from 'class-transformer'; | |
import { IsEmail, IsNotEmpty, ValidateNested } from 'class-validator'; | |
class AddressCustomerType { | |
@IsNotEmpty() | |
city: string; | |
@IsNotEmpty() | |
address: string; | |
} | |
export class CreateCustomerDto { | |
@IsNotEmpty() | |
@IsEmail() | |
email: string; | |
@IsNotEmpty() | |
password: string; | |
@IsNotEmpty() | |
@ValidateNested() | |
@Type(() => AddressCustomerType) | |
address: AddressCustomerType; | |
} |
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
export const exceptionFactory = (errors: ValidationError[]) => { | |
const errorValidation = {}; | |
let errorMessages = []; | |
const parseErrorMessage = (errObject, propertyKey) => { | |
const isNested = | |
typeof errObject?.children !== 'undefined' && | |
errObject?.children.length > 0; | |
if (!isNested) { | |
const messages = Object.values(errObject?.constraints); | |
errorValidation[`${propertyKey}`] = [...messages]; | |
errorMessages.push(messages); // Default property message error | |
return true; | |
} | |
errObject?.children.map((valChild) => { | |
const nextPropertyKey = `${propertyKey}.${valChild.property}`; | |
parseErrorMessage(valChild, nextPropertyKey); | |
}); | |
}; | |
errors.forEach((err) => { | |
parseErrorMessage(err, err.property); | |
}); | |
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