Reputation: 2664
I'm trying to write a custom validation decorator that would prohibit a user from creating an entry with the same title within a single category/subcategory. In order to do that, I'm going to use the class-validator library and write a decorator like this:
@ValidatorConstraint({ name: 'isUniqueEntryTitle', async: true })
@Injectable()
export class IsUniqueEntryTitle implements ValidatorConstraintInterface {
constructor(
private readonly userService: UserService,
) {}
public async validate(val: any, args: ValidationArguments): Promise<boolean> {
return true;
}
public defaultMessage(args: ValidationArguments): string {
return `Entry with such title already exists in this folder`;
}
}
The problem with this is that, I will have to make a pretty complex DB query to check whether an entry with such a title is already in the DB or not. One of the parameters, that I need to know is obviously a user id, the user id can be retrieved from the user jwt token but how do I access it inside this class? That's the problem I'm having right now.
Upvotes: 2
Views: 1435
Reputation: 1703
You can try to set your validator as Request scoped injectable (link on documentation).
This approach allows you inject Request instance to validator and access to user through it.
Briefly it will look like
import { REQUEST } from '@nestjs/core';
@ValidatorConstraint({ name: 'isUniqueEntryTitle', async: true })
@Injectable({ scope: Scope.REQUEST })
export class IsUniqueEntryTitle implements ValidatorConstraintInterface {
constructor(
private readonly userService: UserService,
@Inject(REQUEST) private request: Request
) {}
public async validate(val: any, args: ValidationArguments): Promise<boolean> {
return true;
}
public defaultMessage(args: ValidationArguments): string {
return `Entry with such title already exists in this folder`;
}
}
Upvotes: 4
Reputation: 2997
I didn't get what exactly you need. but to make it easy for you, you use this module nestjs-dbvalidator to check if the colmun is unique or exist
Upvotes: 0