Detailed explanation of Nest.js environment variable configuration and serialization

Detailed explanation of Nest.js environment variable configuration and serialization

A brief description of environment variable configuration

The program requires different environment variables in different environments. For example, the production environment, test environment, and development environment require different database information: link address, link port number, login user name, and password related information. In order to solve this problem, relevant operations need to be performed.

The best approach in Nest is to create a ConfigModule that exposes a ConfigService where you load environment-specific .env files. Nest provides @nestjs/config out of the box.

Configuration

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

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

After installation, use it 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 variables, but use the official recommended package: @nestjs/config:

yarn add @nestjs/config

Configure environment variables .env parsing in the forRoot static method in app.module.ts:

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

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

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

DATABASE_USER=
DATABASE_PASSWORD=
DATABASE_NAME=
DATABASE_PORT=
DATABASE_HOST=

Custom env path

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

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

The one that is sorted earlier has the highest priority, but setting the environment variable in the startup command has the highest priority, for example:

export DATABASE_USER=root && nest start

Custom configuration files

For complex projects, you need to collect the configurable variables used, such as creating a 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 it in ConfigModule.forRoot:

import configuration from './config/configuration'

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

Reading Configuration Variables

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

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

If there are many places involved, it is annoying to import each module. You can do it in the app.module.ts above.

Add a field:

import configuration from './config/configuration'

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

Then inject it in the constructor:

import { ConfigService } from '@nestjs/config'

constructor(private configService: ConfigService) {}

Get configuration variables such as:

const dbUser = this.configService.get<string>('DATABASE_USER')
const dbHost = this.configService.get<string>('database.host')

Serialization

Serialization refers to the process before a program returns an object in a network response and sends it. The provided information must be converted and cleaned before it can be sent to the client: for example, when querying a user, the current user entity information can generally be returned, but the password information in it cannot be sent to the client, so some conversion must be done here.

Fortunately, Nest provides a very useful package called class-transformer:

yarn add class-transformer

For example, the following user entity information excludes password information:

import { Exclude } from 'class-transformer'

export class UserEntity {
 id: number
 firstName: string;
 lastName: string;

 @Exclude()
 password: string;

 constructor(partial: Partial<UserEntity>) {
  Object.assign(this, partial);
 }
}

Then process the query user method in the controller:

@UseInterceptors(ClassSerializerInterceptor)
@Get(':id')
findOne(@Param('id') id: string): Promise<UserEntity> {
 return this.userService.findOne(id)
}

The final query omits the password display.

Summarize

This is the end of this article about Nest.js environment variable configuration and serialization. For more related Nest.js environment variable configuration content, please search for previous articles on 123WORDPRESS.COM or continue to browse the following related articles. I hope everyone will support 123WORDPRESS.COM in the future!

<<:  The difference between Decimal type and Float Double in MySQL (detailed explanation)

>>:  How to install Nginx in CentOS7 and configure automatic startup

Recommend

Vue encapsulation component upload picture component

This article example shares the specific code of ...

A brief analysis of Linux network programming functions

Table of contents 1. Create a socket 2. Bind sock...

What is Software 404 and 404 Error and what is the difference between them

First of all, what is 404 and soft 404? 404: Simpl...

JavaScript adds event listeners to event delegation in batches. Detailed process

1. What is event delegation? Event delegation: Ut...

Talk about nextTick in Vue

When the data changes, the DOM view is not update...

The top fixed div can be set to a semi-transparent effect

Copy code The code is as follows: <!DOCTYPE ht...

Nodejs uses readline to prompt for content input example code

Table of contents Preface 1. bat executes js 2. T...

How to use Docker container to access host network

Recently, a system was deployed, using nginx as a...

Automatically build and deploy using Docker+Jenkins

This article introduces Docker+Jenkins automatic ...

How to configure two or more sites using Apache Web server

How to host two or more sites on the popular and ...

Use Javascript to develop sliding-nav navigation plug-in with sliding bar effect

Table of contents 1. Introduction 2. Usage 3. Dev...

Several ways to hide Html elements

1. Use CSS Copy code The code is as follows: style...

Seven ways to implement array deduplication in JS

Table of contents 1. Using Set()+Array.from() 2. ...