Reputation: 167
I got a problem in my custom validation pipe I'm trying to verify if the id passed exist in an other table.
it telling me that it can not read property of undefined but I console log the id and you can see that its correcly console above the error message.
I've also check if my findOne works in a route and its doing find
import { Injectable } from '@nestjs/common';
import {
ValidatorConstraint,
ValidatorConstraintInterface,
} from 'class-validator';
import { ExerciceRepository } from 'src/Infrastructure/repository/exercice.repository';
@ValidatorConstraint({ name: 'ExerciceExists', async: true })
@Injectable()
export class ExerciceExistRule implements ValidatorConstraintInterface {
constructor(private exerciceRepository: ExerciceRepository) {}
async validate(value: string): Promise<boolean> {
console.log(value);
try {
const data = await this.exerciceRepository.findOne(value);
console.log(data);
if (data) return true;
else return false;
} catch (e) {
console.log(e);
return false;
}
}
defaultMessage(): string {
return 'Exercice doesnt exist';
}
}
Thank you for your repplies
Upvotes: 1
Views: 1395
Reputation: 167
I have found the solution I had to put UseContainer in the main.ts. It will allow class-validator to use NESTJS dependency injection container.
useContainer(app.select(AppModule), { fallbackOnErrors: true });
However i don't know if it's the best way to do it
Upvotes: 3
Reputation: 23937
You are reading the error message wrong. It is not telling, that value
or findOne
is undefined, but the object from which it is trying to read the property of: exerciceRepository
.
This indicates, that you did not register your ExerciceRepository
correctly.
Verify, that it has the @Injectable()
attribute and that it is registered as a provider in the Nest IoC container in your app.module.ts
:
@Module({
controllers: [/*...*/],
providers: [ExerciseRepository],
})
export class AppModule {}
Upvotes: 0