Reputation: 11
I'm trying to create an auto-check in nest js for the existence of a record in a prisma database using a validator class. I currently have the following code:
interface UniqueValidatorOptions {
model: string;
field: string;
}
@ValidatorConstraint({ name: 'UniqueValidator', async: true })
@Injectable()
export class UniqueValidator implements ValidatorConstraintInterface {
constructor(
@Inject(PrismaService)
private readonly prismaService: PrismaService,
) {}
async validate(value: any, info: ValidationArguments) {
console.log(info);
const modelOptions: UniqueValidatorOptions = info.constraints[0];
if (!modelOptions) {
throw new Error('Model options are not provided.');
}
const { model, field } = modelOptions;
try {
const result = await this.prismaService[model].findFirst({
where: {
[field]: value,
},
});
return !result;
} catch (e) {
console.log(e);
return false;
}
}
defaultMessage() {
return ErrorsEnum.NOT_FOUND_USER;
}
}
When I try to use it I get an error: TypeError: Cannot read properties of undefined (reading 'user') at UniqueValidator.validate (C:\Users\grema\OneDrive\Рабочий стол\print studio\ps-core\src\common\is.exist.validator.ts:34:46)
This is how I call the validator:
export class UsersBaseDto {
@Validate(UniqueValidator, [{ model: 'user', field: 'id' }])
id: number;
}
Tell me how can I fix this error? I couldn't find a solution on my own
Upvotes: 1
Views: 33