UNPKG

@alova/wormhole

Version:

More modern openAPI generating solution for alova.js

87 lines (86 loc) 3.23 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.configManager = exports.ConfigManager = void 0; const lodash_1 = require("lodash"); const zod_validation_error_1 = require("zod-validation-error"); const helper_1 = require("../../helper"); const GeneratorHelper_1 = require("../../helper/config/GeneratorHelper"); const zType_1 = require("./zType"); class ConfigManager { constructor() { this.defaultConfig = Object.freeze({ generator: [], autoUpdate: true, }); this.defaultGeneratorConfig = (0, lodash_1.omit)(GeneratorHelper_1.generatorHelper.getDefaultConfig(), ['global']); this.defaultOneGeneratorConfig = GeneratorHelper_1.generatorHelper.getDefaultConfig(); this.config = this.defaultConfig; } static getInstance() { if (!ConfigManager.instance) { ConfigManager.instance = new ConfigManager(); } return ConfigManager.instance; } /** * 加载并验证配置 */ async load(config) { // 合并配置 const mergedConfig = this.mergeConfig(this.defaultConfig, config); // 验证配置 const validatedConfig = this.validateConfig(mergedConfig); // 更新配置 this.config = validatedConfig; this.readConfig = Object.freeze(this.config); helper_1.logger.debug('Configuration loaded successfully', this.config); } /** * 获取完整配置 */ getConfig() { return this.readConfig; } /** * 更新配置 */ async update(partialConfig) { await this.load({ ...this.config, ...partialConfig }); } /** * 验证配置 */ validateConfig(config) { let result = config; try { result = zType_1.zConfig.parse(config); } catch (error) { const zError = (0, zod_validation_error_1.fromError)(error); throw helper_1.logger.throwError(zError.message, zError.details); } return result; } /** * 深度合并配置 */ mergeConfig(defaultConfig, userConfig) { const merged = { ...defaultConfig }; const mergeHandle = (root = '') => (defaultValue, userValue, key) => { if (!root && key === 'generator' && (0, lodash_1.isArray)(userValue)) { return userValue.map((generatorConfig, idx) => (0, lodash_1.mergeWith)({ ...(userValue.length > 1 ? this.defaultGeneratorConfig : this.defaultOneGeneratorConfig) }, generatorConfig, mergeHandle(root ? `${root}.${key}.${idx}` : `${key}.${idx}`))); } if (Array.isArray(userValue)) { return userValue; // 源数组优先级最高 } if ((0, lodash_1.isObject)(defaultValue) && (0, lodash_1.isObject)(userValue)) { return (0, lodash_1.mergeWith)(defaultValue, userValue, mergeHandle(root ? `${root}.${key}` : key)); } }; const result = (0, lodash_1.mergeWith)(merged, userConfig, mergeHandle()); return result; } } exports.ConfigManager = ConfigManager; // 导出单例实例 exports.configManager = ConfigManager.getInstance();