Skip to content

配置项(yml 版本)

  • 个人不推荐因为 prisma 不支持

使用 yaml 方式配置

安装依赖

安装 js-yaml 包和类型

ts
npm i js-yaml -S

npm i @types/js-yaml -D

pnpm i @nestjs/config -S

pnpm i cross-env -S

src 文件夹下创建一个 config 目录来放各个环境的配置,这里创建 3 个环境 dev/prod/test

ts
── src
│   ├── app.module.ts
│   ├── config
│   │   ├── dev.yml
│   │   ├── index.ts
│   │   ├── prod.yml
│   │   └── test.yml
│   ├── main.ts
│   └── user
│       ├── dto
│       │   ├── create-user.dto.ts
│       │   └── update-user.dto.ts
│       ├── entities
│       │   └── user.entity.ts
│       ├── user.controller.ts
│       ├── user.module.ts
│       └── user.service.ts
├── tsconfig.build.json
└── tsconfig.json

config/index.ts是动态加载所有配置的入口页,代码如下

ts
import { readFileSync } from "fs";
import * as yaml from "js-yaml";
import { join } from "path";
const configFileNameObj = {
  development: "dev",
  test: "test",
  production: "prod",
};
const env = process.env.NODE_ENV || "development";
export default () => {
  return yaml.load(
    readFileSync(join(__dirname, `./${configFileNameObj[env]}.yml`), "utf8")
  ) as Record<string, any>;
};

这里有个需要注意的地方导入 js-yaml 的时候一定要用\* as yaml 或者 require()

不然的话会报错 load 方法不存在,当然你也可以单独导入方法,看你喜好。

还需要注意的是导出必须是个函数,以为配置包的 load 方法只接受函数数组

yml格式的配置文件比如dev.yml

ts
# 开发环境配置
app:
  prefix: ''
  port: 8080
  logger:
    # 项目日志存储路径,相对路径(相对本项目根目录)或绝对路径
    dir: '../logs'
  # 文件相关
  file:
    # 是否为本地文件服务或cos
    isLocal: true
    # location 文件上传后存储目录,相对路径(相对本项目根目录)或绝对路径
    location: '../upload'
    # 文件服务器地址,这是开发环境的配置 生产环境请自行配置成可访问域名
    domain: 'http://localhost:8080'
    # 文件虚拟路径, 必须以 / 开头, 如 http://localhost:8080/profile/****.jpg  , 如果不需要则 设置 ''
    serveRoot: '/profile'
    # 文件大小限制,单位M
    maxSize: 10
# 腾讯云cos配置
cos:
  secretId: ''
  secretKey: ''
  bucket: ''
  region: ''
  domain: ''
  location: ''
# 数据库配置
db:
  mysql:
    host: 'xxxxx'
    username: 'root'
    password: 'xxxxx'
    database: 'prismalianbiao'
    port: 3306
    charset: 'utf8mb4'
    logger: 'file'
    logging: true
    multipleStatements: true
    dropSchema: false
    synchronize: true
    supportBigNumbers: true
    bigNumberStrings: true
  mysqlread:
    host: 'xxxxx'
    username: 'root'
    password: 'xxxxx'
    database: 'prismalianbiao2'
    port: 3306
    charset: 'utf8mb4'
    logger: 'file'
    logging: true
    multipleStatements: true
    dropSchema: false
    synchronize: true
    supportBigNumbers: true
    bigNumberStrings: true
# redis 配置 过期时间1 小时
redis:
  host: 'xxxxx'
  password: 'redis_n6BSFa'
  port: 6379
  db: 0
  keyPrefix: ''
  ttl: 3600
# jwt 配置
jwt:
  secretKey: 'jsopy'
  expiresin: '1h'
  refreshExpiresIn: '2h'
# 权限 白名单配置
perm:
  router:
    whiteList: [
        { path: '/users/config', method: 'GET' },
        { path: '/users/register/jwt', method: 'POST' },
        # { path: '/users/login/jwt', method: 'POST' }, 这里我取消了 因为我默认就是jwt登录
        { path: '/users/login/custom', method: 'POST' },
        { path: '/users/login/basic', method: 'POST' },
      ]
# 拦截器白名单
noglobalinterceptor:
  router:
    whiteList: []
# 用户相关
# 初始密码, 重置密码
user:
  initialPassword: '123456'

# 自己写的测试
testconfig:
  test: 'dev'

然后在 app.module.ts 中配置导入 yml 配置

ts
import { Module, Global } from "@nestjs/common";
import { ConfigModule, ConfigService } from "@nestjs/config";
import configuration from "./config/index";
@Global()
@Module({
  imports: [
    // 配置模块
    ConfigModule.forRoot({
      cache: true,
      load: [configuration],
      isGlobal: true,
    }),
  ],
  controllers: [],
  providers: [],
})
export class AppModule {}

现在如果启动项目的话,大概率 yml 文件会找不到而报错,此时还需要去配置下 cli 的配置文件 nest-cli.json

ts
{
  "$schema": "https://json.schemastore.org/nest-cli",
  "collection": "@nestjs/schematics",
  "sourceRoot": "src",
  "compilerOptions": {
    "assets": ["**/*.yml"],
    "deleteOutDir": true,
    "watchAssets": true
  },
  "generateOptions": {
    "spec": false
  }
}

特别注意的就是这个打包配置 compilerOptions 中的 assets,这个要配置成所有的 yml 文件,这样才能在 dist 中找到配置的配置文件

ts
dist
│   ├── app.module.d.ts
│   ├── app.module.js
│   ├── app.module.js.map
│   ├── config
│   │   ├── dev.yml
│   │   ├── index.d.ts
│   │   ├── index.js
│   │   ├── index.js.map
│   │   ├── prod.yml
│   │   └── test.yml

接下来还需要去修改一下 npmscript 命令,加上环境变量来运行对应的环境配置,先安装一个 cross-env

ts
npm i cross-env -D

然后修改对应环境的脚本命令

ts
 "start:dev": "cross-env NODE_ENV=development nest start --watch",
 "start:debug": "cross-env NODE_ENV=development nest start --debug --watch",
 "start:test": "cross-env NODE_ENV=test node dist/main",
 "start:prod": "cross-env NODE_ENV=production node dist/main",

使用配置

使用配置的话,需要导入@nestjs/config 提供的服务来获取配置信息,比如在 user 模块使用配置

因为配置已经设置为全局可用,所以不再需要在 user 模块中导入了,可以直接使用

ts
import { ConfigService } from '@nestjs/config';

@Controller('user')
export class UserController {
  constructor(
    private readonly userService: UserService,
    private configService: ConfigService,
  ) {}

  @Get()
  findAll() {
    console.log('configService===', this.configService.get('db'));

    return this.userService.findAll();
  }