UNPKG

@nexe/config-manager

Version:

Nexe Config Manager - A flexible configuration management solution with multiple sources and hot reload support

273 lines 9.62 kB
"use strict"; // /** // * 配置系统装饰器使用示例 // * // * 这个示例演示了如何使用装饰器定义配置类并使用它们 // * // * 运行方式: // * bun src/shared/infrastructure/config/examples/annotation-example.ts // */ // // 必须首先导入reflect-metadata // import * as fs from 'fs'; // import * as path from 'path'; // import 'reflect-metadata'; // import { container } from 'tsyringe'; // import { // ConfigManager, // ConfigProperty, // ConfigSection, // EnvironmentConfigSource, // JsonConfigSource, // YamlConfigSource, // } from '..'; // // 创建测试配置文件 - 使用当前脚本所在目录 // const SCRIPT_DIR = path.dirname(new URL(import.meta.url).pathname); // const CONFIG_DIR = path.join(SCRIPT_DIR, 'config'); // const JSON_CONFIG_PATH = path.join(CONFIG_DIR, 'config.json'); // const YAML_CONFIG_PATH = path.join(CONFIG_DIR, 'config.yaml'); // console.log(`📂 配置目录: ${CONFIG_DIR}`); // console.log(`📄 YAML配置文件: ${YAML_CONFIG_PATH}`); // // 确保配置目录存在 // if (!fs.existsSync(CONFIG_DIR)) { // fs.mkdirSync(CONFIG_DIR, { recursive: true }); // } // // 创建JSON测试配置文件 // if (!fs.existsSync(JSON_CONFIG_PATH)) { // const jsonConfig = { // app: { // name: 'Elysia应用', // description: '示例配置文件', // version: '1.0.0', // }, // server: { // port: 3000, // host: 'localhost', // maxConnections: 100, // }, // database: { // host: 'localhost', // port: 5432, // username: 'postgres', // password: 'postgres123', // database: 'elysia_db', // ssl: false, // poolSize: 10, // }, // log: { // level: 'info', // format: 'json', // }, // }; // fs.writeFileSync( // JSON_CONFIG_PATH, // JSON.stringify(jsonConfig, null, 2), // 'utf-8', // ); // console.log(`✅ 创建JSON配置文件: ${JSON_CONFIG_PATH}`); // } // // 创建YAML测试配置文件 // if (!fs.existsSync(YAML_CONFIG_PATH)) { // const yamlConfig = `app: // name: Elysia应用(YAML) // description: YAML配置文件 // version: 1.0.0 // server: // port: 3001 // host: localhost // maxConnections: 200 // database: // host: db.example.com // port: 5432 // username: elysia_user // password: secure_password // database: elysia_db_test // ssl: true // poolSize: 20 // log: // level: debug // format: pretty // `; // fs.writeFileSync(YAML_CONFIG_PATH, yamlConfig, 'utf-8'); // console.log(`✅ 创建YAML配置文件: ${YAML_CONFIG_PATH}`); // } // // 设置环境变量用于测试 // process.env.APP_DATABASE_HOST = 'env-db-host'; // process.env.APP_SERVER_PORT = '4000'; // /** // * 服务器配置类示例 // */ // @ConfigSection('server') // class ServerConfig { // @ConfigProperty('port') // port = 8080; // 默认值 // @ConfigProperty('host') // host = '127.0.0.1'; // 默认值 // @ConfigProperty('maxConnections') // maxConnections = 50; // 默认值 // } // /** // * 数据库配置类示例 // */ // @ConfigSection('database') // class DatabaseConfig { // @ConfigProperty('host') // host = 'localhost'; // 默认值 // @ConfigProperty('port') // port = 5432; // 默认值 // @ConfigProperty('username') // username = ''; // @ConfigProperty('password') // password = ''; // @ConfigProperty('database') // database = ''; // @ConfigProperty('ssl') // ssl = false; // @ConfigProperty('poolSize') // poolSize = 10; // } // /** // * 日志配置类示例 // * 演示不同的配置路径 // */ // @ConfigSection('log') // class LogConfig { // @ConfigProperty('level') // level = 'info'; // @ConfigProperty('format') // format = 'json'; // // 特定的自定义配置属性 // @ConfigProperty('custom') // customSetting = 'default'; // } // /** // * 应用配置类示例 // */ // @ConfigSection('app') // class AppConfig { // @ConfigProperty('name') // name = 'Default App'; // @ConfigProperty('version') // version = '0.0.1'; // @ConfigProperty('description') // description = ''; // } // /** // * 服务类示例,展示如何在服务中使用配置 // */ // class MyService { // // 使用非空断言操作符(!)告诉TypeScript这些属性会在init方法中被初始化 // private dbConfig!: DatabaseConfig; // private serverConfig!: ServerConfig; // private initialized = false; // private initPromise: Promise<void>; // constructor(private configManager: ConfigManager) { // // 存储初始化Promise以便外部可以等待 // this.initPromise = this.init(); // } // /** // * 初始化服务 // */ // private async init(): Promise<void> { // try { // // 获取强类型配置对象 // this.dbConfig = await this.configManager.getConfig(DatabaseConfig); // this.serverConfig = await this.configManager.getConfig(ServerConfig); // console.log('\n🔧 数据库配置:'); // console.log(` - 主机: ${this.dbConfig.host}`); // console.log(` - 端口: ${this.dbConfig.port}`); // console.log(` - 数据库: ${this.dbConfig.database}`); // console.log(` - SSL: ${this.dbConfig.ssl ? '启用' : '禁用'}`); // console.log('\n🖥️ 服务器配置:'); // console.log(` - 主机: ${this.serverConfig.host}`); // console.log(` - 端口: ${this.serverConfig.port}`); // console.log(` - 最大连接数: ${this.serverConfig.maxConnections}`); // // 设置初始化完成标志 // this.initialized = true; // } catch (error) { // console.error('初始化服务失败:', error); // throw error; // } // } // /** // * 等待初始化完成 // */ // async waitForInit(): Promise<void> { // return this.initPromise; // } // /** // * 获取数据库连接字符串 // */ // getConnectionString(): string { // if (!this.initialized) { // throw new Error('服务尚未初始化完成'); // } // return `postgresql://${this.dbConfig.username}:${this.dbConfig.password}@${this.dbConfig.host}:${this.dbConfig.port}/${this.dbConfig.database}`; // } // } // /** // * 主函数 // */ // async function main(): Promise<void> { // console.log('🚀 启动配置系统示例...'); // // 创建配置管理器 // const configManager = new ConfigManager(); // // 添加多种配置源(优先级从高到低) // console.log('\n⚙️ 添加配置源:'); // console.log(' - 环境变量 (优先级: 高)'); // console.log(' - YAML 配置文件 (优先级: 中)'); // console.log(' - JSON 配置文件 (优先级: 低)'); // configManager.addSource(new EnvironmentConfigSource('APP_'), 100); // configManager.addSource(new YamlConfigSource(YAML_CONFIG_PATH, true), 50); // configManager.addSource(new JsonConfigSource(JSON_CONFIG_PATH), 10); // // 注册到容器 // container.registerInstance(ConfigManager, configManager); // // 获取并显示各种配置值 // console.log('\n📊 读取各配置源的值:'); // // 1. 直接读取原始值 // const jsonServerPort = await configManager.get<number>('server.port'); // console.log(`服务器端口 (优先级顺序): ${jsonServerPort}`); // // 2. 读取强类型配置对象 // const serverConfig = await configManager.getConfig(ServerConfig); // const dbConfig = await configManager.getConfig(DatabaseConfig); // const logConfig = await configManager.getConfig(LogConfig); // const appConfig = await configManager.getConfig(AppConfig); // console.log('\n📋 强类型配置对象:'); // console.log(' 📦 应用配置:'); // console.log(` - 名称: ${appConfig.name}`); // console.log(` - 版本: ${appConfig.version}`); // console.log(` - 描述: ${appConfig.description}`); // console.log(' 🖥️ 服务器配置:'); // console.log(` - 端口: ${serverConfig.port}`); // console.log(` - 主机: ${serverConfig.host}`); // console.log(` - 最大连接数: ${serverConfig.maxConnections}`); // console.log(' 🔧 数据库配置:'); // console.log(` - 主机: ${dbConfig.host}`); // console.log(` - 端口: ${dbConfig.port}`); // console.log(` - 用户名: ${dbConfig.username}`); // console.log(` - 数据库: ${dbConfig.database}`); // console.log(` - SSL: ${dbConfig.ssl ? '启用' : '禁用'}`); // console.log(` - 连接池大小: ${dbConfig.poolSize}`); // console.log(' 📝 日志配置:'); // console.log(` - 级别: ${logConfig.level}`); // console.log(` - 格式: ${logConfig.format}`); // console.log(` - 自定义设置: ${logConfig.customSetting}`); // // 3. 使用注入的方式在服务中使用配置 // console.log('\n🛠️ 在服务中使用配置:'); // const myService = new MyService(configManager); // // 等待服务初始化完成 // await myService.waitForInit(); // console.log(` 连接字符串: ${myService.getConnectionString()}`); // // 4. 监听配置变更 // console.log('\n👀 设置配置变更监听 (请修改配置文件后观察):'); // configManager.subscribe<number>('server.maxConnections', (newValue) => { // console.log(` 配置变更: server.maxConnections 已更新为 ${newValue}`); // }); // console.log('\n✅ 配置系统示例运行完成'); // console.log('🔍 可以尝试修改 config/config.yaml 文件后观察配置变更'); // } // // 运行主函数 // main().catch((error) => { // console.error('❌ 错误:', error); // process.exit(1); // }); //# sourceMappingURL=annotation-example.js.map