It is not possible to access the database through the validator Nest JS

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

Answers (1)

sabadoryo
sabadoryo

Reputation: 61

Might be related to this. Need to add a useContainer() into your main file.

Upvotes: 0

Related Questions