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-cli framework implements timer application

Technical Background This application uses the vu...

How to use JS to implement waterfall layout of web pages

Table of contents Preface: What is waterfall layo...

Implementation of nginx flow control and access control

nginx traffic control Rate-limiting is a very use...

503 service unavailable error solution explanation

1. When you open the web page, 503 service unavai...

Implementation of CSS scroll bar style settings

webkit scrollbar style reset 1. The scrollbar con...

The visual design path of the website should conform to user habits

Cooper talked about the user's visual path, w...

Detailed explanation of CSS3+JS perfect implementation of magnifying glass mode

About a year ago, I wrote an article: Analysis of...

JavaScript function call classic example code

Table of contents JavaScript function call classi...

Introduction to the deletion process of B-tree

In the previous article https://www.jb51.net/arti...

CentOS7.5 installation tutorial of MySQL

1. First check whether the system has mysql insta...

Several situations that cause MySQL to perform a full table scan

Table of contents Case 1: Case 2: Case 3: To summ...

Solution to the conflict between nginx and backend port

question: When developing the Alice management sy...