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
Technical Background This application uses the vu...
Table of contents Preface: What is waterfall layo...
nginx traffic control Rate-limiting is a very use...
1. When you open the web page, 503 service unavai...
webkit scrollbar style reset 1. The scrollbar con...
This article records some major setting changes w...
Cooper talked about the user's visual path, w...
This week has been as busy as a war. I feel like ...
About a year ago, I wrote an article: Analysis of...
Table of contents forEach() (ES6) method map() (E...
Table of contents JavaScript function call classi...
In the previous article https://www.jb51.net/arti...
1. First check whether the system has mysql insta...
Table of contents Case 1: Case 2: Case 3: To summ...
question: When developing the Alice management sy...