John Oliver
John Oliver

Reputation: 91

Nest.js can't resolve the dependencies of CacheConfigService

I want to use the CacheModule in the AuthModule and I have written this code but still getting the error in the console: enter image description here

The Auth.module.ts file in which I want to import the cache module:

@Module({
  providers: [CacheConfigService, SupertokensService],
  exports: [],
  imports: [CacheConfigModule, UsersModule],
  controllers: [],
})
export class AuthModule implements NestModule {
  configure(consumer: MiddlewareConsumer) {
    consumer.apply(AuthMiddleware).forRoutes('*');
  }

  static forRoot({
    connectionURI,
    apiKey,
    appInfo,
  }: AuthModuleConfig): DynamicModule {
    return {
      // providers and exports
      imports: [CacheConfigModule],
    };
  }
}

The cache config.module.ts file code. The cache config.service.ts file contains the logic:

@Module({
  providers: [CacheConfigService],
  exports: [CacheConfigService],
  imports: [
    CacheModule.register<RedisClientOptions>({
      isGlobal: true,
      // store: redisStore,
      url: 'redis://' + process.env.REDIS_HOST + ':' + process.env.REDIS_PORT,
    }),
  ],
})
export class CacheConfigModule {}

I want to use the cache service in the following class:

@Injectable()
export class SupertokensService {
  private redisClient = redis.createClient({
    url: this.cacheConfigService.url,
  });

  constructor(
    @Inject(forwardRef(() => UsersService)) private userService: UsersService,
    private cacheConfigService: CacheConfigService
  ) {
    supertokens.init({
      appInfo: this.config.appInfo,
      supertokens: {
        connectionURI: this.config.connectionURI,
        apiKey: this.config.apiKey,
      },
      recipeList: [
        ThirdPartyEmailPassword.init({
          providers: [
            ThirdPartyEmailPassword.Google({
              clientSecret: 'TODO: GOOGLE_CLIENT_SECRET',
              clientId:
                'CLIENT_ID',
            }),
          ],
          signUpFeature: {
            ...signup logic
          },
          override: {
            apis: (originalImplementation: any) => {
              return {
                ...originalImplementation,

                emailPasswordSignInPOST: async (input: any) => {
                  if (
                    originalImplementation.emailPasswordSignInPOST === undefined
                  ) {
                    throw Error('Should never come here');
                  }

                  let response: any =
                    await originalImplementation.emailPasswordSignInPOST(input);

                  // retrieving the input from body logic
                  const { email } = inputObject;
                  const user = await this.userService.findOneByEmail(email);
                  const id = user?.id;
                  const token = jwt.sign({email, id}, 'mysecret';, {
                    expiresIn: '2h',
                  });
                  response.token = token;
                  await this.redisClient.set("Token", token, {
                    EX: 60 * 60 * 24,
                  });
                  return response;
                },
              };
            },
          },
        }),
      ],
    });
  }
}

Upvotes: 0

Views: 396

Answers (1)

Mostafa Fakhraei
Mostafa Fakhraei

Reputation: 3687

The error has been thrown because you have used ConfigService in CacheConfigService, but it has never been imported into CacheConfigModule.

If you want to have ConfigService then you must import it into AppModule, as well as CacheConfigModule.

app.module.ts:

import { ConfigModule } from '@nestjs/config';
import configuration from './config/configuration'; // or wherever your config file exists

@Module({
  imports: [
    ConfigModule.forRoot({
      load: [configuration],
    }),
    // rest of code
  ],
  // rest of code
})
export class AppModule {}

config.module.ts:

import { ConfigModule } from '@nestjs/config';

@Module({
  providers: [CacheConfigService],
  exports: [CacheConfigService],
  imports: [
    CacheModule.register<RedisClientOptions>({
      isGlobal: true,
      // store: redisStore,
      url: 'redis://' + process.env.REDIS_HOST + ':' + process.env.REDIS_PORT,
    }),
    ConfigModule,
  ],
})
export class CacheConfigModule {}

Upvotes: 1

Related Questions