forked from RedHatInsights/curiosity-frontend
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserviceConfig.js
More file actions
390 lines (339 loc) · 12.1 KB
/
Copy pathserviceConfig.js
File metadata and controls
390 lines (339 loc) · 12.1 KB
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
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
import axios, { CancelToken } from 'axios';
import { LRUCache } from 'lru-cache';
import { serviceHelpers } from './helpers';
/**
* Axios config for cancelling, caching, and emulated service calls.
*
* @memberof Helpers
* @module ServiceConfig
*/
/**
* Set Axios XHR default timeout.
*
* @type {number}
*/
const globalXhrTimeout = Number.parseInt(process.env.REACT_APP_AJAX_TIMEOUT, 10) || 60000;
/**
* Set Axios polling default.
*
* @type {number}
*/
const globalPollInterval = Number.parseInt(process.env.REACT_APP_AJAX_POLL_INTERVAL, 10) || 10000;
/**
* Cache Axios service call cancel tokens.
*
* @type {object}
*/
const globalCancelTokens = {};
/**
* Cache Axios service call responses.
*
* @type {object}
*/
const globalResponseCache = new LRUCache({
ttl: Number.parseInt(process.env.REACT_APP_AJAX_CACHE, 10) || 30000,
max: 100,
updateAgeOnGet: true
});
/**
* Set Axios configuration. This includes response schema validation and caching.
* Call platform "getUser" auth method, and apply service config. Service configuration
* includes the ability to cancel all and specific calls, cache and normalize a response
* based on both a provided schema and a successful API response. The cache will refresh
* its timeout on continuous calls. To reset it a user will either need to refresh the
* page or wait the "maxAge".
*
* @param {object} config
* @param {object} config.cache
* @param {boolean} config.cancel
* @param {string} config.cancelId
* @param {object} config.params
* @param {{location: Function|string|{url: string|Function, config: serviceConfig}, validate: Function,
* pollInterval: number, status: Function}|Function} config.poll
* @param {Array} config.schema
* @param {Array} config.transform
* @param {string|Function} config.url
* @param {object} options
* @param {string} options.cancelledMessage
* @param {object} options.responseCache
* @param {number} options.xhrTimeout
* @param {number} options.pollInterval
* @returns {Promise<*>}
*/
const axiosServiceCall = async (
config = {},
{
cancelledMessage = 'cancelled request',
responseCache = globalResponseCache,
xhrTimeout = globalXhrTimeout,
pollInterval = globalPollInterval
} = {}
) => {
const updatedConfig = {
timeout: xhrTimeout,
...config,
cache: undefined,
cacheResponse: config.cache,
method: config.method || 'get'
};
const responseTransformers = [];
const axiosInstance = axios.create();
// don't cache responses if "get" isn't used
updatedConfig.cacheResponse = updatedConfig.cacheResponse === true && updatedConfig.method === 'get';
// account for alterations to transforms, and other config props
const cacheId = (updatedConfig.cacheResponse === true && serviceHelpers.generateHash(updatedConfig)) || null;
// simple check to place responsibility on consumer, primarily used for testing
if (updatedConfig.exposeCacheId === true) {
updatedConfig.cacheId = cacheId;
}
// apply cancel configuration
if (updatedConfig.cancel === true) {
const cancelTokensId =
updatedConfig.cancelId || serviceHelpers.generateHash({ ...updatedConfig, data: undefined, params: undefined });
if (globalCancelTokens[cancelTokensId]) {
await globalCancelTokens[cancelTokensId].cancel(cancelledMessage);
}
globalCancelTokens[cancelTokensId] = CancelToken.source();
updatedConfig.cancelToken = globalCancelTokens[cancelTokensId].token;
delete updatedConfig.cancel;
}
// if cached response return
if (updatedConfig.cacheResponse === true) {
const cachedResponse = responseCache.get(cacheId);
if (cachedResponse) {
updatedConfig.adapter = adapterConfig =>
Promise.resolve({
...cachedResponse,
status: 304,
statusText: 'Not Modified',
config: adapterConfig
});
return axiosInstance(updatedConfig);
}
}
// if schema transform, add before standard transform
if (updatedConfig.schema) {
responseTransformers.push(updatedConfig.schema);
}
// add response transformers
if (updatedConfig.transform) {
responseTransformers.push(updatedConfig.transform);
}
// apply response transformers
responseTransformers.forEach(([successTransform, errorTransform]) => {
const transformers = [undefined, response => Promise.reject(response)];
if (successTransform) {
transformers[0] = response => {
const updatedResponse = { ...response };
const { data, error: normalizeError } = serviceHelpers.passDataToCallback(
successTransform,
serviceHelpers.memoClone(updatedResponse.data),
serviceHelpers.memoClone(updatedResponse.config)
);
if (normalizeError) {
console.warn(normalizeError);
} else {
updatedResponse.data = data;
}
return updatedResponse;
};
}
if (errorTransform) {
transformers[1] = response => {
const updatedResponse = { ...(response.response || response) };
if (updatedResponse?.message === cancelledMessage || updatedResponse?.code === 'ERR_CANCELED') {
const updatedCancelResponse = { ...updatedResponse, message: updatedResponse?.message || cancelledMessage };
return Promise.reject(updatedCancelResponse);
}
// Note: Reevaluate memoClone, it was removed from data/message because it was interfering with passed errors.
const { data, error: normalizeError } = serviceHelpers.passDataToCallback(
errorTransform,
updatedResponse?.data || updatedResponse?.message,
serviceHelpers.memoClone(updatedResponse.config)
);
if (normalizeError) {
console.warn(normalizeError);
} else {
updatedResponse.response = { ...updatedResponse, data };
}
return Promise.reject(updatedResponse);
};
}
axiosInstance.interceptors.response.use(...transformers);
});
// apply a response to cache
if (updatedConfig.cacheResponse === true) {
axiosInstance.interceptors.response.use(
response => {
const updatedResponse = { ...response };
responseCache.set(cacheId, updatedResponse);
return updatedResponse;
},
response => Promise.reject(response)
);
}
// use a function instead of a url-string, receive service emulated output (for implementation consistency)
if (typeof updatedConfig.url === 'function') {
const emulateCallback = updatedConfig.url;
updatedConfig.url = '/emulated';
let message = 'success, emulated';
let emulatedResponse;
let isSuccess = true;
let emulatedErrorStatus = 418;
try {
emulatedResponse = await serviceHelpers.timeoutFunctionCancel(emulateCallback, { timeout: xhrTimeout });
} catch (err) {
emulatedResponse = err?.data || err;
isSuccess = false;
message = err?.message || err || 'Unknown error';
emulatedErrorStatus = err?.status || err?.response?.status || emulatedErrorStatus;
}
if (isSuccess) {
updatedConfig.adapter = adapterConfig =>
Promise.resolve({
data: emulatedResponse,
status: 200,
statusText: message,
config: adapterConfig
});
} else {
updatedConfig.adapter = adapterConfig =>
Promise.reject({ // eslint-disable-line
...new Error(message),
message,
data: emulatedResponse,
status: emulatedErrorStatus,
config: adapterConfig
});
}
}
// apply a response poll
if (typeof updatedConfig.poll === 'function' || typeof updatedConfig.poll?.validate === 'function') {
axiosInstance.interceptors.response.use(
async response => {
const updatedResponse = { ...response };
const callbackResponse = serviceHelpers.memoClone(updatedResponse);
const updatedLocation = { url: undefined, config: undefined };
if (
!updatedConfig.poll.location ||
typeof updatedConfig.poll.location === 'string' ||
typeof updatedConfig.poll.location === 'function'
) {
updatedLocation.url = updatedConfig.poll.location || updatedConfig.url;
}
if (updatedConfig.poll.location?.url) {
updatedLocation.url = updatedConfig.poll.location.url;
updatedLocation.config = updatedConfig.poll.location.config;
}
// passed config, allow future updates by passing a modified poll config into a setTimeout
const updatedPoll = {
...updatedConfig.poll,
// internal counter passed towards validate and status
__retryCount: updatedConfig.poll.__retryCount ?? -1,
// url, callback that returns a url to poll, or object { url: string|Function, config: serviceConfig }
location: updatedLocation,
// only required param, a function, validate status in prep for next
validate: updatedConfig.poll.validate || updatedConfig.poll,
// a number, the setTimeout interval
pollInterval: updatedConfig.poll.pollInterval || pollInterval
};
let validated;
try {
validated = await updatedPoll.validate.call(null, callbackResponse, updatedPoll.__retryCount);
} catch (err) {
console.error(err);
validated = true;
}
if (validated === true) {
return updatedResponse;
}
let tempLocationUrl = updatedPoll.location.url;
if (typeof tempLocationUrl === 'function') {
try {
tempLocationUrl = await tempLocationUrl.call(null, callbackResponse, updatedPoll.__retryCount);
} catch (err) {
console.error(err);
tempLocationUrl = updatedConfig.url;
}
}
const pollResponse = new Promise((resolve, reject) => {
const setupPoll = async retryCount => {
try {
const output = await axiosServiceCall({
...config,
...updatedPoll.location.config,
method: 'get',
data: undefined,
url: tempLocationUrl,
cache: false,
poll: { ...updatedPoll, __retryCount: retryCount }
});
resolve(output);
} catch (e) {
reject(e);
}
};
if (updatedPoll.__retryCount < 0) {
if (typeof updatedPoll.status === 'function') {
try {
updatedPoll.status.call(null, undefined, updatedPoll.__retryCount);
} catch (err) {
console.error(err);
}
}
}
updatedPoll.__retryCount += 1;
window.setTimeout(async () => setupPoll(updatedPoll.__retryCount), updatedPoll.pollInterval);
});
// either apply a status resolver for up-to-date responses or chain poll-response to the response
if (typeof updatedPoll.status === 'function') {
pollResponse.then(
resolved => {
try {
updatedPoll.status.call(
null,
{ ...resolved, error: false, status: resolved?.response?.status },
updatedPoll.__retryCount
);
} catch (err) {
console.error(err);
}
},
resolved => {
try {
updatedPoll.status.call(
null,
{ ...resolved, error: true, status: resolved?.response?.status },
updatedPoll.__retryCount
);
} catch (err) {
console.error(err);
}
}
);
} else {
return pollResponse;
}
return updatedResponse;
},
response => Promise.reject(response)
);
}
return axiosInstance(updatedConfig);
};
const serviceConfig = {
axiosServiceCall,
globalXhrTimeout,
globalPollInterval,
globalCancelTokens,
globalResponseCache
};
export {
serviceConfig as default,
serviceConfig,
axiosServiceCall,
globalXhrTimeout,
globalPollInterval,
globalCancelTokens,
globalResponseCache
};