UNPKG

af-consul

Version:

A highly specialized function library

50 lines 2.33 kB
/* eslint-disable no-console */ // noinspection JSUnusedGlobalSymbols import { getConsulApiCached } from './prepare-consul-api'; import { CONSUL_DEBUG_ON, MAX_API_CACHED, PREFIX } from './constants'; import { getConfigHash } from './lib/hash'; import { getRegisterConfig } from './get-register-config'; import { minimizeCache } from './lib/utils'; import { getRegisterCyclic } from './cyclic-register'; import { magenta, reset, yellow } from './lib/color'; export { accessPointsUpdater } from './access-points/access-points-updater'; const defaultGetConsulUIAddress = (serviceId) => { const { NODE_ENV, CONSUL_UI_HOST, CONSUL_DC_PROD, CONSUL_DC_DEV } = process.env; const p = NODE_ENV === 'production'; return `https://${CONSUL_UI_HOST || ''}/ui/dc-${p ? (CONSUL_DC_PROD || 'prd') : (CONSUL_DC_DEV || 'dev')}/services/${serviceId}/instances`; }; const debug = (msg) => { if (CONSUL_DEBUG_ON) { console.log(`${magenta}${PREFIX}${reset}: ${msg}`); } }; // cached export const apiCache = {}; export const getAPI = async (options) => { var _a; const hash = getConfigHash(options); if (!apiCache[hash]) { const api = await getConsulApiCached(options); const registerConfig = await getRegisterConfig(options); const serviceId = registerConfig.id; minimizeCache(apiCache, MAX_API_CACHED); (_a = options.logger) === null || _a === void 0 ? void 0 : _a.info(`Consul UI: ${(options.getConsulUIAddress || defaultGetConsulUIAddress)(serviceId)}`); debug(`${yellow} REGISTER CONFIG:\n${JSON.stringify(registerConfig, undefined, 2)}\n${reset}`); const value = { registerConfig, serviceId, register: { once: async (registerType = 'if-not-registered') => api.registerService(registerConfig, { registerType }), cyclic: getRegisterCyclic(options, api, registerConfig), }, deregister: (svcId, agentOptions) => api.deregisterIfNeed(svcId || serviceId, agentOptions), }; Object.entries(api).forEach(([k, v]) => { // @ts-ignore value[k] = typeof v === 'function' ? v.bind(api) : v; }); apiCache[hash] = { created: Date.now(), value }; } return apiCache[hash].value; }; //# sourceMappingURL=get-api.js.map