首页 > 编程技术 > js

Nest.js环境变量配置与序列化详解

发布时间:2021-2-21 15:00

环境变量配置简述

程序在不同的环境下需要不同的环境变量,例如生产环境、测试环境以及开发环境所需要不同的数据库信息:链接地址、链接端口号、登录用户名和密码相关信息。为了解决这个问题需要进行相关操作。

在 Nest 中最佳方案创建一个 ConfigModule,该 ConfigModule 公开一个 ConfigService ,在 ConfigService 加载特有环境的 .env 文件。 Nest 提供了 @nestjs/config 开箱即用的依赖包。

配置

npm 生态有很多相关的依赖包,比如最简单的:

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

安装好了直接在 main.ts 使用:

import * as dotenv from 'dotenv-flow'

/**
 * 导入 .env 环境
 * https://www.npmjs.com/package/dotenv-flow
 */
dotenv.config()

就可以使用对应的环境 .env 变量了,不过这样使用官方推荐软件包:@nestjs/config :

yarn add @nestjs/config

在 app.module.ts 中的 forRoot 静态方法配置环境变量 .env 解析:

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

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

然后在项目根目录下新建 .env 文件:

DATABASE_USER=
DATABASE_PASSWORD=
DATABASE_NAME=
DATABASE_PORT=
DATABASE_HOST=

自定义 env 路径

如果 .env 需要细化生产、测试和开发环境可以按照下面进行配置:

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

其中排序越前面则优先级最高,但在启动命令中设置环境变量则是最高,例如:

export DATABASE_USER=root && nest start

自定义配置文件

对于复杂的项目,需要把用到的可配置变量需要收集起来,比如新建 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
 }
})

然后在 ConfigModule.forRoot 加载:

import configuration from './config/configuration'

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

读取配置变量

如果需要读取相关的配置变量需要用到 ConfigService ,需要在用到的 *.module.ts 文件引入:

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

如果涉及的很多地方要写,每个 module 都要引入很烦人,可以在上面的 app.module.ts

添加一个字段:

import configuration from './config/configuration'

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

然后在构造函数注入使用:

import { ConfigService } from '@nestjs/config'

constructor(private configService: ConfigService) {}

获取配置变量例如:

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

序列化

序列化指的是程序在网络响应中返回对象发送之前的过程,将提供的信息要进行转换和清理才能发给客户端:比如查询某个用户,一般来说可以返回当前用户实体信息,但里面的密码信息是不可以发送给客户端的,所以这边要做一些转换。

还好 Nest 提供一个 class-transformer 相当好用的软件包:

yarn add class-transformer

比如在下列的用户实体信息排除密码信息:

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);
 }
}

然后在控制器处理查询用户方法:

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

最终查询会忽略密码显示。

总结

到此这篇关于Nest.js环境变量配置与序列化的文章就介绍到这了,更多相关Nest.js环境变量配置内容请搜索猪先飞以前的文章或继续浏览下面的相关文章希望大家以后多多支持猪先飞!

标签:[!--infotagslink--]

您可能感兴趣的文章: