Skip to content

Instantly share code, notes, and snippets.

@ramirezsandin
Last active July 23, 2022 15:01
Show Gist options
  • Save ramirezsandin/02d3384a8fe1e4a200828199b3d49306 to your computer and use it in GitHub Desktop.
Save ramirezsandin/02d3384a8fe1e4a200828199b3d49306 to your computer and use it in GitHub Desktop.
Validation Pipe for Yup & NestJS
// 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