-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathrequest.js
More file actions
352 lines (291 loc) · 7.22 KB
/
request.js
File metadata and controls
352 lines (291 loc) · 7.22 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
import { cache } from './cache'
import EventEmitter from './event-emitter'
import * as qs from './qs'
import { castArray, isObject, isFormData, ensureEncoding } from './utils'
import { ResponseError } from './error'
const CONTENT_TYPE_HEADER = 'Content-Type'
const REQUEST_EVENT = 'request'
const RESPONSE_EVENT = 'response'
const ERROR_EVENT = 'error'
const DONE_EVENT = 'done'
export class Request extends EventEmitter {
constructor(path, method, body) {
super()
this.method = method
this.path = ensureEncoding(path)
this.body = body
this.tags = undefined
this.unwrap = true
this.cacheTTL = 0
this.headers = {}
this.queryParams = {}
this.encoding = 'utf8'
this.timeout = 0
this.withCredentials = null
this.abortSignal = null
}
/**
* Sets a header
*
* @param {String|Object} key or map of headers
* @param {String} [value]
* @returns {Request}
*/
set(key, value) {
if (isObject(key)) {
for (const headerName in key) {
this.set(headerName, key[headerName])
}
} else if (typeof value !== 'undefined') {
this.headers[key] = value
}
return this
}
/**
* Which kind of tags this request affects.
* Used for cache validation.
* Non GET requests with defined tags, will clean all related to these tags caches
*
* @param {Array.<String>} tags
* @returns {Request}
*/
cacheTags(...tags) {
this.tags = tags
return this
}
/**
* @param {Object} queryParams
* @returns {Request}
*/
query(queryParams) {
Object.assign(this.queryParams, queryParams)
return this
}
form(form) {
if (form) {
const FormData = Request.FormData
if (form instanceof FormData) {
this.body = form
} else {
const formData = new FormData()
for (const formKey in form) {
if (formKey) {
castArray(form[formKey]).forEach(formValue => {
if (formValue && formValue.hasOwnProperty('value') && formValue.hasOwnProperty('options')) {
formData.append(formKey, formValue.value, formValue.options)
} else {
formData.append(formKey, formValue)
}
})
}
}
this.body = formData
}
}
return this
}
/**
* Should we cache or use cached result
*
* @param {Number} ttl Time to live for cached response. 15 seconds by default
* @returns {Request}
*/
useCache(ttl = 15000) {
this.cacheTTL = ttl
return this
}
/**
* Reset cache if passed TRUE and tags has been specified before
*
* @param {Boolean} reset - flag to reset cache or not
* @returns {Request}
*/
resetCache(reset) {
if (reset && this.tags) {
cache.deleteByTags(this.tags)
}
return this
}
/**
* Shortcut for req.set('Content-Type', value)
*
* @param {String} contentType
* @returns {Request}
*/
type(contentType) {
this.set(CONTENT_TYPE_HEADER, contentType)
return this
}
/**
* Should we unwrap the response and return only body. true by default
* @param {Boolean} unwrap
* @returns {Request}
*/
unwrapBody(unwrap) {
this.unwrap = unwrap
return this
}
/**
* set encoding to response
* works only for Node js
*
* @param {String} encoding
* @returns {Request}
*/
setEncoding(encoding) {
this.encoding = encoding
return this
}
/**
* set withCredentials option
*
* @param {Boolean} value
* @returns {Request}
*/
setWithCredentials(value) {
this.withCredentials = value
return this
}
/**
* A number specifying request timeout in milliseconds.
* @param {Number} ms
* @returns {Request}
*/
setTimeout(ms) {
this.timeout = ms
return this
}
/**
* Sets abort signal
* @param abortSignal
* @returns {Request}
*/
setAbortSignal(abortSignal) {
this.abortSignal = abortSignal
return this
}
/**
* Sends the request
*
* @param {Object} body
* @returns {Promise}
*/
send(body) {
this.emit(REQUEST_EVENT, this)
let path = this.path
const queryString = qs.stringify(this.queryParams)
if (queryString) {
path += '?' + queryString
}
if (this.cacheTTL) {
const cached = cache.get(path)
if (cached !== undefined) {
return Promise.resolve(cached)
}
}
const type = this.headers[CONTENT_TYPE_HEADER]
if (!type && isObject(body) && !isFormData(body)) {
this.type('application/json')
}
if (body) {
const isJSON = this.headers[CONTENT_TYPE_HEADER] === 'application/json'
body = (isJSON && typeof body !== 'string') ? JSON.stringify(body) : body
}
const unwrapBody = res => {
return this.unwrap ? res.body : res
}
/**
* Caches the response if required
*/
const cacheResponse = res => {
if (this.cacheTTL) {
cache.set(path, res, this.tags, this.cacheTTL)
}
return res
}
/**
* Deletes all relevant to req.cacheTags keys from the cache if this request method is not GET
*/
const flushCache = res => {
if (this.tags && this.method !== 'get') {
cache.deleteByTags(this.tags)
}
return res
}
if (Request.verbose) {
console.log(this.method.toUpperCase(), decodeURIComponent(path), body, this.headers)
}
const withCredentials = typeof this.withCredentials === 'boolean'
? this.withCredentials
: Request.withCredentials
const syncError = new Error()
const request = Request.send(
path,
this.method.toUpperCase(),
this.headers,
body,
this.encoding,
this.timeout,
withCredentials,
this.abortSignal,
)
.then(parseBody)
.then(checkStatus)
.then(unwrapBody)
.then(cacheResponse)
.then(flushCache)
.catch(error => {
error.stack = `${error.stack}${syncError.stack}`
throw error
})
request
.then(result => {
this.emit(RESPONSE_EVENT, result)
this.emit(DONE_EVENT, null, result)
})
.catch(error => {
this.emit(ERROR_EVENT, error)
this.emit(DONE_EVENT, error)
})
return request
}
/**
* If you are too lazy to use method 'send', don't use it and stay cool :)
*
* @param {Function} successHandler
* @param {Function} errorHandler
* @returns {Promise}
*/
then(successHandler, errorHandler) {
this.promise = this.promise || this.send(this.body)
return this.promise.then(successHandler, errorHandler)
}
/**
* @param {Function} errorHandler
* @returns {Promise}
*/
catch(errorHandler) {
this.promise = this.promise || this.send(this.body)
return this.promise.catch(errorHandler)
}
}
function parseBody(res) {
try {
return { ...res, body: JSON.parse(res.body) }
} catch (e) {
return res
}
}
/**
* Checks if a network request came back fine, and throws an error if not
*
* @param {object} response A response from a network request
*
* @return {object|undefined} Returns either the response, or throws an error
*/
function checkStatus(response) {
if (response.status >= 200 && response.status < 300) {
return response
}
throw new ResponseError(response)
}