当前位置: 首页 > news >正文

nestjs 配置管理简单说明

nestjs 配置管理简单说明

nestjs 配置管理是一个独立的模块,机制上不像midwayjs的玩法,直接提供了装饰器可以快速获取,但是nestjs 是以模块的模式提供的,同时支持范型模式,当然有支持midwayjs 接口定义获取的模式(自动进行对象转换),以下是一个简单玩法

基于yaml的简单实例

内容实际来自官方文档,我做了一些简单调整,使用了多模块的模式

  • 配置
http:host: "localhost"port: 8080db:postgres:host: "localhost"port: 5432database: "mydb"username: "user"password: "password"sqlite:database: "db.sqlite"
  • 宿主应该暴露全局配置模块
  imports: [ConfigModule.forRoot({isGlobal: true, // 此处注册为了全局模块,子模块就可以直接通过ConfigService 获取了load: [configuration],}),

configuration 定义

import { readFileSync } from 'fs';
import { join } from 'path';
import * as yaml from 'js-yaml';const YAML_CONFIG_FILENAME = 'app.yaml';export default () => {const filePath = join(__dirname, '..', 'conf', YAML_CONFIG_FILENAME);const file = readFileSync(filePath, 'utf8');const config = yaml.load(file) as Record<string, any>;return config;
};
  • 子模块通过ConfigService 获取实体数据

接口类型定义,可以让ConfigService 自动帮助我们进行对象处理

export interface PGDBConfig {host: string;port: number;username: string;password: string;database: string;
}export interface HttpConfig {host: string;port: number;
}export interface SQLiteDBConfig {database: string;
}export interface AppConfig {http: HttpConfig;db: {postgres: PGDBConfig;sqlite: SQLiteDBConfig;};
}

使用配置(注意不太好的是暂时没有提供直接获取所有的,对于配置是基于字符串格式获取的)

import { Controller, Get } from '@nestjs/common';
import { ModuleBService } from './moduleb.service';
import {ConfigService} from  "@nestjs/config"
import  type {PGDBConfig} from "./config"
@Controller("mb")
export class ModuleBController {constructor(private readonly moduleBService: ModuleBService, private readonly configService: ConfigService) {}@Get("/")getHello(): string {const query = this.configService.get<PGDBConfig>('db.postgres');return `Host: ${JSON.stringify(query)}, Message: ${this.moduleBService.getHello()}`;}
}

说明

从使用上midwayjs 的似乎是是挺不错的实践,但是nestjs 比较符合nestjs 的模块,服务,ioc 的套路,同时注入配置注册为全局,我们的子模块使用也是很不错的,官方文档很值得看看

参考资料

https://docs.nestjs.com/techniques/configuration