Last active
July 23, 2022 15:01
-
-
Save ramirezsandin/02d3384a8fe1e4a200828199b3d49306 to your computer and use it in GitHub Desktop.
Validation Pipe for Yup & NestJS
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
// NestJS documentation on schema pipes: | |
// https://docs.nestjs.com/pipes#schema-based-validation | |
import { ArgumentMetadata, BadRequestException, Injectable, PipeTransform } from '@nestjs/common'; | |
import { SchemaOf, ValidationError } from 'yup'; | |
@Injectable() | |
export class YupValidationPripe<T> implements PipeTransform { | |
constructor(private schema: SchemaOf<T>) {} | |
transform(value: T, _: ArgumentMetadata) { | |
try { | |
const validValue = this.schema.defined().validateSync(value, { | |
stripUnknown: true, | |
abortEarly: false, | |
}); | |
return validValue; | |
} catch (err) { | |
if (err instanceof ValidationError) { | |
throw new BadRequestException( | |
err.errors, | |
`The data received doesn't meet the requirements.`, | |
); | |
} | |
throw err; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment