Logo
Section 1 / 3

在 NestJS 应用中设置环境变量

学习如何在 NestJS 中使用环境变量。

导入

在 NestJS 应用中设置环境变量

学习如何在 NestJS 中使用环境变量。

使用环境变量存储应用程序配置

1npm install @nestjs/config
1import { Module } from '@nestjs/common'; 2import { AppController } from './app.controller'; 3import { AppService } from './app.service'; 4import { BooksModule } from './books/books.module'; 5import { TypeOrmModule } from '@nestjs/typeorm'; 6import { Book } from './books/entities/book.entity'; 7import { Author } from './authors/entities/author.entity'; 8import { AuthorsModule } from './authors/authors.module'; 9import { ConfigModule } from "@nestjs/config"; 10 11@Module({ 12 imports: [ 13 ConfigModule.forRoot(), 14 TypeOrmModule.forRoot({ 15 type: 'postgres', 16 host: 'localhost', 17 port: 5432, 18 username: 'postgres', 19 password: 'pwd123', 20 database: 'book_database', 21 entities: [Book, Author], 22 synchronize: true 23 }), 24 BooksModule, 25 AuthorsModule 26 ], 27 controllers: [AppController], 28 providers: [AppService], 29}) 30export class AppModule {}

使用 ConfigService 获取环境变量的值

1import { Module } from '@nestjs/common'; 2import { AppController } from './app.controller'; 3import { AppService } from './app.service'; 4import { BooksModule } from './books/books.module'; 5import { TypeOrmModule } from '@nestjs/typeorm'; 6import { Book } from './books/entities/book.entity'; 7import { Author } from './authors/entities/author.entity'; 8import { AuthorsModule } from './authors/authors.module'; 9import { ConfigModule } from "@nestjs/config"; 10 11@Module({ 12 imports: [ 13 ConfigModule.forRoot({ 14 envFilePath: `.dev.env`, 15 }), 16 TypeOrmModule.forRoot({ 17 type: 'postgres', 18 host: 'localhost', 19 port: 5432, 20 username: 'postgres', 21 password: 'pwd123', 22 database: 'book_database', 23 entities: [Book, Author], 24 synchronize: true 25 }), 26 BooksModule, 27 AuthorsModule 28 ], 29 controllers: [AppController], 30 providers: [AppService], 31}) 32export class AppModule {}
1import { Module } from '@nestjs/common'; 2import { AppController } from './app.controller'; 3import { AppService } from './app.service'; 4import { BooksModule } from './books/books.module'; 5import { TypeOrmModule } from '@nestjs/typeorm'; 6import { Book } from './books/entities/book.entity'; 7import { Author } from './authors/entities/author.entity'; 8import { AuthorsModule } from './authors/authors.module'; 9import { ConfigModule } from "@nestjs/config"; 10 11@Module({ 12 imports: [ 13 ConfigModule.forRoot({ 14 envFilePath: `.${process.env.NODE_ENV}.env`, 15 }), 16 TypeOrmModule.forRoot({ 17 type: 'postgres', 18 host: 'localhost', 19 port: 5432, 20 username: 'postgres', 21 password: 'pwd123', 22 database: 'book_database', 23 entities: [Book, Author], 24 synchronize: true 25 }), 26 BooksModule, 27 AuthorsModule 28 ], 29 controllers: [AppController], 30 providers: [AppService], 31}) 32export class AppModule {}
1{ 2 "name": "books-api", 3 "version": "0.0.1", 4 "description": "", 5 "author": "", 6 "private": true, 7 "license": "UNLICENSED", 8 "scripts": { 9 "build": "nest build", 10 "format": "prettier --write \"src/**/*.ts\" \"test/**/*.ts\"", 11 "start": "NODE_ENV=dev nest start", 12 "start:dev": "NODE_ENV=dev nest start --watch", 13 "start:debug": "NODE_ENV=dev nest start --debug --watch", 14 "start:prod": "NODE_ENV=prod node dist/main", 15 "lint": "eslint \"{src,apps,libs,test}/**/*.ts\" --fix", 16 "test": "NODE_ENV=test jest", 17 "test:watch": "NODE_ENV=test jest --watch", 18 "test:cov": "NODE_ENV=test jest --coverage", 19 "test:debug": "NODE_ENV=test node --inspect-brk -r tsconfig-paths/register -r ts-node/register node_modules/.bin/jest --runInBand", 20 "test:e2e": "NODE_ENV=test jest --config ./test/jest-e2e.json" 21 }, 22 "dependencies": { 23 "@nestjs/common": "^9.0.0", 24 "@nestjs/core": "^9.0.0", 25 "@nestjs/mapped-types": "^1.2.2", 26 "@nestjs/platform-express": "^9.0.0", 27 "@nestjs/typeorm": "^9.0.1", 28 "class-transformer": "^0.5.1", 29 "class-validator": "^0.14.0", 30 "pg": "^8.11.0", 31 "reflect-metadata": "^0.1.13", 32 "rxjs": "^7.2.0", 33 "typeorm": "^0.3.16" 34 }, 35 "devDependencies": { 36 "@nestjs/cli": "^9.0.0", 37 "@nestjs/schematics": "^9.0.0", 38 "@nestjs/testing": "^9.0.0", 39 "@types/express": "^4.17.13", 40 "@types/jest": "29.2.4", 41 "@types/node": "18.11.18", 42 "@types/supertest": "^2.0.11", 43 "@typescript-eslint/eslint-plugin": "^5.0.0", 44 "@typescript-eslint/parser": "^5.0.0", 45 "eslint": "^8.0.1", 46 "eslint-config-prettier": "^8.3.0", 47 "eslint-plugin-prettier": "^4.0.0", 48 "jest": "29.3.1", 49 "prettier": "^2.3.2", 50 "source-map-support": "^0.5.20", 51 "supertest": "^6.1.3", 52 "ts-jest": "29.0.3", 53 "ts-loader": "^9.2.3", 54 "ts-node": "^10.0.0", 55 "tsconfig-paths": "4.1.1", 56 "typescript": "^4.7.4" 57 }, 58 "jest": { 59 "moduleFileExtensions": [ 60 "js", 61 "json", 62 "ts" 63 ], 64 "rootDir": "src", 65 "testRegex": ".*\\.spec\\.ts$", 66 "transform": { 67 "^.+\\.(t|j)s$": "ts-jest" 68 }, 69 "collectCoverageFrom": [ 70 "**/*.(t|j)s" 71 ], 72 "coverageDirectory": "../coverage", 73 "testEnvironment": "node" 74 } 75}
1DATABASE_USER=postgres 2DATABASE_PASSWORD=pwd123 3DATABASE_NAME=book_database 4DATABASE_PORT=5432 5DATABASE_HOST=localhost

利用 TypeOrmModule.forRootAsync 通过环境变量和 ConfigService 配置数据库选项

TypeOrmModule.forRootAsync 模块使用配置对象异步初始化 TypeOrmModule。请查看以下配置项:

  • imports: [ConfigModule]:将 ConfigModule 导入到 TypeOrmModule.forRootAsync 的配置上下文中,使得 ConfigModule 所导出的提供者(如 ConfigService)可以在该模块的其他部分被注入和使用。

  • inject: [ConfigService]:指定将 ConfigService 注入工厂函数中。ConfigService 的作用是提供对 ConfigModule 管理的配置项的访问能力,我们用它来获取具体的数据库配置。

  • useFactory: async (configService: ConfigService):这是一个异步工厂函数,用于创建并返回 TypeORM 模块的配置。该工厂函数会设置必要的参数,并通过 configService 动态获取相应的配置值。

数据库操作

使用Joi进行配置验证