3

I have my environment variable in the root of the director and the following config files to import as a module.

/config/config.service.ts

// NPM Packages
import * as dotenv from 'dotenv';
import * as fs from 'fs';
import * as Joi from '@hapi/joi';

export type EnvConfig = Record<string, string>;

export class ConfigService {
  private readonly envConfig: EnvConfig;

  constructor(filePath: string) {
    const config = dotenv.parse(fs.readFileSync(filePath));
    this.envConfig = this.validateInput(config);
  }

  /**
   * Ensures all needed variables are set,
   * and returns the validated JavaScript object
   * including the applied default values.
   */
  private validateInput(envConfig: EnvConfig): EnvConfig {
    const envVarsSchema: Joi.ObjectSchema = Joi.object({
      NODE_ENV: Joi.string()
        .valid('development', 'production', 'test', 'provision')
        .default('development'),
      PORT: Joi.number().default(3000),
      MONGO_URI: Joi.required(),
      API_AUTH_ENABLED: Joi.boolean().required(),
      IS_AUTH_ENABLED: Joi.boolean().required(),
      JWT_SECRET: Joi.required(),
      JWT_EXPIRE: Joi.required(),
      JWT_COOKIE_EXPIRE: Joi.required(),
    });

    const { error, value: validatedEnvConfig } = envVarsSchema.validate(
      envConfig,
    );
    if (error) {
      throw new Error(`Config validation error: ${error.message}`);
    }
    return validatedEnvConfig;
  }

  get(key: string): string {
    return this.envConfig[key];
  }
}

/config/config.module.ts

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

// Custom Packages
import { ConfigService } from './config.service';

@Module({
  providers: [
    {
      provide: ConfigService,
      useValue: new ConfigService(
        `${process.env.NODE_ENV || 'development'}.env`,
      ),
    },
  ],
  exports: [ConfigService],
})
export class ConfigModule {}

I have imported it globally in app.modules as follows

@Module({
  imports: [ConfigModule]
})

In my database provider src/database/database.providers.ts I am trying to import the MONGO_URL variable but am getting an error.

// NPM Packages
import * as mongoose from 'mongoose';

// Custom Packages
import { envConfig } from '../config/config.service';

const mongoUrl: string = envConfig.get('MONGO_URI');

export const databaseProviders = [
  {
    provide: 'DATABASE_CONNECTION',
    useFactory: async (): Promise<typeof mongoose> =>
      await mongoose.connect(mongoUrl, {
        useNewUrlParser: true,
        useUnifiedTopology: true,
        useCreateIndex: true,
        useFindAndModify: false,
      }),
  },
];

Error:

Property 'get' does not exist on type 'typeof ConfigService'.ts(2339)

4
  • what is the error message ? Commented Nov 16, 2019 at 7:27
  • @SafiNettah Property 'get' does not exist on type 'typeof ConfigService'.ts(2339) Commented Nov 16, 2019 at 7:27
  • declare your get like static get Commented Nov 16, 2019 at 7:30
  • @SafiNettah does not help. I am confused on how to import the Config into the Database Provider file. and then call for the key Commented Nov 16, 2019 at 7:32

1 Answer 1

1

Here, you are importing the ConfigService class, not an instance of the ConfigService, so there is no static get method on the ConfigService class, just an instance method. What you can do instead is modify your databaseProvider to look like this:

export const databaseProviders = [
  {
    provide: 'DATABASE_CONNECTION',
    useFactory: async (private readonly configService: ConfigService): Promise<typeof mongoose> =>
      await mongoose.connect(configSerivce.get('MONGO_URI'), {
        useNewUrlParser: true,
        useUnifiedTopology: true,
        useCreateIndex: true,
        useFindAndModify: false,
      }),
    inject: [ConfigService],
    imports: [ConfigModule]
  },
];
Sign up to request clarification or add additional context in comments.

4 Comments

Could you please explain to me the inject and imports part. I am confused why its added in there
When I try the above code am getting A parameter property is only allowed in a constructor implementation.ts(2369)
and Property 'get' does not exist on type 'typeof ConfigService'. errors
I'll make changes to your git repo and make more comments there. I used ConfigService as that is the class you have, and ConfigModule out of a guess as to what you called it. Once I have it working we can discuss more about the why

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.