Good night everyone, I'm working on a NestJs project, attempting to use a custom validator which requires using a repository. Right now the repository is undefined when I call the validate method, I don't finish to understand decorators and frankly a big part of NestJs/Typescript as well...
These are my current call to the validation method:
@IsString()
@Matches(/^([a-zA-Z0-9 _-]+)$/, {
message:
'Please use only letters, numbers, - symbol, or _ symbol when creating a username',
})
@UsernameAlreadyExists({
message: 'Username $value already exist, please choose another username.',
})
username: string;
And this is my definition of the Validator Class extending ValidatorConstraintInterface:
registerDecorator,
ValidationOptions,
ValidatorConstraint,
ValidatorConstraintInterface,
ValidationArguments,
} from 'class-validator';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { User } from './user.entity';
@ValidatorConstraint({ async: true })
export class UsernameAlreadyExistsConstraint
implements ValidatorConstraintInterface
{
constructor(
@InjectRepository(User)
private userRepository: Repository<User>,
) {}
validate(userName: any, args: ValidationArguments) {
console.log(userName, this.userRepository, this);
return this.userRepository
.findOneBy({ username: userName })
.then((user) => {
if (user) return false;
return true;
});
}
}
export function UsernameAlreadyExists(validationOptions?: ValidationOptions) {
return function (object: unknown, propertyName: string) {
registerDecorator({
target: object.constructor,
propertyName: propertyName,
options: validationOptions,
constraints: [],
validator: UsernameAlreadyExistsConstraint,
});
};
}
I can't understand the reason for it to not be working, I wasn't able to find solutions other than deprecated (it seems to me at least) solutions like using
useContainer(app, { fallback: true });
Which, anyways, did not solve my issue
Thank you guys :)