UNPKG

@elastic.io/component-commons-library

Version:
53 lines (52 loc) 2.35 kB
"use strict"; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", { value: true }); exports.PlatformApiRestClient = void 0; const package_json_1 = __importDefault(require("../../package.json")); const index_1 = require("../externalApi/index"); const axiosVersion = package_json_1.default.dependencies.axios; class PlatformApiRestClient { constructor(emitter, cfg, userAgent, msgId) { if (!!cfg.email !== !!cfg.apiKey) { throw new Error('Either both Email and API Key need to be provided or neither should be provided.'); } if (!!cfg.url && (!cfg.email || !cfg.apiKey)) { throw new Error('If providing a Platform Instance URL, then an Email and API Key need to be provided as well.'); } const baseUrl = (cfg.url || process.env.ELASTICIO_API_URI).trim().replace(/\/$/g, ''); this.baseUrl = `${baseUrl}/v2`; this.username = cfg.email || process.env.ELASTICIO_API_USERNAME; this.password = cfg.apiKey || process.env.ELASTICIO_API_KEY; this.logger = emitter.logger; this.usingTaskUser = !cfg.email; this.logger.debug(`Will connect to ${baseUrl} as ${this.usingTaskUser ? 'task' : 'specified'} user`); this.msgId = msgId; this.userAgentHeaders = { 'User-Agent': `${userAgent || ''} axios/${axiosVersion}`, 'x-request-id': `f:${process.env.ELASTICIO_FLOW_ID};s:${process.env.ELASTICIO_STEP_ID};m:${this.msgId}`, }; } async makeRequest(options) { const { url, method, body, headers = {} } = options; this.logger.debug(`Making ${method} request...`); const requestOptions = { method, baseURL: this.baseUrl, url: url.trim(), data: body, headers: { ...headers, ...this.userAgentHeaders, }, auth: { username: this.username, password: this.password, }, }; const response = await (0, index_1.axiosReqWithRetryOnServerError)(requestOptions, undefined, this.logger); return response.data; } } exports.PlatformApiRestClient = PlatformApiRestClient;