7

Taking configuration as an example, the Nest.js documentation advocates registering Config Modules and injecting them into other modules in a dependency injection way.

The benefits are obvious, and the dependencies and code are clear, but what if I have a nest.js project that needs to invoke the configuration information at startup? This actually caused me trouble.

My idea is to use a store (actually a closure) to manage all the variables that might be needed globally, the client-side link objects, registered at startup, and introduced when needed.

When corresponding variables are registered in this way, they can be introduced anywhere. The drawback is that you need to manage dependencies yourself.

With the above concept design of demo: https://github.com/sophons-space/nest-server.

Please e help me correct, I am still a rookie.

Sai Gummaluri
  • 1,340
  • 9
  • 16
yang.liu
  • 71
  • 1
  • 1
  • 3
  • I'm not really sure what the question is here. NestJS is a framework on top of NodeJS, so (mostly) anything valid in Node can be done in Nest. Are you seeing an error with your approach? – Jay McDoniel Feb 21 '21 at 18:16

6 Answers6

8

If you want to use Nest flow it should be defined in the configuration file

// app.module.ts
import configuration from './config/configuration';

imports: [
// first import as first initialization
  ConfigModule.forRoot({
    isGlobal: true, // to get access to it in every component
    load: [configuration],
  }),
]
...
// configuration.ts
export default (): any => {
  return {
    someGlobalConfigVariable: parseInt(process.env.PORT, 10) || 3000,
  };
};

kosiakMD
  • 923
  • 7
  • 22
  • `ConfigModule` comes from `@nestjs/config` for anybody wondering. More on this can be found in the [nest docu](https://docs.nestjs.com/techniques/configuration) – Tanonic Jun 29 '22 at 19:03
  • What version you are talking about ? 6/7/8? The best way is to initiate on the entry point to have all consistent everywhere - it should make thread block operation to read file synchronously – kosiakMD Jul 03 '22 at 12:32
6

Create a file global.service.ts (inside a folder you can name it utils or whatever) & put the code bellow

export class GlobalService{ 
   static globalVar: any; 
}

Set value to the globalVar

GlobalService.globalVar = 'some value';

Get value from globalVar

console.log(GlobalService.globalVar);

N.B. Don't forget to import GlobalService wherever you want to use.

Musabbir Mamun
  • 251
  • 3
  • 6
4

The way you can approach this is similar to how NestJS libraries or integrations usually handle configuration; using a method on the base module.

main.ts

import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';

async function bootstrap() {
  // Note the `configure`-method
  const app = await NestFactory.create(AppModule.configure({
    myConfig: 'value',
  });
  await app.listen(3000);
}
bootstrap();

app.module.ts

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


export class AppModule {
  static configure(config): DynamicModule {
     return {
       module: AppModule,
       providers: [{ provide: 'CONFIG', useValue: config }],
       // ....
     }
  }
}
Livio Brunner
  • 727
  • 2
  • 8
  • 22
  • I'm getting error of `Nest can't resolve dependencies of the EntryController (EntryService, ?). Please make sure that the argument CONFIG at index [1] is available in the EntryModule context.`, what do I miss? While using this answer works, https://stackoverflow.com/a/55413562, but I don't want to create a new module – sulaiman sudirman Apr 19 '21 at 00:51
2

You can use the general NodeJS approach

global.SomeGlobalVariableName = 'SomeGlobalVariableValue';

console.log(SomeGlobalVariableName);
kosiakMD
  • 923
  • 7
  • 22
0

Approach I used is using my config variables in yaml files and then getting those variables or objects wherever I want in my Nestjs project using config package. e.g in default.yml file key: value and then in file where I want to use this

import config from 'config';
let value = config.get<string>('key');

you can take this pkg from this npmjs link here

Muhammad Awais
  • 1,608
  • 1
  • 21
  • 21
0

Why not go with more NestJs way i.e. with provide instance scope?

Most of the answers posted here are correct and easy to implement but I have a more generic way to define that variable that fits well in NestJs (Nestjs Scope and Dependency Injection flow). I would be happy to share the sample code, if required

Steps

  1. Create a provider
  2. Add a private instance variable to this provider - instead of a class variable (i.e. static variables) use an instance variable as NestJs automatically (by default) manages the instance of its providers in a singleton way i.e. a single instance of the provider is shared across the entire application. Read more about scopes here
  3. Add get/set and other methods for that variable
  4. Inject that provider wherever you need the global variable (instance variable of the provider(per instance).

Other ways of doing it

  1. Config - preferrable for pre-defined types(like string, number...)
  2. Static variable in util.ts file
  3. Native Global variable - I would not recommend this(explanation is outside the scope of the question)
RollerCosta
  • 5,020
  • 9
  • 53
  • 71