Home > OS >  Nest - Nest can't resolve dependencies
Nest - Nest can't resolve dependencies

Time:04-27

I have a very simple CryptoModule that looks like this:

import { Module } from '@nestjs/common';

import { CryptoService } from './crypto.service';

@Module({
  providers: [CryptoService],
  exports: [CryptoService],
})
export class CryptoModule {}

Now the service CryptoService is using an environment variable to set the secret key, and for that I use Nest Config package.

import { Injectable } from '@nestjs/common';
import { ConfigService } from '@nestjs/config';
import Cryptr from 'cryptr';

@Injectable()
export class CryptoService {
  constructor(private readonly config: ConfigService, private cryptr: Cryptr) {
    this.cryptr = new Cryptr(this.config.get('CRYPTO_SECRET'));
  }

  encrypt = this.cryptr.encrypt;
  decrypt = this.cryptr.decrypt;
}

The ConfigModule is imported in app.module like so:

  imports: [
    ConfigModule.forRoot({
      envFilePath: !ENV ? '.env' : `.env.${ENV}`,
      isGlobal: true,
    }),

The thing is I keep getting the following error:

"Error: Nest can't resolve dependencies of the CryptoService (ConfigService, ?). Please make sure that the argument dependency at index [1] is available in the CryptoModule context.\n"

But since the ConfigModule is global I don't think it has to be added to the imports of the crypto module? I also tried doing that by the way and still the same error message... Am I missing something?

The only place where I use this module at the moment is here:

import { Module } from '@nestjs/common';

import { UserService } from './user.service';
import { UserController } from './user.controller';
import { CryptoModule } from '../crypto/crypto.module';

@Module({
  imports: [CryptoModule],
  controllers: [UserController],
  providers: [UserService],
})
export class UserModule {}

And of course in the service than I import the CryptoService

CodePudding user response:

I think the issue is that you added private cryptr: Cryptr in the constructor. Nest is trying to resolve this but there is no module Cryptr.

Try removing it from the constructor and add a variable cryptr instead.

cryptr: Cryptr

constructor(private readonly config: ConfigService){ /* ... */
  • Related