A brief description of environment variable configurationThe 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. ConfigurationThe 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 pathIf .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 filesFor 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 VariablesIf 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') SerializationSerialization 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. SummarizeThis 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
Table of contents Overview Create a type definiti...
1. Use CSS to draw a small pointed-corner chat di...
1. Introduction The topic of whether to use forei...
question Question 1: How to solve the performance...
Table of contents 1. IDEA downloads the docker pl...
Preface Although some love in this world has a pr...
Trident core: IE, MaxThon, TT, The World, 360, So...
Table of contents What is ref How to use ref Plac...
Scenario 1: To achieve a semi-transparent border:...
What is k3d? k3d is a small program for running a...
Table of contents background accomplish Supplemen...
Table of contents Step 1: Installation Step 2: Ci...
Table of contents Preface vue.config.js configura...
I searched for three-level linkage on the Interne...
This article is the second article about objects ...