mirror of
https://github.com/ershisan99/flashcards-api.git
synced 2025-12-16 12:33:17 +00:00
38 lines
1019 B
TypeScript
38 lines
1019 B
TypeScript
import { BadRequestException, INestApplication, ValidationPipe } from '@nestjs/common'
|
|
import { ValidationError } from 'class-validator'
|
|
|
|
export const validationErrorsMapper = {
|
|
mapValidationErrorArrayToValidationPipeErrorTypeArray(
|
|
errors: ValidationError[]
|
|
): ValidationPipeErrorType[] {
|
|
return errors.flatMap(error => {
|
|
const constraints = error.constraints ?? []
|
|
return Object.entries(constraints).map(([_, value]) => ({
|
|
field: error.property,
|
|
message: value,
|
|
}))
|
|
})
|
|
},
|
|
}
|
|
|
|
export function pipesSetup(app: INestApplication) {
|
|
app.useGlobalPipes(
|
|
new ValidationPipe({
|
|
whitelist: true,
|
|
transform: true,
|
|
|
|
stopAtFirstError: true,
|
|
exceptionFactory: (errors: ValidationError[]) => {
|
|
const err =
|
|
validationErrorsMapper.mapValidationErrorArrayToValidationPipeErrorTypeArray(errors)
|
|
throw new BadRequestException(err)
|
|
},
|
|
})
|
|
)
|
|
}
|
|
|
|
export type ValidationPipeErrorType = {
|
|
field: string
|
|
message: string
|
|
}
|