简体   繁体   中英

How to use global variables in nest.js?

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.

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);

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

You can use the general NodeJS approach

global.SomeGlobalVariableName = 'SomeGlobalVariableValue';

console.log(SomeGlobalVariableName);

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,
  };
};

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 }],
       // ....
     }
  }
}

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. eg 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

Why not go with more NestJs way ie 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 (ie static variables) use an instance variable as NestJs automatically (by default) manages the instance of its providers in a singleton way ie 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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM