-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbasic.js
404 lines (356 loc) · 11.7 KB
/
basic.js
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
391
392
393
394
395
396
397
398
399
400
401
402
403
404
/* eslint-disable func-names */
'use strict'
const urlJoin = require('url-join')
const { v4: uuidv4 } = require('uuid')
const { fetchWrappers, removeUndefined } = require('./fetchUtils')
const REQUEST_GUID = 'request-guid'
function _toBaseUrl({ protocol, https, host, hostname, port }) {
let baseurl = host || hostname || 'http://localhost'
if (!baseurl.includes('://')) baseurl = `http://${baseurl}`
const myUrl = new URL(baseurl)
myUrl.protocol = protocol || (https ? 'https:' : 'http:')
if (protocol) myUrl.protocol = protocol
if (port) myUrl.port = port
return myUrl.toString()
}
/**
* Creates a wrapper around request with useful defaults.
* @param {object} [options] - plain js object with options
* @param {string} [options.host] - set hostname and port, e.g. 'www.example.org:80'
* @param {string} [options.hostname='localhost'] - set hostname, e.g. 'www.example.org'
* @param {string|number} [options.port] - set custom port, e.g. 80
* @param {boolean} [options.https] - set true to use https, e.g. true
* @param {string} [options.protocol] - explicitly set protocol, e.g. 'https:'
* @param {string} [options.basePath] - optional base path to prefix requests with
* @param {boolean} [options.json] - automatically call JSON.parse/stringify
* @param {object} [options.headers] - custom HTTP headers
* @param {object} [options.redis] - configure redis to enable caching
* @param {*} [options.redis.client] - a node-redis compatible client
* @param {string} [options.redis.prefix] - redis key prefix
* @param {number} [options.redis.expire=300] - expiration time in seconds
* @param {BasicAPI} [base] - used internally when calling defaults
* @constructor
*/
function BasicAPI(options, base) {
if (!(this instanceof BasicAPI)) {
return new BasicAPI(options, base)
}
const myOptions = { headers: {}, ...options }
if (base) {
this._request = base._request.defaults(myOptions)
this._redis = base._redis
this._hasRedis = base._hasRedis
} else {
const opts = {
baseUrl: _toBaseUrl(myOptions),
headers: myOptions.headers,
json: myOptions.json,
pool: { maxSockets: Infinity },
}
this._request = fetchWrappers(opts)
this._redis = myOptions.redis
this._hasRedis = !!(this._redis && this._redis.client)
this._basePath = myOptions.basePath || ''
this._defaultTimeout = myOptions.defaultTimeout || 2000
this._retryOnESOCKETTIMEDOUT = myOptions.retryOnESOCKETTIMEDOUT ? myOptions.retryOnESOCKETTIMEDOUT : undefined
this._maxNumberOfRetries = myOptions.maxNumberOfRetries ? myOptions.maxNumberOfRetries : 5
this._log = myOptions.log
}
}
/**
* ESOCKETTIMEDOUT, ETIMEDOUT, and node-fetch timeout errors return true.
* @param {*} e
*/
const isTimeoutError = e => {
let errorStr
if (e.name.includes('Error')) {
errorStr = e.toString().toLowerCase()
return errorStr.includes('timedout') || errorStr.includes('timeout')
}
if (typeof e === 'object') {
errorStr = JSON.stringify(e).toLowerCase()
return errorStr.includes('timedout') || errorStr.includes('timeout')
}
errorStr = e.toString().toLowerCase()
return errorStr.includes('timedout') || errorStr.includes('timeout')
}
const retryWrapper = (_this, cb, args) => {
let counter = 0
const sendRequest = () =>
cb.apply(_this, args).catch(e => {
if (isTimeoutError(e) && counter < _this._maxNumberOfRetries) {
counter++
const myUrl = typeof args[2] === 'object' ? args[2].uri : args[2]
if (_this._log) {
_this._log.info(
`Request with guid ${_this.lastRequestGuid} to "${myUrl}" failed, Retry ${counter}/${_this._maxNumberOfRetries}`
)
}
return sendRequest()
}
if (isTimeoutError(e)) {
throw new Error(
`The request with guid ${_this.lastRequestGuid} timed out after ${counter} retries. The connection to the API seems to be overloaded.`
)
} else {
throw e
}
})
return sendRequest()
}
function _getURI(api, options) {
const relpath = typeof options === 'string' ? options : options.uri || ''
const queryObj = removeUndefined(options.qs || {})
const queryString = new URLSearchParams(queryObj).toString()
if (queryString) return urlJoin(api._basePath, relpath, '?' + queryString)
return urlJoin(api._basePath, relpath)
}
function _getKey(api, options, method) {
const prefix = api._redis.prefix ? api._redis.prefix + ':' : ''
return prefix + method + ':' + _getURI(api, options)
}
function _wrapCallback(api, options, method, callback) {
return (error, result, body) => {
if (error) {
callback(error, result, body)
return
}
if (api._hasRedis && result.statusCode >= 200 && result.statusCode < 400) {
const key = _getKey(api, options, method)
const redisData = { ...result, body }
const value = JSON.stringify(redisData)
let redisMaybeFnc = api._redis.client
if (typeof api._redis.client === 'function') {
const { clientName, clientOptions } = api._redis
if (clientName == null && clientOptions == null) {
redisMaybeFnc = api._redis.client()
} else {
redisMaybeFnc = api._redis.client(clientName || 'default', clientOptions || null)
}
}
Promise.resolve(redisMaybeFnc)
.then(client => {
client.set(key, value, err => {
if (err) callback(err)
})
client.expire(key, api._redis.expire || 300, err => {
if (err) callback(err)
})
})
.catch(err => {
callback(err)
})
}
callback(error, result, body)
}
}
function _makeRequest(api, options, method, callback) {
const fullUriPath = _getURI(api, options)
let opts
if (typeof options === 'string') {
opts = {
uri: options,
requestGuid: uuidv4(),
headers: {},
}
} else {
opts = { headers: {}, requestGuid: uuidv4(), ...options }
}
opts.headers[REQUEST_GUID] = opts.requestGuid
api.lastRequestGuid = opts.requestGuid // eslint-disable-line no-param-reassign
const cb = _wrapCallback(api, opts, method, callback)
return api._request[method]({ ...opts, uri: fullUriPath }, cb)
}
function _exec(api, options, method, callback) {
if (api._hasRedis && options.useCache) {
const key = _getKey(api, options, method)
const redisMaybeFnc = typeof api._redis.client === 'function' ? api._redis.client() : api._redis.client
Promise.resolve(redisMaybeFnc)
.then(
client =>
new Promise((resolve, reject) => {
client.get(key, (err, reply) => {
if (err || !reply) {
reject(err)
} else {
// TODO: Should we catch parse errors and return a reasonable message or
// is this good enough?
const value = JSON.parse(reply)
resolve(callback(null, value, value.body))
}
})
})
)
.catch(() => _makeRequest(api, options, method, callback))
} else {
_makeRequest(api, options, method, callback)
}
}
/**
* Sends an HTTP GET request.
* @param {string|object} options
* @param {function} callback
* @returns {request.Request}
*/
BasicAPI.prototype.get = function (options, callback) {
return _exec(this, options, 'get', callback)
}
function _createPromiseCallback(resolve, reject) {
return function (error, response, body) {
if (error) {
reject(error)
} else {
resolve({
response,
statusCode: response.statusCode,
statusMessage: response.statusMessage,
headers: response.headers,
body,
})
}
}
}
function _createPromise(api, func, options) {
// Create a options object so we can add default timeout
let opt
if (typeof options !== 'object') {
opt = { timeout: api._defaultTimeout, uri: options }
} else {
opt = { timeout: api._defaultTimeout, ...options }
}
return new Promise((resolve, reject) => {
func.call(api, opt, _createPromiseCallback(resolve, reject))
})
}
/**
* Sends an HTTP GET request using a promise.
* @param {string|object} options
* @returns {Promise}
*/
BasicAPI.prototype.getAsync = function (options) {
if (this._retryOnESOCKETTIMEDOUT) {
return retryWrapper(this, _createPromise, [this, this.get, options])
}
return _createPromise(this, this.get, options)
}
/**
* Sends an HTTP POST request.
* @param {string|object} options
* @param {function} callback
* @returns {request.Request}
*/
BasicAPI.prototype.post = function (options, callback) {
return _exec(this, options, 'post', callback)
}
/**
* Sends an HTTP POST request using a promise.
* @param {string|object} options
* @returns {Promise}
*/
BasicAPI.prototype.postAsync = function (options) {
if (this._retryOnESOCKETTIMEDOUT) {
return retryWrapper(this, _createPromise, [this, this.post, options])
}
return _createPromise(this, this.post, options)
}
/**
* Sends an HTTP PUT request.
* @param {string|object} options
* @param {function} callback
* @returns {request.Request}
*/
BasicAPI.prototype.put = function (options, callback) {
return _exec(this, options, 'put', callback)
}
/**
* Sends an HTTP PUT request using a promise.
* @param {string|object} options
* @returns {Promise}
*/
BasicAPI.prototype.putAsync = function (options) {
if (this._retryOnESOCKETTIMEDOUT) {
return retryWrapper(this, _createPromise, [this, this.put, options])
}
return _createPromise(this, this.put, options)
}
/**
* Sends an HTTP DELETE request.
* @param {string|object} options
* @param {function} callback
* @returns {request.Request}
*/
BasicAPI.prototype.del = function (options, callback) {
return _exec(this, options, 'del', callback)
}
/**
* Sends an HTTP DELETE request using a promise.
* @param {string|object} options
* @returns {Promise}
*/
BasicAPI.prototype.delAsync = function (options) {
if (this._retryOnESOCKETTIMEDOUT) {
return retryWrapper(this, _createPromise, [this, this.del, options])
}
return _createPromise(this, this.del, options)
}
/**
* Sends an HTTP HEAD request.
* @param {string|object} options
* @param {function} callback
* @returns {request.Request}
*/
BasicAPI.prototype.head = function (options, callback) {
return _exec(this, options, 'head', callback)
}
/**
* Sends an HTTP HEAD request using a promise.
* @param {string|object} options
* @returns {Promise}
*/
BasicAPI.prototype.headAsync = function (options) {
if (this._retryOnESOCKETTIMEDOUT) {
return retryWrapper(this, _createPromise, [this, this.head, options])
}
return _createPromise(this, this.head, options)
}
/**
* Sends an HTTP PATCH request.
* @param {string|object} options
* @param {function} callback
* @returns {request.Request}
*/
BasicAPI.prototype.patch = function (options, callback) {
return _exec(this, options, 'patch', callback)
}
/**
* Sends an HTTP PATCH request using a promise.
* @param {string|object} options
* @returns {Promise}
*/
BasicAPI.prototype.patchAsync = function (options) {
if (this._retryOnESOCKETTIMEDOUT) {
return retryWrapper(this, _createPromise, [this, this.patch, options])
}
return _createPromise(this, this.patch, options)
}
/**
* Using this request as base, create a new BasicAPI instance
* passing the options directly into `request.defaults()`.
* @deprecated since version 4
* @param {object} options
* @returns {BasicAPI}
*/
BasicAPI.prototype.defaults = function (options) {
return new BasicAPI(options, this)
}
BasicAPI.prototype.resolve = function (uri, params) {
let myUri = uri
for (const key in params) {
if (Object.prototype.hasOwnProperty.call(params, key)) {
const value = params[key]
myUri = myUri.replace(new RegExp(':' + key, 'gi'), encodeURIComponent(value))
}
}
return myUri
}
module.exports = BasicAPI