|
| 1 | +import { Injectable } from '@nestjs/common' |
| 2 | +import { InjectConnection } from '@nestjs/mongoose' |
| 3 | +import { |
| 4 | + ValidationArguments, |
| 5 | + ValidationOptions, |
| 6 | + ValidatorConstraint, |
| 7 | + ValidatorConstraintInterface, |
| 8 | + registerDecorator, |
| 9 | +} from 'class-validator' |
| 10 | +import { Connection } from 'mongoose' |
| 11 | +import { get } from 'radash' |
| 12 | + |
| 13 | +@ValidatorConstraint({ name: 'UniquenessMailValidator', async: true }) |
| 14 | +@Injectable() |
| 15 | +export class UniquenessMailValidator implements ValidatorConstraintInterface { |
| 16 | + public constructor(@InjectConnection() private connection: Connection) { } |
| 17 | + public async validate( |
| 18 | + value: any, |
| 19 | + args?: ValidationArguments |
| 20 | + ): Promise<boolean> { |
| 21 | + for (const contraint of args.constraints) { |
| 22 | + const $ne = get(args.object, contraint.primaryKey) |
| 23 | + const val = get(value, contraint.key) |
| 24 | + const count = await this.connection.collection(contraint.collection).countDocuments({ |
| 25 | + [contraint.primaryKey]: { $ne }, |
| 26 | + [contraint.key]: val, |
| 27 | + }) |
| 28 | + |
| 29 | + console.log('count', count) |
| 30 | + console.log('debug', { |
| 31 | + [contraint.primaryKey]: { $ne }, |
| 32 | + [contraint.key]: val, |
| 33 | + }) |
| 34 | + |
| 35 | + if (count > 0) { |
| 36 | + return false |
| 37 | + } |
| 38 | + } |
| 39 | + |
| 40 | + return true |
| 41 | + } |
| 42 | + |
| 43 | + defaultMessage(validationArguments?: ValidationArguments): string { |
| 44 | + // return custom field message |
| 45 | + const field: string = validationArguments.property |
| 46 | + return `${field} is already exist` |
| 47 | + } |
| 48 | +} |
| 49 | + |
| 50 | +export type UniquenessMailInterface = { |
| 51 | + collection: string |
| 52 | + primaryKey: string |
| 53 | + key: string |
| 54 | +} |
| 55 | + |
| 56 | +export function isUnique(options: UniquenessMailInterface, validationOptions?: ValidationOptions) { |
| 57 | + return function (object: any, propertyName: string) { |
| 58 | + registerDecorator({ |
| 59 | + name: 'isUnique', |
| 60 | + target: object.constructor, |
| 61 | + propertyName: propertyName, |
| 62 | + options: validationOptions, |
| 63 | + constraints: [options], |
| 64 | + validator: UniquenessMailValidator, |
| 65 | + }) |
| 66 | + } |
| 67 | +} |
0 commit comments