@jiaxinjiang/nest-nacos
Version:
Nacos component for NestJs.
87 lines • 3.4 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.createNacosConfigService = exports.NacosConfigService = exports.ConfigStore = void 0;
const events_1 = require("events");
const common_1 = require("@nestjs/common");
const nacos_config_constants_1 = require("./nacos.config.constants");
const nacos_config_client_1 = require("./nacos.config.client");
class ConfigStore extends events_1.EventEmitter {
get config() {
return ConfigStore._config;
}
set(key, value) {
this.config.set(key, value);
}
get(key, defaultValue) {
return this.config.get(key) || defaultValue;
}
}
exports.ConfigStore = ConfigStore;
ConfigStore._config = new Map();
class NacosConfigService {
constructor(options) {
this.options = options;
this.configClient = null;
this.configStore = new ConfigStore();
this.listeners = new Array();
this.logger = options.logger || new common_1.Logger();
this.logger.setContext('NacosConfigService');
}
getListeners() {
return this.listeners;
}
getConfigStore() {
return this.configStore;
}
getConfigClient() {
return this.configClient;
}
clearListeners() {
this.listeners.length = 0;
}
getConfigKey(dataId, groupName = 'DEFAULT_GROUP') {
return `${groupName}_${dataId}`;
}
async init() {
this.logger.log('Nacos Config Initializing...');
this.configClient = new nacos_config_client_1.NacosConfigClient(this.options.configClient);
await this.configClient.ready();
for (const configOptions of (this.options.configs || [])) {
const { dataId, groupName, options = {} } = configOptions;
const configKey = this.getConfigKey(dataId, groupName);
const remoteConfig = await this.configClient.getConfig(dataId, groupName, Object.assign({}, options));
this.configStore.set(configKey, remoteConfig);
this.logger.log(`Subscribed Nacos Config! group: ${groupName} configId: ${dataId}`);
this.listeners.push({
dataId,
groupName,
listener: (content) => {
this.logger.log(`Nacos Config update! group: ${groupName} configId: ${dataId}`);
this.configStore.set(configKey, content);
this.configStore.emit('change', configKey, content);
},
});
}
this.listeners.forEach(({ dataId, groupName, listener }) => this.configClient.subscribe({ dataId, group: groupName }, listener));
}
async unSubscribe() {
for (const { dataId, groupName, listener } of this.listeners) {
this.configClient.unSubscribe({ dataId, groupName }, listener);
}
this.listeners.length = 0;
}
}
exports.NacosConfigService = NacosConfigService;
function createNacosConfigService() {
return {
provide: NacosConfigService,
useFactory: async (options) => {
const nacosConfigService = new NacosConfigService(options);
await nacosConfigService.init();
return nacosConfigService;
},
inject: [nacos_config_constants_1.NACOS_CONFIG_OPTION],
};
}
exports.createNacosConfigService = createNacosConfigService;
//# sourceMappingURL=nacos.config.service.js.map