-
Notifications
You must be signed in to change notification settings - Fork 8.1k
/
callApi.ts
77 lines (64 loc) · 2.06 KB
/
callApi.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
/*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License;
* you may not use this file except in compliance with the Elastic License.
*/
import { FetchOptions } from 'apollo-link-http';
import { isString, startsWith } from 'lodash';
import LRU from 'lru-cache';
import hash from 'object-hash';
import { kfetch, KFetchOptions } from 'ui/kfetch';
import { KFetchKibanaOptions } from 'ui/kfetch/kfetch';
function fetchOptionsWithDebug(fetchOptions: KFetchOptions) {
const debugEnabled =
sessionStorage.getItem('apm_debug') === 'true' &&
startsWith(fetchOptions.pathname, '/api/apm');
if (!debugEnabled) {
return fetchOptions;
}
return {
...fetchOptions,
query: {
...fetchOptions.query,
_debug: true
}
};
}
const cache = new LRU<string, any>({ max: 100, maxAge: 1000 * 60 * 60 });
export function _clearCache() {
cache.reset();
}
export async function callApi<T = void>(
fetchOptions: KFetchOptions,
options?: KFetchKibanaOptions
): Promise<T> {
const cacheKey = getCacheKey(fetchOptions);
const cacheResponse = cache.get(cacheKey);
if (cacheResponse) {
return cacheResponse;
}
const combinedFetchOptions = fetchOptionsWithDebug(fetchOptions);
const res = await kfetch(combinedFetchOptions, 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: KFetchOptions) {
if (
!(fetchOptions.query && fetchOptions.query.start && fetchOptions.query.end)
) {
return false;
}
return (
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: FetchOptions) {
return hash(options);
}