@algolia/client-common 4.14.2 → 5.0.0-alpha.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/client-common.cjs.js +803 -91
- package/dist/client-common.esm.node.js +774 -0
- package/dist/index.d.ts +10 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/src/cache/createBrowserLocalStorageCache.d.ts +3 -0
- package/dist/src/cache/createBrowserLocalStorageCache.d.ts.map +1 -0
- package/dist/src/cache/createFallbackableCache.d.ts +3 -0
- package/dist/src/cache/createFallbackableCache.d.ts.map +1 -0
- package/dist/src/cache/createMemoryCache.d.ts +3 -0
- package/dist/src/cache/createMemoryCache.d.ts.map +1 -0
- package/dist/src/cache/createNullCache.d.ts +3 -0
- package/dist/src/cache/createNullCache.d.ts.map +1 -0
- package/dist/src/cache/index.d.ts +5 -0
- package/dist/src/cache/index.d.ts.map +1 -0
- package/dist/src/constants.d.ts +7 -0
- package/dist/src/constants.d.ts.map +1 -0
- package/dist/src/createAlgoliaAgent.d.ts +3 -0
- package/dist/src/createAlgoliaAgent.d.ts.map +1 -0
- package/dist/src/createAuth.d.ts +6 -0
- package/dist/src/createAuth.d.ts.map +1 -0
- package/dist/src/createEchoRequester.d.ts +7 -0
- package/dist/src/createEchoRequester.d.ts.map +1 -0
- package/dist/src/createRetryablePromise.d.ts +14 -0
- package/dist/src/createRetryablePromise.d.ts.map +1 -0
- package/dist/src/getAlgoliaAgent.d.ts +8 -0
- package/dist/src/getAlgoliaAgent.d.ts.map +1 -0
- package/dist/src/transporter/createStatefulHost.d.ts +3 -0
- package/dist/src/transporter/createStatefulHost.d.ts.map +1 -0
- package/dist/src/transporter/createTransporter.d.ts +3 -0
- package/dist/src/transporter/createTransporter.d.ts.map +1 -0
- package/dist/src/transporter/errors.d.ts +21 -0
- package/dist/src/transporter/errors.d.ts.map +1 -0
- package/dist/src/transporter/helpers.d.ts +9 -0
- package/dist/src/transporter/helpers.d.ts.map +1 -0
- package/dist/src/transporter/index.d.ts +7 -0
- package/dist/src/transporter/index.d.ts.map +1 -0
- package/dist/src/transporter/responses.d.ts +5 -0
- package/dist/src/transporter/responses.d.ts.map +1 -0
- package/dist/src/transporter/stackTrace.d.ts +4 -0
- package/dist/src/transporter/stackTrace.d.ts.map +1 -0
- package/dist/src/types/Cache.d.ts +47 -0
- package/dist/src/types/Cache.d.ts.map +1 -0
- package/dist/src/types/CreateClient.d.ts +12 -0
- package/dist/src/types/CreateClient.d.ts.map +1 -0
- package/dist/src/types/CreateRetryablePromise.d.ts +19 -0
- package/dist/src/types/CreateRetryablePromise.d.ts.map +1 -0
- package/dist/src/types/Host.d.ts +33 -0
- package/dist/src/types/Host.d.ts.map +1 -0
- package/dist/src/types/Requester.d.ts +66 -0
- package/dist/src/types/Requester.d.ts.map +1 -0
- package/dist/src/types/Transporter.d.ts +128 -0
- package/dist/src/types/Transporter.d.ts.map +1 -0
- package/dist/src/types/index.d.ts +7 -0
- package/dist/src/types/index.d.ts.map +1 -0
- package/index.ts +9 -0
- package/package.json +24 -15
- package/src/__tests__/cache/browser-local-storage-cache.test.ts +134 -0
- package/src/__tests__/cache/fallbackable-cache.test.ts +126 -0
- package/src/__tests__/cache/memory-cache.test.ts +90 -0
- package/src/__tests__/cache/null-cache.test.ts +49 -0
- package/src/__tests__/create-retryable-promise.test.ts +86 -0
- package/src/cache/createBrowserLocalStorageCache.ts +74 -0
- package/src/cache/createFallbackableCache.ts +53 -0
- package/src/cache/createMemoryCache.ts +56 -0
- package/src/cache/createNullCache.ts +34 -0
- package/src/cache/index.ts +4 -0
- package/src/constants.ts +7 -0
- package/src/createAlgoliaAgent.ts +20 -0
- package/src/createAuth.ts +25 -0
- package/src/createEchoRequester.ts +59 -0
- package/src/createRetryablePromise.ts +52 -0
- package/src/getAlgoliaAgent.ts +25 -0
- package/src/transporter/createStatefulHost.ts +24 -0
- package/src/transporter/createTransporter.ts +347 -0
- package/src/transporter/errors.ts +51 -0
- package/src/transporter/helpers.ts +119 -0
- package/src/transporter/index.ts +6 -0
- package/src/transporter/responses.ts +23 -0
- package/src/transporter/stackTrace.ts +30 -0
- package/src/types/Cache.ts +61 -0
- package/src/types/CreateClient.ts +23 -0
- package/src/types/CreateRetryablePromise.ts +21 -0
- package/src/types/Host.ts +38 -0
- package/src/types/Requester.ts +72 -0
- package/src/types/Transporter.ts +153 -0
- package/src/types/index.ts +6 -0
- package/dist/client-common.d.ts +0 -102
- package/dist/client-common.esm.js +0 -89
- package/index.js +0 -2
|
@@ -2,100 +2,812 @@
|
|
|
2
2
|
|
|
3
3
|
Object.defineProperty(exports, '__esModule', { value: true });
|
|
4
4
|
|
|
5
|
-
function createAuth(
|
|
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
|
-
const
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
5
|
+
function createAuth(appId, apiKey, authMode = 'WithinHeaders') {
|
|
6
|
+
const credentials = {
|
|
7
|
+
'x-algolia-api-key': apiKey,
|
|
8
|
+
'x-algolia-application-id': appId
|
|
9
|
+
};
|
|
10
|
+
return {
|
|
11
|
+
headers() {
|
|
12
|
+
return authMode === 'WithinHeaders' ? credentials : {};
|
|
13
|
+
},
|
|
14
|
+
|
|
15
|
+
queryParameters() {
|
|
16
|
+
return authMode === 'WithinQueryParameters' ? credentials : {};
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
};
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
function getUrlParams({
|
|
23
|
+
host,
|
|
24
|
+
searchParams: urlSearchParams,
|
|
25
|
+
pathname
|
|
26
|
+
}) {
|
|
27
|
+
const algoliaAgent = urlSearchParams.get('x-algolia-agent') || '';
|
|
28
|
+
const searchParams = {};
|
|
29
|
+
|
|
30
|
+
for (const [k, v] of urlSearchParams) {
|
|
31
|
+
if (k === 'x-algolia-agent') {
|
|
32
|
+
continue;
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
searchParams[k] = v;
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
return {
|
|
39
|
+
host,
|
|
40
|
+
algoliaAgent,
|
|
41
|
+
searchParams: Object.keys(searchParams).length === 0 ? undefined : searchParams,
|
|
42
|
+
path: pathname
|
|
43
|
+
};
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
function createEchoRequester({
|
|
47
|
+
getURL,
|
|
48
|
+
status = 200
|
|
49
|
+
}) {
|
|
50
|
+
function send(request) {
|
|
51
|
+
const {
|
|
52
|
+
host,
|
|
53
|
+
searchParams,
|
|
54
|
+
algoliaAgent,
|
|
55
|
+
path
|
|
56
|
+
} = getUrlParams(getURL(request.url));
|
|
57
|
+
const content = { ...request,
|
|
58
|
+
data: request.data ? JSON.parse(request.data) : undefined,
|
|
59
|
+
path,
|
|
60
|
+
host,
|
|
61
|
+
algoliaAgent: encodeURI(algoliaAgent),
|
|
62
|
+
searchParams
|
|
63
|
+
};
|
|
64
|
+
return Promise.resolve({
|
|
65
|
+
content: JSON.stringify(content),
|
|
66
|
+
isTimedOut: false,
|
|
67
|
+
status
|
|
68
|
+
});
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
return {
|
|
72
|
+
send
|
|
73
|
+
};
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
const DEFAULT_MAX_RETRIES = 50;
|
|
77
|
+
const DEFAULT_TIMEOUT = retryCount => Math.min(retryCount * 200, 5000);
|
|
78
|
+
/**
|
|
79
|
+
* Return a promise that retry a task until it meets the condition.
|
|
80
|
+
*
|
|
81
|
+
* @param createRetryablePromiseOptions - The createRetryablePromise options.
|
|
82
|
+
* @param createRetryablePromiseOptions.func - The function to run, which returns a promise.
|
|
83
|
+
* @param createRetryablePromiseOptions.validate - The validator function. It receives the resolved return of `func`.
|
|
84
|
+
* @param createRetryablePromiseOptions.maxRetries - The maximum number of retries. 50 by default.
|
|
85
|
+
* @param createRetryablePromiseOptions.timeout - The function to decide how long to wait between retries.
|
|
86
|
+
*/
|
|
87
|
+
|
|
88
|
+
function createRetryablePromise({
|
|
89
|
+
func,
|
|
90
|
+
validate,
|
|
91
|
+
maxRetries = DEFAULT_MAX_RETRIES,
|
|
92
|
+
timeout = DEFAULT_TIMEOUT
|
|
93
|
+
}) {
|
|
94
|
+
let retryCount = 0;
|
|
95
|
+
|
|
96
|
+
const retry = () => {
|
|
97
|
+
return new Promise((resolve, reject) => {
|
|
98
|
+
func().then(response => {
|
|
99
|
+
const isValid = validate(response);
|
|
100
|
+
|
|
101
|
+
if (isValid) {
|
|
102
|
+
resolve(response);
|
|
103
|
+
} else if (retryCount + 1 >= maxRetries) {
|
|
104
|
+
reject(new Error(`The maximum number of retries exceeded. (${retryCount + 1}/${maxRetries})`));
|
|
105
|
+
} else {
|
|
106
|
+
retryCount += 1;
|
|
107
|
+
setTimeout(() => {
|
|
108
|
+
retry().then(resolve).catch(reject);
|
|
109
|
+
}, timeout(retryCount));
|
|
110
|
+
}
|
|
111
|
+
}).catch(error => {
|
|
112
|
+
reject(error);
|
|
113
|
+
});
|
|
114
|
+
});
|
|
115
|
+
};
|
|
116
|
+
|
|
117
|
+
return retry();
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
function createBrowserLocalStorageCache(options) {
|
|
121
|
+
let storage; // We've changed the namespace to avoid conflicts with v4, as this version is a huge breaking change
|
|
122
|
+
|
|
123
|
+
const namespaceKey = `algolia-client-js-${options.key}`;
|
|
124
|
+
|
|
125
|
+
function getStorage() {
|
|
126
|
+
if (storage === undefined) {
|
|
127
|
+
storage = options.localStorage || window.localStorage;
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
return storage;
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
function getNamespace() {
|
|
134
|
+
return JSON.parse(getStorage().getItem(namespaceKey) || '{}');
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
return {
|
|
138
|
+
get(key, defaultValue, events = {
|
|
139
|
+
miss: () => Promise.resolve()
|
|
140
|
+
}) {
|
|
141
|
+
return Promise.resolve().then(() => {
|
|
142
|
+
const keyAsString = JSON.stringify(key);
|
|
143
|
+
const value = getNamespace()[keyAsString];
|
|
144
|
+
return Promise.all([value || defaultValue(), value !== undefined]);
|
|
145
|
+
}).then(([value, exists]) => {
|
|
146
|
+
return Promise.all([value, exists || events.miss(value)]);
|
|
147
|
+
}).then(([value]) => value);
|
|
148
|
+
},
|
|
149
|
+
|
|
150
|
+
set(key, value) {
|
|
151
|
+
return Promise.resolve().then(() => {
|
|
152
|
+
const namespace = getNamespace();
|
|
153
|
+
namespace[JSON.stringify(key)] = value;
|
|
154
|
+
getStorage().setItem(namespaceKey, JSON.stringify(namespace));
|
|
155
|
+
return value;
|
|
156
|
+
});
|
|
157
|
+
},
|
|
158
|
+
|
|
159
|
+
delete(key) {
|
|
160
|
+
return Promise.resolve().then(() => {
|
|
161
|
+
const namespace = getNamespace();
|
|
162
|
+
delete namespace[JSON.stringify(key)];
|
|
163
|
+
getStorage().setItem(namespaceKey, JSON.stringify(namespace));
|
|
164
|
+
});
|
|
165
|
+
},
|
|
166
|
+
|
|
167
|
+
clear() {
|
|
168
|
+
return Promise.resolve().then(() => {
|
|
169
|
+
getStorage().removeItem(namespaceKey);
|
|
170
|
+
});
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
};
|
|
174
|
+
}
|
|
175
|
+
|
|
176
|
+
function createNullCache() {
|
|
177
|
+
return {
|
|
178
|
+
get(_key, defaultValue, events = {
|
|
179
|
+
miss: () => Promise.resolve()
|
|
180
|
+
}) {
|
|
181
|
+
const value = defaultValue();
|
|
182
|
+
return value.then(result => Promise.all([result, events.miss(result)])).then(([result]) => result);
|
|
183
|
+
},
|
|
184
|
+
|
|
185
|
+
set(_key, value) {
|
|
186
|
+
return Promise.resolve(value);
|
|
187
|
+
},
|
|
188
|
+
|
|
189
|
+
delete(_key) {
|
|
190
|
+
return Promise.resolve();
|
|
191
|
+
},
|
|
192
|
+
|
|
193
|
+
clear() {
|
|
194
|
+
return Promise.resolve();
|
|
195
|
+
}
|
|
196
|
+
|
|
197
|
+
};
|
|
198
|
+
}
|
|
199
|
+
|
|
200
|
+
function createFallbackableCache(options) {
|
|
201
|
+
const caches = [...options.caches];
|
|
202
|
+
const current = caches.shift();
|
|
203
|
+
|
|
204
|
+
if (current === undefined) {
|
|
205
|
+
return createNullCache();
|
|
206
|
+
}
|
|
207
|
+
|
|
208
|
+
return {
|
|
209
|
+
get(key, defaultValue, events = {
|
|
210
|
+
miss: () => Promise.resolve()
|
|
211
|
+
}) {
|
|
212
|
+
return current.get(key, defaultValue, events).catch(() => {
|
|
213
|
+
return createFallbackableCache({
|
|
214
|
+
caches
|
|
215
|
+
}).get(key, defaultValue, events);
|
|
216
|
+
});
|
|
217
|
+
},
|
|
218
|
+
|
|
219
|
+
set(key, value) {
|
|
220
|
+
return current.set(key, value).catch(() => {
|
|
221
|
+
return createFallbackableCache({
|
|
222
|
+
caches
|
|
223
|
+
}).set(key, value);
|
|
224
|
+
});
|
|
225
|
+
},
|
|
226
|
+
|
|
227
|
+
delete(key) {
|
|
228
|
+
return current.delete(key).catch(() => {
|
|
229
|
+
return createFallbackableCache({
|
|
230
|
+
caches
|
|
231
|
+
}).delete(key);
|
|
232
|
+
});
|
|
233
|
+
},
|
|
234
|
+
|
|
235
|
+
clear() {
|
|
236
|
+
return current.clear().catch(() => {
|
|
237
|
+
return createFallbackableCache({
|
|
238
|
+
caches
|
|
239
|
+
}).clear();
|
|
240
|
+
});
|
|
241
|
+
}
|
|
242
|
+
|
|
243
|
+
};
|
|
244
|
+
}
|
|
245
|
+
|
|
246
|
+
function createMemoryCache(options = {
|
|
247
|
+
serializable: true
|
|
248
|
+
}) {
|
|
249
|
+
let cache = {};
|
|
250
|
+
return {
|
|
251
|
+
get(key, defaultValue, events = {
|
|
252
|
+
miss: () => Promise.resolve()
|
|
253
|
+
}) {
|
|
254
|
+
const keyAsString = JSON.stringify(key);
|
|
255
|
+
|
|
256
|
+
if (keyAsString in cache) {
|
|
257
|
+
return Promise.resolve(options.serializable ? JSON.parse(cache[keyAsString]) : cache[keyAsString]);
|
|
258
|
+
}
|
|
259
|
+
|
|
260
|
+
const promise = defaultValue();
|
|
261
|
+
return promise.then(value => events.miss(value)).then(() => promise);
|
|
262
|
+
},
|
|
263
|
+
|
|
264
|
+
set(key, value) {
|
|
265
|
+
cache[JSON.stringify(key)] = options.serializable ? JSON.stringify(value) : value;
|
|
266
|
+
return Promise.resolve(value);
|
|
267
|
+
},
|
|
268
|
+
|
|
269
|
+
delete(key) {
|
|
270
|
+
delete cache[JSON.stringify(key)];
|
|
271
|
+
return Promise.resolve();
|
|
272
|
+
},
|
|
273
|
+
|
|
274
|
+
clear() {
|
|
275
|
+
cache = {};
|
|
276
|
+
return Promise.resolve();
|
|
277
|
+
}
|
|
278
|
+
|
|
279
|
+
};
|
|
280
|
+
}
|
|
281
|
+
|
|
282
|
+
// By default, API Clients at Algolia have expiration delay of 5 mins.
|
|
283
|
+
// In the JavaScript client, we have 2 mins.
|
|
284
|
+
const EXPIRATION_DELAY = 2 * 60 * 1000;
|
|
285
|
+
function createStatefulHost(host, status = 'up') {
|
|
286
|
+
const lastUpdate = Date.now();
|
|
287
|
+
|
|
288
|
+
function isUp() {
|
|
289
|
+
return status === 'up' || Date.now() - lastUpdate > EXPIRATION_DELAY;
|
|
290
|
+
}
|
|
291
|
+
|
|
292
|
+
function isTimedOut() {
|
|
293
|
+
return status === 'timed out' && Date.now() - lastUpdate <= EXPIRATION_DELAY;
|
|
294
|
+
}
|
|
295
|
+
|
|
296
|
+
return { ...host,
|
|
297
|
+
status,
|
|
298
|
+
lastUpdate,
|
|
299
|
+
isUp,
|
|
300
|
+
isTimedOut
|
|
301
|
+
};
|
|
302
|
+
}
|
|
303
|
+
|
|
304
|
+
function _defineProperty(obj, key, value) {
|
|
305
|
+
if (key in obj) {
|
|
306
|
+
Object.defineProperty(obj, key, {
|
|
307
|
+
value: value,
|
|
308
|
+
enumerable: true,
|
|
309
|
+
configurable: true,
|
|
310
|
+
writable: true
|
|
311
|
+
});
|
|
312
|
+
} else {
|
|
313
|
+
obj[key] = value;
|
|
314
|
+
}
|
|
315
|
+
|
|
316
|
+
return obj;
|
|
317
|
+
}
|
|
318
|
+
|
|
319
|
+
class AlgoliaError extends Error {
|
|
320
|
+
constructor(message, name) {
|
|
321
|
+
super(message);
|
|
322
|
+
|
|
323
|
+
_defineProperty(this, "name", 'AlgoliaError');
|
|
324
|
+
|
|
325
|
+
if (name) {
|
|
326
|
+
this.name = name;
|
|
327
|
+
}
|
|
328
|
+
}
|
|
329
|
+
|
|
330
|
+
}
|
|
331
|
+
class ErrorWithStackTrace extends AlgoliaError {
|
|
332
|
+
constructor(message, stackTrace, name) {
|
|
333
|
+
super(message, name); // the array and object should be frozen to reflect the stackTrace at the time of the error
|
|
334
|
+
|
|
335
|
+
_defineProperty(this, "stackTrace", void 0);
|
|
336
|
+
|
|
337
|
+
this.stackTrace = stackTrace;
|
|
338
|
+
}
|
|
339
|
+
|
|
340
|
+
}
|
|
341
|
+
class RetryError extends ErrorWithStackTrace {
|
|
342
|
+
constructor(stackTrace) {
|
|
343
|
+
super('Unreachable hosts - your application id may be incorrect. If the error persists, contact support@algolia.com.', stackTrace, 'RetryError');
|
|
344
|
+
}
|
|
345
|
+
|
|
346
|
+
}
|
|
347
|
+
class ApiError extends ErrorWithStackTrace {
|
|
348
|
+
constructor(message, status, stackTrace) {
|
|
349
|
+
super(message, stackTrace, 'ApiError');
|
|
350
|
+
|
|
351
|
+
_defineProperty(this, "status", void 0);
|
|
352
|
+
|
|
353
|
+
this.status = status;
|
|
354
|
+
}
|
|
355
|
+
|
|
356
|
+
}
|
|
357
|
+
class DeserializationError extends AlgoliaError {
|
|
358
|
+
constructor(message, response) {
|
|
359
|
+
super(message, 'DeserializationError');
|
|
360
|
+
|
|
361
|
+
_defineProperty(this, "response", void 0);
|
|
362
|
+
|
|
363
|
+
this.response = response;
|
|
364
|
+
}
|
|
365
|
+
|
|
366
|
+
}
|
|
367
|
+
|
|
368
|
+
function shuffle(array) {
|
|
369
|
+
const shuffledArray = array;
|
|
370
|
+
|
|
371
|
+
for (let c = array.length - 1; c > 0; c--) {
|
|
372
|
+
const b = Math.floor(Math.random() * (c + 1));
|
|
373
|
+
const a = array[c];
|
|
374
|
+
shuffledArray[c] = array[b];
|
|
375
|
+
shuffledArray[b] = a;
|
|
376
|
+
}
|
|
377
|
+
|
|
378
|
+
return shuffledArray;
|
|
379
|
+
}
|
|
380
|
+
function serializeUrl(host, path, queryParameters) {
|
|
381
|
+
const queryParametersAsString = serializeQueryParameters(queryParameters);
|
|
382
|
+
let url = `${host.protocol}://${host.url}/${path.charAt(0) === '/' ? path.substr(1) : path}`;
|
|
383
|
+
|
|
384
|
+
if (queryParametersAsString.length) {
|
|
385
|
+
url += `?${queryParametersAsString}`;
|
|
386
|
+
}
|
|
387
|
+
|
|
388
|
+
return url;
|
|
389
|
+
}
|
|
390
|
+
function serializeQueryParameters(parameters) {
|
|
391
|
+
const isObjectOrArray = value => Object.prototype.toString.call(value) === '[object Object]' || Object.prototype.toString.call(value) === '[object Array]';
|
|
392
|
+
|
|
393
|
+
return Object.keys(parameters).map(key => `${key}=${isObjectOrArray(parameters[key]) ? JSON.stringify(parameters[key]) : parameters[key]}`).join('&');
|
|
394
|
+
}
|
|
395
|
+
function serializeData(request, requestOptions) {
|
|
396
|
+
if (request.method === 'GET' || request.data === undefined && requestOptions.data === undefined) {
|
|
397
|
+
return undefined;
|
|
398
|
+
}
|
|
399
|
+
|
|
400
|
+
const data = Array.isArray(request.data) ? request.data : { ...request.data,
|
|
401
|
+
...requestOptions.data
|
|
402
|
+
};
|
|
403
|
+
return JSON.stringify(data);
|
|
404
|
+
}
|
|
405
|
+
function serializeHeaders(baseHeaders, requestHeaders, requestOptionsHeaders) {
|
|
406
|
+
const headers = {
|
|
407
|
+
Accept: 'application/json',
|
|
408
|
+
...baseHeaders,
|
|
409
|
+
...requestHeaders,
|
|
410
|
+
...requestOptionsHeaders
|
|
411
|
+
};
|
|
412
|
+
const serializedHeaders = {};
|
|
413
|
+
Object.keys(headers).forEach(header => {
|
|
414
|
+
const value = headers[header];
|
|
415
|
+
serializedHeaders[header.toLowerCase()] = value;
|
|
416
|
+
});
|
|
417
|
+
return serializedHeaders;
|
|
418
|
+
}
|
|
419
|
+
function deserializeSuccess(response) {
|
|
420
|
+
try {
|
|
421
|
+
return JSON.parse(response.content);
|
|
422
|
+
} catch (e) {
|
|
423
|
+
throw new DeserializationError(e.message, response);
|
|
424
|
+
}
|
|
425
|
+
}
|
|
426
|
+
function deserializeFailure({
|
|
427
|
+
content,
|
|
428
|
+
status
|
|
429
|
+
}, stackFrame) {
|
|
430
|
+
let message = content;
|
|
431
|
+
|
|
432
|
+
try {
|
|
433
|
+
message = JSON.parse(content).message;
|
|
434
|
+
} catch (e) {// ..
|
|
435
|
+
}
|
|
436
|
+
|
|
437
|
+
return new ApiError(message, status, stackFrame);
|
|
438
|
+
}
|
|
439
|
+
|
|
440
|
+
function isNetworkError({
|
|
441
|
+
isTimedOut,
|
|
442
|
+
status
|
|
443
|
+
}) {
|
|
444
|
+
return !isTimedOut && ~~status === 0;
|
|
445
|
+
}
|
|
446
|
+
function isRetryable({
|
|
447
|
+
isTimedOut,
|
|
448
|
+
status
|
|
449
|
+
}) {
|
|
450
|
+
return isTimedOut || isNetworkError({
|
|
451
|
+
isTimedOut,
|
|
452
|
+
status
|
|
453
|
+
}) || ~~(status / 100) !== 2 && ~~(status / 100) !== 4;
|
|
454
|
+
}
|
|
455
|
+
function isSuccess({
|
|
456
|
+
status
|
|
457
|
+
}) {
|
|
458
|
+
return ~~(status / 100) === 2;
|
|
459
|
+
}
|
|
460
|
+
|
|
461
|
+
function stackTraceWithoutCredentials(stackTrace) {
|
|
462
|
+
return stackTrace.map(stackFrame => stackFrameWithoutCredentials(stackFrame));
|
|
463
|
+
}
|
|
464
|
+
function stackFrameWithoutCredentials(stackFrame) {
|
|
465
|
+
const modifiedHeaders = stackFrame.request.headers['x-algolia-api-key'] ? {
|
|
466
|
+
'x-algolia-api-key': '*****'
|
|
467
|
+
} : {};
|
|
468
|
+
return { ...stackFrame,
|
|
469
|
+
request: { ...stackFrame.request,
|
|
470
|
+
headers: { ...stackFrame.request.headers,
|
|
471
|
+
...modifiedHeaders
|
|
472
|
+
}
|
|
473
|
+
}
|
|
474
|
+
};
|
|
475
|
+
}
|
|
476
|
+
|
|
477
|
+
function createTransporter({
|
|
478
|
+
hosts,
|
|
479
|
+
hostsCache,
|
|
480
|
+
baseHeaders,
|
|
481
|
+
baseQueryParameters,
|
|
482
|
+
algoliaAgent,
|
|
483
|
+
timeouts,
|
|
484
|
+
requester,
|
|
485
|
+
requestsCache,
|
|
486
|
+
responsesCache
|
|
487
|
+
}) {
|
|
488
|
+
async function createRetryableOptions(compatibleHosts) {
|
|
489
|
+
const statefulHosts = await Promise.all(compatibleHosts.map(compatibleHost => {
|
|
490
|
+
return hostsCache.get(compatibleHost, () => {
|
|
491
|
+
return Promise.resolve(createStatefulHost(compatibleHost));
|
|
492
|
+
});
|
|
493
|
+
}));
|
|
494
|
+
const hostsUp = statefulHosts.filter(host => host.isUp());
|
|
495
|
+
const hostsTimedOut = statefulHosts.filter(host => host.isTimedOut()); // Note, we put the hosts that previously timed out on the end of the list.
|
|
496
|
+
|
|
497
|
+
const hostsAvailable = [...hostsUp, ...hostsTimedOut];
|
|
498
|
+
const compatibleHostsAvailable = hostsAvailable.length > 0 ? hostsAvailable : compatibleHosts;
|
|
499
|
+
return {
|
|
500
|
+
hosts: compatibleHostsAvailable,
|
|
501
|
+
|
|
502
|
+
getTimeout(timeoutsCount, baseTimeout) {
|
|
503
|
+
/**
|
|
504
|
+
* Imagine that you have 4 hosts, if timeouts will increase
|
|
505
|
+
* on the following way: 1 (timed out) > 4 (timed out) > 5 (200).
|
|
506
|
+
*
|
|
507
|
+
* Note that, the very next request, we start from the previous timeout.
|
|
508
|
+
*
|
|
509
|
+
* 5 (timed out) > 6 (timed out) > 7 ...
|
|
510
|
+
*
|
|
511
|
+
* This strategy may need to be reviewed, but is the strategy on the our
|
|
512
|
+
* current v3 version.
|
|
513
|
+
*/
|
|
514
|
+
const timeoutMultiplier = hostsTimedOut.length === 0 && timeoutsCount === 0 ? 1 : hostsTimedOut.length + 3 + timeoutsCount;
|
|
515
|
+
return timeoutMultiplier * baseTimeout;
|
|
516
|
+
}
|
|
517
|
+
|
|
518
|
+
};
|
|
519
|
+
}
|
|
520
|
+
|
|
521
|
+
async function retryableRequest(request, requestOptions, isRead = true) {
|
|
522
|
+
const stackTrace = [];
|
|
83
523
|
/**
|
|
84
|
-
*
|
|
85
|
-
*/
|
|
86
|
-
|
|
524
|
+
* First we prepare the payload that do not depend from hosts.
|
|
525
|
+
*/
|
|
526
|
+
|
|
527
|
+
const data = serializeData(request, requestOptions);
|
|
528
|
+
const headers = serializeHeaders(baseHeaders, request.headers, requestOptions.headers); // On `GET`, the data is proxied to query parameters.
|
|
529
|
+
|
|
530
|
+
const dataQueryParameters = request.method === 'GET' ? { ...request.data,
|
|
531
|
+
...requestOptions.data
|
|
532
|
+
} : {};
|
|
533
|
+
const queryParameters = {
|
|
534
|
+
'x-algolia-agent': algoliaAgent.value,
|
|
535
|
+
...baseQueryParameters,
|
|
536
|
+
...request.queryParameters,
|
|
537
|
+
...dataQueryParameters
|
|
538
|
+
};
|
|
539
|
+
|
|
540
|
+
if (requestOptions && requestOptions.queryParameters) {
|
|
541
|
+
for (const key of Object.keys(requestOptions.queryParameters)) {
|
|
542
|
+
// We want to keep `undefined` and `null` values,
|
|
543
|
+
// but also avoid stringifying `object`s, as they are
|
|
544
|
+
// handled in the `serializeUrl` step right after.
|
|
545
|
+
if (!requestOptions.queryParameters[key] || Object.prototype.toString.call(requestOptions.queryParameters[key]) === '[object Object]') {
|
|
546
|
+
queryParameters[key] = requestOptions.queryParameters[key];
|
|
547
|
+
} else {
|
|
548
|
+
queryParameters[key] = requestOptions.queryParameters[key].toString();
|
|
549
|
+
}
|
|
550
|
+
}
|
|
551
|
+
}
|
|
552
|
+
|
|
553
|
+
let timeoutsCount = 0;
|
|
554
|
+
|
|
555
|
+
const retry = async (retryableHosts, getTimeout) => {
|
|
556
|
+
/**
|
|
557
|
+
* We iterate on each host, until there is no host left.
|
|
558
|
+
*/
|
|
559
|
+
const host = retryableHosts.pop();
|
|
560
|
+
|
|
561
|
+
if (host === undefined) {
|
|
562
|
+
throw new RetryError(stackTraceWithoutCredentials(stackTrace));
|
|
563
|
+
}
|
|
564
|
+
|
|
565
|
+
let responseTimeout = requestOptions.timeout;
|
|
566
|
+
|
|
567
|
+
if (responseTimeout === undefined) {
|
|
568
|
+
responseTimeout = isRead ? timeouts.read : timeouts.write;
|
|
569
|
+
}
|
|
570
|
+
|
|
571
|
+
const payload = {
|
|
572
|
+
data,
|
|
573
|
+
headers,
|
|
574
|
+
method: request.method,
|
|
575
|
+
url: serializeUrl(host, request.path, queryParameters),
|
|
576
|
+
connectTimeout: getTimeout(timeoutsCount, timeouts.connect),
|
|
577
|
+
responseTimeout: getTimeout(timeoutsCount, responseTimeout)
|
|
578
|
+
};
|
|
579
|
+
/**
|
|
580
|
+
* The stackFrame is pushed to the stackTrace so we
|
|
581
|
+
* can have information about onRetry and onFailure
|
|
582
|
+
* decisions.
|
|
583
|
+
*/
|
|
584
|
+
|
|
585
|
+
const pushToStackTrace = response => {
|
|
586
|
+
const stackFrame = {
|
|
587
|
+
request: payload,
|
|
588
|
+
response,
|
|
589
|
+
host,
|
|
590
|
+
triesLeft: retryableHosts.length
|
|
591
|
+
};
|
|
592
|
+
stackTrace.push(stackFrame);
|
|
593
|
+
return stackFrame;
|
|
594
|
+
};
|
|
595
|
+
|
|
596
|
+
const response = await requester.send(payload);
|
|
597
|
+
|
|
598
|
+
if (isRetryable(response)) {
|
|
599
|
+
const stackFrame = pushToStackTrace(response); // If response is a timeout, we increase the number of timeouts so we can increase the timeout later.
|
|
600
|
+
|
|
601
|
+
if (response.isTimedOut) {
|
|
602
|
+
timeoutsCount++;
|
|
603
|
+
}
|
|
604
|
+
/**
|
|
605
|
+
* Failures are individually sent to the logger, allowing
|
|
606
|
+
* the end user to debug / store stack frames even
|
|
607
|
+
* when a retry error does not happen.
|
|
608
|
+
*/
|
|
609
|
+
// eslint-disable-next-line no-console -- this will be fixed by exposing a `logger` to the transporter
|
|
610
|
+
|
|
611
|
+
|
|
612
|
+
console.log('Retryable failure', stackFrameWithoutCredentials(stackFrame));
|
|
613
|
+
/**
|
|
614
|
+
* We also store the state of the host in failure cases. If the host, is
|
|
615
|
+
* down it will remain down for the next 2 minutes. In a timeout situation,
|
|
616
|
+
* this host will be added end of the list of hosts on the next request.
|
|
617
|
+
*/
|
|
618
|
+
|
|
619
|
+
await hostsCache.set(host, createStatefulHost(host, response.isTimedOut ? 'timed out' : 'down'));
|
|
620
|
+
return retry(retryableHosts, getTimeout);
|
|
621
|
+
}
|
|
622
|
+
|
|
623
|
+
if (isSuccess(response)) {
|
|
624
|
+
return deserializeSuccess(response);
|
|
625
|
+
}
|
|
626
|
+
|
|
627
|
+
pushToStackTrace(response);
|
|
628
|
+
throw deserializeFailure(response, stackTrace);
|
|
629
|
+
};
|
|
87
630
|
/**
|
|
88
|
-
*
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
631
|
+
* Finally, for each retryable host perform request until we got a non
|
|
632
|
+
* retryable response. Some notes here:
|
|
633
|
+
*
|
|
634
|
+
* 1. The reverse here is applied so we can apply a `pop` later on => more performant.
|
|
635
|
+
* 2. We also get from the retryable options a timeout multiplier that is tailored
|
|
636
|
+
* for the current context.
|
|
637
|
+
*/
|
|
638
|
+
|
|
639
|
+
|
|
640
|
+
const compatibleHosts = hosts.filter(host => host.accept === 'readWrite' || (isRead ? host.accept === 'read' : host.accept === 'write'));
|
|
641
|
+
const options = await createRetryableOptions(compatibleHosts);
|
|
642
|
+
return retry([...options.hosts].reverse(), options.getTimeout);
|
|
643
|
+
}
|
|
644
|
+
|
|
645
|
+
function createRequest(request, requestOptions = {}) {
|
|
646
|
+
/**
|
|
647
|
+
* A read request is either a `GET` request, or a request that we make
|
|
648
|
+
* via the `read` transporter (e.g. `search`).
|
|
649
|
+
*/
|
|
650
|
+
const isRead = request.useReadTransporter || request.method === 'GET';
|
|
651
|
+
|
|
652
|
+
if (!isRead) {
|
|
653
|
+
/**
|
|
654
|
+
* On write requests, no cache mechanisms are applied, and we
|
|
655
|
+
* proxy the request immediately to the requester.
|
|
656
|
+
*/
|
|
657
|
+
return retryableRequest(request, requestOptions, isRead);
|
|
658
|
+
}
|
|
659
|
+
|
|
660
|
+
const createRetryableRequest = () => {
|
|
661
|
+
/**
|
|
662
|
+
* Then, we prepare a function factory that contains the construction of
|
|
663
|
+
* the retryable request. At this point, we may *not* perform the actual
|
|
664
|
+
* request. But we want to have the function factory ready.
|
|
665
|
+
*/
|
|
666
|
+
return retryableRequest(request, requestOptions);
|
|
667
|
+
};
|
|
668
|
+
/**
|
|
669
|
+
* Once we have the function factory ready, we need to determine of the
|
|
670
|
+
* request is "cacheable" - should be cached. Note that, once again,
|
|
671
|
+
* the user can force this option.
|
|
672
|
+
*/
|
|
673
|
+
|
|
674
|
+
|
|
675
|
+
const cacheable = requestOptions.cacheable || request.cacheable;
|
|
676
|
+
/**
|
|
677
|
+
* If is not "cacheable", we immediately trigger the retryable request, no
|
|
678
|
+
* need to check cache implementations.
|
|
679
|
+
*/
|
|
680
|
+
|
|
681
|
+
if (cacheable !== true) {
|
|
682
|
+
return createRetryableRequest();
|
|
683
|
+
}
|
|
684
|
+
/**
|
|
685
|
+
* If the request is "cacheable", we need to first compute the key to ask
|
|
686
|
+
* the cache implementations if this request is on progress or if the
|
|
687
|
+
* response already exists on the cache.
|
|
688
|
+
*/
|
|
689
|
+
|
|
690
|
+
|
|
691
|
+
const key = {
|
|
692
|
+
request,
|
|
693
|
+
requestOptions,
|
|
694
|
+
transporter: {
|
|
695
|
+
queryParameters: baseQueryParameters,
|
|
696
|
+
headers: baseHeaders
|
|
697
|
+
}
|
|
698
|
+
};
|
|
699
|
+
/**
|
|
700
|
+
* With the computed key, we first ask the responses cache
|
|
701
|
+
* implementation if this request was been resolved before.
|
|
702
|
+
*/
|
|
703
|
+
|
|
704
|
+
return responsesCache.get(key, () => {
|
|
705
|
+
/**
|
|
706
|
+
* If the request has never resolved before, we actually ask if there
|
|
707
|
+
* is a current request with the same key on progress.
|
|
708
|
+
*/
|
|
709
|
+
return requestsCache.get(key, () =>
|
|
710
|
+
/**
|
|
711
|
+
* Finally, if there is no request in progress with the same key,
|
|
712
|
+
* this `createRetryableRequest()` will actually trigger the
|
|
713
|
+
* retryable request.
|
|
714
|
+
*/
|
|
715
|
+
requestsCache.set(key, createRetryableRequest()).then(response => Promise.all([requestsCache.delete(key), response]), err => Promise.all([requestsCache.delete(key), Promise.reject(err)])).then(([_, response]) => response));
|
|
716
|
+
}, {
|
|
717
|
+
/**
|
|
718
|
+
* Of course, once we get this response back from the server, we
|
|
719
|
+
* tell response cache to actually store the received response
|
|
720
|
+
* to be used later.
|
|
721
|
+
*/
|
|
722
|
+
miss: response => responsesCache.set(key, response)
|
|
723
|
+
});
|
|
724
|
+
}
|
|
725
|
+
|
|
726
|
+
return {
|
|
727
|
+
hostsCache,
|
|
728
|
+
requester,
|
|
729
|
+
timeouts,
|
|
730
|
+
algoliaAgent,
|
|
731
|
+
baseHeaders,
|
|
732
|
+
baseQueryParameters,
|
|
733
|
+
hosts,
|
|
734
|
+
request: createRequest,
|
|
735
|
+
requestsCache,
|
|
736
|
+
responsesCache
|
|
737
|
+
};
|
|
738
|
+
}
|
|
739
|
+
|
|
740
|
+
function createAlgoliaAgent(version) {
|
|
741
|
+
const algoliaAgent = {
|
|
742
|
+
value: `Algolia for JavaScript (${version})`,
|
|
743
|
+
|
|
744
|
+
add(options) {
|
|
745
|
+
const addedAlgoliaAgent = `; ${options.segment}${options.version !== undefined ? ` (${options.version})` : ''}`;
|
|
746
|
+
|
|
747
|
+
if (algoliaAgent.value.indexOf(addedAlgoliaAgent) === -1) {
|
|
748
|
+
algoliaAgent.value = `${algoliaAgent.value}${addedAlgoliaAgent}`;
|
|
749
|
+
}
|
|
750
|
+
|
|
751
|
+
return algoliaAgent;
|
|
752
|
+
}
|
|
753
|
+
|
|
754
|
+
};
|
|
755
|
+
return algoliaAgent;
|
|
756
|
+
}
|
|
757
|
+
|
|
758
|
+
function getAlgoliaAgent({
|
|
759
|
+
algoliaAgents,
|
|
760
|
+
client,
|
|
761
|
+
version
|
|
762
|
+
}) {
|
|
763
|
+
const defaultAlgoliaAgent = createAlgoliaAgent(version).add({
|
|
764
|
+
segment: client,
|
|
765
|
+
version
|
|
766
|
+
});
|
|
767
|
+
algoliaAgents.forEach(algoliaAgent => defaultAlgoliaAgent.add(algoliaAgent));
|
|
768
|
+
return defaultAlgoliaAgent;
|
|
769
|
+
}
|
|
770
|
+
|
|
771
|
+
const DEFAULT_CONNECT_TIMEOUT_BROWSER = 1000;
|
|
772
|
+
const DEFAULT_READ_TIMEOUT_BROWSER = 2000;
|
|
773
|
+
const DEFAULT_WRITE_TIMEOUT_BROWSER = 30000;
|
|
774
|
+
const DEFAULT_CONNECT_TIMEOUT_NODE = 2000;
|
|
775
|
+
const DEFAULT_READ_TIMEOUT_NODE = 5000;
|
|
776
|
+
const DEFAULT_WRITE_TIMEOUT_NODE = 30000;
|
|
92
777
|
|
|
93
|
-
exports.
|
|
94
|
-
exports.
|
|
778
|
+
exports.AlgoliaError = AlgoliaError;
|
|
779
|
+
exports.ApiError = ApiError;
|
|
780
|
+
exports.DEFAULT_CONNECT_TIMEOUT_BROWSER = DEFAULT_CONNECT_TIMEOUT_BROWSER;
|
|
781
|
+
exports.DEFAULT_CONNECT_TIMEOUT_NODE = DEFAULT_CONNECT_TIMEOUT_NODE;
|
|
782
|
+
exports.DEFAULT_MAX_RETRIES = DEFAULT_MAX_RETRIES;
|
|
783
|
+
exports.DEFAULT_READ_TIMEOUT_BROWSER = DEFAULT_READ_TIMEOUT_BROWSER;
|
|
784
|
+
exports.DEFAULT_READ_TIMEOUT_NODE = DEFAULT_READ_TIMEOUT_NODE;
|
|
785
|
+
exports.DEFAULT_TIMEOUT = DEFAULT_TIMEOUT;
|
|
786
|
+
exports.DEFAULT_WRITE_TIMEOUT_BROWSER = DEFAULT_WRITE_TIMEOUT_BROWSER;
|
|
787
|
+
exports.DEFAULT_WRITE_TIMEOUT_NODE = DEFAULT_WRITE_TIMEOUT_NODE;
|
|
788
|
+
exports.DeserializationError = DeserializationError;
|
|
789
|
+
exports.ErrorWithStackTrace = ErrorWithStackTrace;
|
|
790
|
+
exports.RetryError = RetryError;
|
|
791
|
+
exports.createAlgoliaAgent = createAlgoliaAgent;
|
|
95
792
|
exports.createAuth = createAuth;
|
|
793
|
+
exports.createBrowserLocalStorageCache = createBrowserLocalStorageCache;
|
|
794
|
+
exports.createEchoRequester = createEchoRequester;
|
|
795
|
+
exports.createFallbackableCache = createFallbackableCache;
|
|
796
|
+
exports.createMemoryCache = createMemoryCache;
|
|
797
|
+
exports.createNullCache = createNullCache;
|
|
96
798
|
exports.createRetryablePromise = createRetryablePromise;
|
|
97
|
-
exports.
|
|
98
|
-
exports.
|
|
99
|
-
exports.
|
|
799
|
+
exports.createStatefulHost = createStatefulHost;
|
|
800
|
+
exports.createTransporter = createTransporter;
|
|
801
|
+
exports.deserializeFailure = deserializeFailure;
|
|
802
|
+
exports.deserializeSuccess = deserializeSuccess;
|
|
803
|
+
exports.getAlgoliaAgent = getAlgoliaAgent;
|
|
804
|
+
exports.isNetworkError = isNetworkError;
|
|
805
|
+
exports.isRetryable = isRetryable;
|
|
806
|
+
exports.isSuccess = isSuccess;
|
|
807
|
+
exports.serializeData = serializeData;
|
|
808
|
+
exports.serializeHeaders = serializeHeaders;
|
|
809
|
+
exports.serializeQueryParameters = serializeQueryParameters;
|
|
810
|
+
exports.serializeUrl = serializeUrl;
|
|
100
811
|
exports.shuffle = shuffle;
|
|
101
|
-
exports.
|
|
812
|
+
exports.stackFrameWithoutCredentials = stackFrameWithoutCredentials;
|
|
813
|
+
exports.stackTraceWithoutCredentials = stackTraceWithoutCredentials;
|