Search code examples
javascriptnode.jstypescriptnestjstypeorm

NestJS can't resolve dependencies of the AuthServices


After first problem with JWT_MODULE_OPTION, back to old problem who I thought I was fixed. It turned out that when I "fix" old problem create the new with JWT.

So again can't compile:

Nest can't resolve dependencies of the AuthService (?, RoleRepository, JwtService). Please make sure that the argument at index [0] is available in the AppModule context. +25ms

It's really strange, because this way work on another my project and can't understand where I'm wrong. Here is the auth.service.ts:

@Injectable()
export class AuthService {
    constructor(
        @InjectRepository(User) private readonly userRepo: Repository<User>,
        @InjectRepository(Role) private readonly rolesRepo: Repository<Role>,
        private readonly jwtService: JwtService,
    ) { }

It get role and jwtService but the problem is with User, the path is correct. Here is app.module.ts:

@Module({
  imports: [
    TypeOrmModule.forRootAsync({
      imports: [ConfigModule, AuthModule],
      inject: [ConfigService],
      useFactory: async (configService: ConfigService) => ({
        type: configService.dbType as any,
        host: configService.dbHost,
        port: configService.dbPort,
        username: configService.dbUsername,
        password: configService.dbPassword,
        database: configService.dbName,
        entities: ['./src/data/entities/*.ts'],
      }),
    }),
  ],
  controllers: [AppController, AuthController],
  providers: [AuthService],
})
export class AppModule { }

Have the same compile error for controllers & providers & can't understand what is wrong...


Solution

  • You might be missing the TypeOrmModule.forFeature([User]) import. Typically, all entities are imported in dedicated feature modules. If you only have one module (i.e. AppModule) you need to put the forFeature import there in addition to the forRoot import.

    @Module({
      imports: [
        TypeOrmModule.forRootAsync({...}),
        TypeOrmModule.forFeature([User, Role]),
      ],