-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathis-unique-constraint.decorator.ts
More file actions
48 lines (41 loc) · 1.41 KB
/
Copy pathis-unique-constraint.decorator.ts
File metadata and controls
48 lines (41 loc) · 1.41 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
import {
registerDecorator,
ValidatorConstraint,
ValidatorConstraintInterface,
ValidationArguments,
ValidationOptions,
} from 'class-validator';
import { PrismaService } from 'nestjs-prisma';
import { Injectable, BadRequestException } from '@nestjs/common';
import { DatabaseService } from './../database/database.service';
// const swap = await this.databaseService.position.findFirst({
@ValidatorConstraint({ name: 'isUnique', async: true })
@Injectable()
export class IsUniqueConstraint implements ValidatorConstraintInterface {
constructor(
private readonly databaseService: DatabaseService,
private prisma: PrismaService
) {}
async validate(value: string, args: ValidationArguments) {
const [entity, column] = args.constraints;
const result = await this.prisma.$queryRawUnsafe(`SELECT * FROM $1 WHERE $2 = $3 WHERE LIMIT 1`, entity, column, value);
if (result) {
return false;
}
return true;
}
defaultMessage(args: ValidationArguments) {
return `"${args.value}" already exists for ${args.constraints[1]}`;
}
}
export function IsUnique(entity: { new (): any }, column: string, validationOptions?: ValidationOptions) {
return (object: object, propertyName: string) => {
registerDecorator({
target: object.constructor,
propertyName,
options: validationOptions,
constraints: [entity, column],
validator: IsUniqueConstraint,
});
};
}