Odeus
Odeus

Reputation: 123

NestJS. Can't inject a repository from a different module

I am trying to use a typeorm custom repository defined in another module.

Following the documentation:

If you want to use the repository outside of the module which imports TypeOrmModule.forFeature, you'll need to re-export the providers generated by it. You can do this by exporting the whole module, like this:

@Module({
  imports: [TypeOrmModule.forFeature([Role])],
  exports: [TypeOrmModule]
})
export class RoleModule {}

Now if we import UsersModule in UserHttpModule, we can use @InjectRepository(User) in the providers of the latter module.

In my case i do:

@Module({
  imports: [RoleModule],
  providers: [UsersService],
  controllers: [UsersController]
})
export class UserModule {}

Now when i inject the Role repository

export class UserService {
  constructor(@InjectRepository(Role) private roleRepository: Repository<Role>) {}
}

i've got an error: Nest can't resolve dependencies of the UserService (?).

Is it me or is the documentation incorrect? Can someone suggest what is the error here or give a corrected example?

Upvotes: 5

Views: 11433

Answers (1)

Art Olshansky
Art Olshansky

Reputation: 3356

Try to add TypeOrmModule.forFeature([Role]) to imports:

@Module({
  imports: [TypeOrmModule.forFeature([Role]), RoleModule], // <-- here
  providers: [UsersService],
  controllers: [UsersController]
})
export class UserModule {}

Upvotes: 8

Related Questions