davi
davi

Reputation: 91

Can I use NestJS Config Service outside a module?

I have a class that is not related to any nest modules. I wanted to import and use my ConfigService inside of this class. Can I do this without adding this class to any module or do I need to have a module in order to use nest generated classes?

Thanks

Upvotes: 9

Views: 7156

Answers (3)

Qwerty
Qwerty

Reputation: 32048

Building on Vinayak Sarawagi's solution, you can even do this inside your custom ConfigModule:

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

@Injectable()
export class MyConfigService {
  static config: MyConfigService

  constructor(private configService: ConfigService) {
    MyConfigService.config = this
  }

  get isDevelopment(): boolean {
    return this.configService.get('NODE_ENV') === 'development'
  }
}

you can then use whatever private property you have on that service

AppConfig.config.isDevelopment

See the linked answer for details how to export the module globally.

Upvotes: 0

Vinayak Sarawagi
Vinayak Sarawagi

Reputation: 1072

You can create on class like below

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

@Injectable()
export class AppConfig {
  static service: ConfigService;

  constructor(service: ConfigService) {
    AppConfig.service = service;
  }

  static get(key: string): any {
    return AppConfig.service.get(key);
  }
}

add this class as a provider in your root module AppModule,

...
providers: [AppConfig],
...

now once the app is booted, you can use it as following anywhere inside app,

AppConfig.get('database.port');

Hope this helped!

Upvotes: 10

Ayzrian
Ayzrian

Reputation: 2465

Yep, you can get anything from Nest.js DI container using app.get method.

e.g.

const configService = app.get(ConfigService)

Upvotes: -1

Related Questions