Nest. js Environment Variable Configuration and Serialization Detailed Explanation

  • 2021-10-27 06:30:51
  • OfStack

Brief introduction of environment variable configuration

Programs need different environment variables in different environments, such as production environment, test environment and development environment, which need different database information: link address, link port number, login user name and password. In order to solve this problem, relevant operations are needed.

The best solution in Nest is to create an ConfigModule, which exposes an ConfigService, and load the environment-specific. env file in ConfigService. Nest provides @ nestjs/config out-of-the-box dependency packages.

Configure

The npm ecosystem has many related dependency packages, such as the simplest:


yarn add dotenv-flow
yarn add @types/dotenv-flow -D

Installed and used directly in main. ts:


import * as dotenv from 'dotenv-flow'

/**
 *  Import  .env  Environment 
 * https://www.npmjs.com/package/dotenv-flow
 */
dotenv.config()

You can use the corresponding environment. env variable, but use the official recommended package: @ nestjs/config:


yarn add @nestjs/config

The forRoot static method in app. module. ts configures the environment variable. env parsing:


import { Module } from '@nestjs/common'
import { ConfigModule } from '@nestjs/config'

@Module({
 imports: [ConfigModule.forRoot()]
})
export class AppModule {}

Then create a new. env file under the root directory of the project:


DATABASE_USER=
DATABASE_PASSWORD=
DATABASE_NAME=
DATABASE_PORT=
DATABASE_HOST=

Custom env path

If. env needs to refine production, test and development environments can be configured as follows:


ConfigModule.forRoot({
 envFilePath: ['.env.development.local', '.env.development'],
})

The higher the order, the higher the priority, but setting the environment variable in the startup command is the highest, for example:


export DATABASE_USER=root && nest start

Custom profile

For complex projects, it is necessary to collect the configurable variables used, such as creating new src/config/configuration. ts:


export default () => ({
 port: parseInt(process.env.PORT, 10) || 3000,
 database: {
  host: process.env.DATABASE_HOST || 'localhost',
  port: parseInt(process.env.DATABASE_PORT, 10) || 3306
 }
})

Then load on ConfigModule. forRoot:


import configuration from './config/configuration'

@Module({
 imports: [
  ConfigModule.forRoot({
   load: [configuration]
  })
 ]
})
export class AppModule {}

Reading configuration variables

If you need to read the relevant configuration variables and need to use ConfigService, you need to introduce it in the *. module. ts file:


@Module({
 imports: [ConfigModule],
 // ...
})

If there are many places to write, it is annoying to introduce every module, which can be found in app. module. ts above

Add 1 field:


import * as dotenv from 'dotenv-flow'

/**
 *  Import  .env  Environment 
 * https://www.npmjs.com/package/dotenv-flow
 */
dotenv.config()

0

Then, in the constructor injection, use:


import * as dotenv from 'dotenv-flow'

/**
 *  Import  .env  Environment 
 * https://www.npmjs.com/package/dotenv-flow
 */
dotenv.config()

1

Get configuration variables such as:


import * as dotenv from 'dotenv-flow'

/**
 *  Import  .env  Environment 
 * https://www.npmjs.com/package/dotenv-flow
 */
dotenv.config()

2

Serialization

Serialization refers to the process before the program returns the object to send in the network response, and the information provided should be converted and cleaned before being sent to the client: for example, if you query a certain user, you can generally return the current user entity information, but the password information inside cannot be sent to the client, so you should do some conversion here.

Fortunately, Nest provides a fairly easy-to-use software package for class-transformer:


yarn add class-transformer

For example, password information is excluded from the following user entity information:


import * as dotenv from 'dotenv-flow'

/**
 *  Import  .env  Environment 
 * https://www.npmjs.com/package/dotenv-flow
 */
dotenv.config()

4

Then process the query user method in the controller:


import * as dotenv from 'dotenv-flow'

/**
 *  Import  .env  Environment 
 * https://www.npmjs.com/package/dotenv-flow
 */
dotenv.config()

5

The final query ignores the password display.

Summarize


Related articles: