Created
December 7, 2022 10:56
-
-
Save mahkassem/bd9e0ec510585ef93ecf45600b424251 to your computer and use it in GitHub Desktop.
Nestjs - Unique Constraints Class-Validator Decorator
This file contains hidden or 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 { | |
| ValidatorConstraint, | |
| ValidatorConstraintInterface, | |
| ValidationArguments, | |
| registerDecorator, | |
| ValidationOptions, | |
| } from 'class-validator'; | |
| import { DataSource } from 'typeorm'; | |
| @ValidatorConstraint({ async: true }) | |
| export class isUnique implements ValidatorConstraintInterface { | |
| constructor(private readonly dataSource: DataSource) { } | |
| async validate(value: any, args: ValidationArguments) { | |
| const [entityName, exceptField = null] = args.constraints; | |
| const [property] = args.property.split('.'); | |
| const entity = this.dataSource.manager.getRepository(entityName); | |
| console.log('args', args); | |
| const result = await entity.findOne({ where: { [property]: value } }); | |
| if (!result) return true; | |
| // except field | |
| if (!exceptField) return false; | |
| const exceptFieldValue = (args.object as any)[exceptField]; | |
| if (!exceptFieldValue) return false; | |
| return result[exceptField] === exceptFieldValue; | |
| } | |
| defaultMessage(args: ValidationArguments) { | |
| const [entityName] = args.constraints; | |
| return `${args.property} alread exists in ${entityName}!`; | |
| } | |
| } | |
| export function Unique( | |
| entityName: string, | |
| exceptField: string = null, | |
| validationOptions?: ValidationOptions) { | |
| return function (object: unknown, propertyName: string) { | |
| registerDecorator({ | |
| target: object.constructor, | |
| propertyName: propertyName, | |
| options: validationOptions, | |
| constraints: [entityName, exceptField], | |
| validator: isUnique, | |
| }); | |
| }; | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment