-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathindex.js
280 lines (239 loc) · 6.71 KB
/
index.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
const
Debug = require('@superhero/debug'),
url = require('url'),
querystring = require('querystring'),
sleep = (delay) => new Promise((go) => setTimeout(go, delay))
module.exports = class
{
constructor(config)
{
this.config = Object.assign(
{
rejectUnauthorized: true,
debug : false,
debug_color : 'cyan',
debug_date : true,
debug_prefix : 'debug request:',
debug_separator : ' ',
headers : {},
retry : 0,
timeout : 30e3,
url : '',
proxy : process.env.HTTP_PROXY
}, config)
this.debug = new Debug(
{
color : this.config.debug_color,
date : this.config.debug_date,
prefix : this.config.debug_prefix,
separator : this.config.debug_separator,
debug : this.config.debug
})
}
get(...args)
{
return this.fetch('GET', ...args)
}
put(...args)
{
return this.fetch('PUT', ...args)
}
post(...args)
{
return this.fetch('POST', ...args)
}
delete(...args)
{
return this.fetch('DELETE', ...args)
}
async fetch(method, options)
{
if(typeof options == 'string')
{
options = { url:options }
}
options = Object.assign(
{
method,
headers : {},
timeout : this.config.timeout,
url : '',
port : this.config.port,
retry : this.config.retry
}, options)
const result = await this.resolveThroughRetryLoop(options)
return result
}
async resolveThroughRetryLoop(options)
{
let result, retry, i = 0
do
{
try
{
result = await this.resolve(options.method, options)
retry = false
}
catch(error)
{
const
isClientError = error.code === 'E_REQUEST_CLIENT_ERROR',
isClientTimeoutError = error.code === 'E_REQUEST_CLIENT_TIMEOUT',
isInRetryLoopSpan = ++i < options.retry
retry = isInRetryLoopSpan && (isClientError || (options.retryOnClientTimeout && isClientTimeoutError))
if(!retry)
{
throw error
}
}
if(retry)
{
await sleep(200)
}
}
while(retry)
return result
}
resolve(method, options)
{
return new Promise((fulfill, reject) =>
{
this.debug.log('incoming options:', options)
const
assigned = Object.assign({}, this.config.headers, options.headers),
objectKeys = Object.keys(assigned),
headers = objectKeys.reduce((c, k) => (c[k.toLowerCase()] = assigned[k], c), {}),
body = typeof (options.data || '') == 'string' || Buffer.isBuffer(options.data)
? options.data
: ( headers['content-type'] || '' ).startsWith('application/json')
? JSON.stringify(options.data)
: querystring.stringify(options.data),
composedUrl = this.config.url + options.url
let parsedUrl
try
{
parsedUrl = url.parse(composedUrl, false, true)
}
catch (error)
{
const encodedUrl = encodeURI(composedUrl)
parsedUrl = url.parse(encodedUrl, false, true)
}
const
parsedProxy = url.parse(this.config.proxy || '', false, true),
config = this.config.proxy
?
{
auth : parsedProxy.auth,
host : parsedProxy.hostname,
path : parsedUrl.href,
port : parsedProxy.port,
}
:
{
auth : parsedUrl.auth,
host : parsedUrl.hostname,
port : parsedUrl.port,
path : parsedUrl.path,
}
config.rejectUnauthorized = options.rejectUnauthorized
config.timeout = options.timeout
config.method = method
config.headers = (() =>
{
headers['content-length'] = Buffer.byteLength(body || '', 'utf8')
return headers
})()
// removes null valued keys from the config object
for(const key in config)
if(config[key] === null)
delete config[key]
const
path = `${method} ${parsedUrl.href}`,
request = ( this.config.proxy || parsedUrl.protocol === 'http:'
? require('http')
: require('https')).request(config, this.onResult.bind(this, fulfill, options, composedUrl))
this.debug.log('parsed config:', config)
// writing body, if one is declared
if(body)
{
this.debug.log('writing request body:', body)
request.write(body)
}
request.on('error', (clientError) =>
{
const
msg = `client error -> ${path}`,
error = new Error(msg)
this.debug.error(msg, options)
error.code = 'E_REQUEST_CLIENT_ERROR'
error.previous = clientError
reject(error)
})
request.on('timeout', () =>
{
const
msg = `client timeout (${config.timeout / 1000}s) -> ${path}`,
error = new Error(msg)
this.debug.error(msg, options)
error.code = 'E_REQUEST_CLIENT_TIMEOUT'
reject(error)
request.destroy()
})
request.end()
})
}
onResult(fulfill, options, url, result)
{
this.debug.log('response recieved')
let data = ''
if(options.pipe || options.stream)
{
this.debug.log('piping the result')
result.pipe(options.pipe || options.stream)
fulfill(
{
url : url,
status : result.statusCode,
headers : result.headers,
stream : result
})
}
else if(result.readableEnded)
{
fulfill(
{
url : url,
status : result.statusCode,
headers : result.headers,
data : data
})
}
else
{
result.on('data', (chunk) => data += chunk)
result.on('end', () =>
{
try
{
data = JSON.parse(data)
}
catch (e)
{
this.debug.log('tried and failed to parse content as json:', e.message)
}
this.debug.log('options:', options)
this.debug.log('status:', result.statusCode)
this.debug.log('headers:', result.headers)
this.debug.log('data:', data)
fulfill(
{
url : url,
status : result.statusCode,
headers : result.headers,
data : data
})
})
}
}
}