Reputation: 83
I have a small question about custom repositories in nestjs.
I have the following logic when a request comes in (for example for user entity).
A controller for the user requests -> pass the data to a service -> service does the logic and parsing -> call the custom repository for basic data commands (save, update, get etc.).
So i have the following repository:
@EntityRepository(User)
export class UserRepository extends Repository<User> {
/**
* Get a user by id
* @param id
*/
async getUserById(id: number): Promise<User> {
return await this.findOne({
where: [{ id }],
});
}
}
And the service looks like this:
@Injectable()
export class UserService{
constructor(
@InjectRepository(UserRepository)
private userRepository: UserRepository
){
}
/**
* Returns a user object by id
* @param id
*/
async getUserById(id: number): Promise<User>{
return await this.userRepository.getUserById(id);
}
}
If it matters the user module is:
@Module({
imports: [
TypeOrmModule.forFeature([User, UserRepository])
],
controllers: [UserController],
providers: [UserService],
exports: [UserService],
})
export class UserModule{
}
But for some reason when i call getUserById i get the following error: "TypeError: Cannot read property 'findOne' of undefined"
Iam able to fix it if i change the repository function to this:
return await getRepository(User).findOne({where: [{ id }]})
But it seems like a messy solution, any ideas why it doesnt work in the original way?
Thank in advance, Gabi.
Upvotes: 3
Views: 8504
Reputation: 1304
you don't need @InjectRepository if you use Custom repository. You need @InjectRepository when you inject your repository in service like
constructor(
@InjectRepository(User)
private readonly userService: Repository<User>
){}
Upvotes: 4
Reputation: 1174
Custom repositories don't need to be injected with
@InjectRepository(UserRepository)
You should remove that line. It could be the reason for your error.
Upvotes: 2