import { Agent, EggApplication } from 'egg';
import * as fs from 'fs';
import * as path from 'path';
import * as assert from 'assert';
import * as YAML from 'yamljs';
import * as is from 'is-type-of';
export const nacosRuntimeFile = './run/nacos-remote-config.json';
export const deepGet = (object, path, defaultValue?) => {
return (
(!Array.isArray(path)
? path
.replace(/\[/g, '.')
.replace(/\]/g, '')
.split('.')
: path
).reduce((o, k) => (o || {})[k], object) || defaultValue
);
};
export const depthSearch = (obj, config) => {
const regular = /^\$\{(.*)+\}$/;
for (const index in obj) {
const item = obj[index];
if (is.object(item)) {
depthSearch(item, config);
} else if (is.string(item) && regular.test(item)) {
const temp = item.match(regular);
obj[index] = deepGet(config, temp[1], '');
}
}
};
export const saveNacosRemoteConfig = async (agent: Agent) => {
const { nacosConfig, config } = agent;
try {
const configs = await nacosConfig.getAllConfigs();
if (configs.length < 1) {
throw new Error('Nacos配置信息未找到');
}
const configData = YAML.parse(Object.values(configs[0])[0]);
const tempConfigFile = path.join(agent.baseDir, nacosRuntimeFile);
fs.writeFileSync(tempConfigFile, JSON.stringify(configData));
} catch (err) {
agent.logger.error(err);
throw new Error('Nacos配置信息获取失败!');
}
};
export const initNacosConfig = (app: EggApplication) => {
const tempConfigFile = path.join(app.baseDir, nacosRuntimeFile);
try {
const content = fs.readFileSync(tempConfigFile);
const remoteConfig = JSON.parse(content.toString());
depthSearch(app.config, remoteConfig);
} catch (err) {
app.logger.error('nacos配置文件读取失败!');
throw err;
}
};