UNPKG

backendless-consul-config-provider

Version:

Consul Configs provider for Backendless' JS Servers

82 lines (63 loc) 2.7 kB
'use strict' const Utils = require('./utils') const ConsulApi = require('./consul-api') const Logger = require('./logger') const BL_PROPERTY_PREFIX = 'BL_PROPERTY_' const COMMON_CONFIG = { apiUrl : 'config/server/httpAddress', apiHost : 'config/server/internalHost', apiPort : 'config/server/internalPort', apiProtocol: 'config/server/internalProtocol', apiUri : 'config/server/internalUri', repoPath : 'config/repository/location', } exports.provide = ({ url, aclToken, serviceKey, extraKeys }) => { aclToken = aclToken || process.env.BL_CONSUL_ACL_TOKEN delete process.env.BL_CONSUL_ACL_TOKEN Logger.info('====================================================================') Logger.info('===================== CONSUL CONFIG PROVIDER =======================') Logger.info('Run Consul Configs provider') const consulApi = new ConsulApi(url, aclToken) const envConfigs = {} Object .keys(process.env) .forEach(key => { if (key.startsWith(BL_PROPERTY_PREFIX)) { envConfigs[key.replace(BL_PROPERTY_PREFIX, '').replace(/_/g, '/')] = process.env[key] } }) Logger.info(`Additional config from ENV:${ JSON.stringify(envConfigs) }`) return Promise.resolve() .then(() => loadServiceConfigs({ consulApi, serviceKey, envConfigs })) .then(serviceConfig => buildConfig({ consulApi, serviceConfig, extraKeys, envConfigs })) .then(config => { Logger.info(`Completed building configuration from Consul`) Logger.info(JSON.stringify(config)) Logger.info('===================== CONSUL CONFIG PROVIDER =======================') Logger.info('====================================================================') return config }) } function loadServiceConfigs({ consulApi, serviceKey, envConfigs }) { Logger.info('Check if Consul is ready for work...') return Promise.resolve() .then(() => consulApi.loadItemsTreeByKey(serviceKey, envConfigs)) .catch(error => { Logger.error(`Could not load or build configs, wait a little and try again...`, error) return Utils.wait(5000).then(() => loadServiceConfigs({ consulApi, serviceKey, envConfigs })) }) } function buildConfig({ consulApi, serviceConfig, extraKeys, envConfigs }) { return Promise .all([ consulApi.loadItemsTreeBySchema(COMMON_CONFIG, envConfigs), consulApi.loadItemsTreeBySchema(extraKeys, envConfigs) ]) .then(([commonConfig, extraConfig]) => { let result = {} result = Utils.mergeObjects(result, commonConfig) result = Utils.mergeObjects(result, extraConfig) result = Utils.mergeObjects(result, serviceConfig) return result }) }