"use strict"; var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault"); Object.defineProperty(exports, "__esModule", { value: true }); exports.callApi = callApi; exports.clearCache = clearCache; var _lodash = require("lodash"); var _lruCache = _interopRequireDefault(require("lru-cache")); var _objectHash = _interopRequireDefault(require("object-hash")); var _public = require("@kbn/observability-plugin/public"); /* * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one * or more contributor license agreements. Licensed under the Elastic License * 2.0; you may not use this file except in compliance with the Elastic License * 2.0. */ function fetchOptionsWithDebug(fetchOptions, inspectableEsQueriesEnabled) { const debugEnabled = inspectableEsQueriesEnabled && (0, _lodash.startsWith)(fetchOptions.pathname, '/internal/apm'); const { body, ...rest } = fetchOptions; return { ...rest, ...(body !== undefined ? { body: JSON.stringify(body) } : {}), query: { ...fetchOptions.query, ...(debugEnabled ? { _inspect: true } : {}) } }; } const cache = new _lruCache.default({ max: 100, maxAge: 1000 * 60 * 60 }); function clearCache() { cache.reset(); } async function callApi({ http, uiSettings }, fetchOptions) { const inspectableEsQueriesEnabled = uiSettings.get(_public.enableInspectEsQueries); const cacheKey = getCacheKey(fetchOptions); const cacheResponse = cache.get(cacheKey); if (cacheResponse) { return cacheResponse; } const { pathname, method = 'get', ...options } = fetchOptionsWithDebug(fetchOptions, inspectableEsQueriesEnabled); const lowercaseMethod = method.toLowerCase(); const res = await http[lowercaseMethod](pathname, options); if (isCachable(fetchOptions)) { cache.set(cacheKey, res); } return res; } // only cache items that has a time range with `start` and `end` params, // and where `end` is not a timestamp in the future function isCachable(fetchOptions) { if (fetchOptions.isCachable !== undefined) { return fetchOptions.isCachable; } if (!(fetchOptions.query && fetchOptions.query.start && fetchOptions.query.end)) { return false; } return (0, _lodash.isString)(fetchOptions.query.end) && new Date(fetchOptions.query.end).getTime() < Date.now(); } // order the options object to make sure that two objects with the same arguments, produce produce the // same cache key regardless of the order of properties function getCacheKey(options) { const { pathname, method, body, query, headers } = options; return (0, _objectHash.default)({ pathname, method, body, query, headers }); }