UNPKG

cloud-conf

Version:

node micservice config resolver client

85 lines 3.44 kB
"use strict"; var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; var __importStar = (this && this.__importStar) || function (mod) { if (mod && mod.__esModule) return mod; var result = {}; if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k]; result["default"] = mod; return result; }; Object.defineProperty(exports, "__esModule", { value: true }); const lodash_1 = __importDefault(require("lodash")); const pwd = process.cwd(); const yaml = require("node-yaml"); const path = __importStar(require("path")); const cloud_error_1 = __importDefault(require("cloud-error")); class Config { ready() { return __awaiter(this, void 0, void 0, function* () { //分析 let obj = yield yaml.read(path.resolve(pwd, 'config.yml')); try { const localConfig = yield yaml.read(path.resolve(pwd, 'config.local.yml')); obj = Object.assign(obj, localConfig); } catch (err) { console.debug(err); } obj = replaceEnv(obj); for (let key in obj) { this[key] = obj[key]; } if (this.name === undefined || this.port === undefined || this.env === undefined) { throw cloud_error_1.default.CUSTOMER_ERROR(400, 'config.yml config.name or config.port or config.env maybe undefined!'); } return this; }); } } exports.Config = Config; const reg = /\$\{([^}^{]+)\}/; function replaceEnv(obj) { return lodash_1.default.transform(obj, function (result, value, index) { if (typeof value == 'string') { let groups = reg.exec(value); if (groups && groups.length) { let val = groups[1]; let idx = val.indexOf(":"); let envName = val.substr(0, idx); let defaultVal = val.substr(idx + 1); defaultVal = defaultVal.replace(/^(\"|\')/, ''); defaultVal = defaultVal.replace(/[\"\']\s*$/, ''); //替换环境变量 let envVal = process.env[envName]; if (!envVal) { envVal = defaultVal; } value = value.replace(reg, envVal); } } if (value instanceof RegExp) { value = value.toString(); } if (value instanceof Date) { value = value.toISOString(); } if (typeof value == 'object') { value = replaceEnv(value); } result[index] = value; return result; }); } const C = new Config(); exports.default = C; //# sourceMappingURL=index.js.map