-
Notifications
You must be signed in to change notification settings - Fork 30
/
http.js
334 lines (280 loc) · 8.51 KB
/
http.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
/* eslint-disable no-undef */
'use strict'
const fetch = require('node-fetch')
const merge = require('merge-options')
const { URL, URLSearchParams } = require('iso-url')
const TextDecoder = require('./text-encoder')
const AbortController = require('abort-controller')
const Request = fetch.Request
const Headers = fetch.Headers
class TimeoutError extends Error {
constructor () {
super('Request timed out')
this.name = 'TimeoutError'
}
}
class HTTPError extends Error {
constructor (response) {
super(response.statusText)
this.name = 'HTTPError'
this.response = response
}
}
const timeout = (promise, ms, abortController) => {
if (ms === undefined) {
return promise
}
return new Promise((resolve, reject) => {
const timeoutID = setTimeout(() => {
reject(new TimeoutError())
abortController.abort()
}, ms)
promise
.then((result) => {
clearTimeout(timeoutID)
resolve(result)
}, (err) => {
clearTimeout(timeoutID)
reject(err)
})
})
}
const defaults = {
headers: {},
throwHttpErrors: true,
credentials: 'same-origin',
transformSearchParams: p => p
}
/**
* @typedef {Object} APIOptions - creates a new type named 'SpecialType'
* @prop {any} [body] - Request body
* @prop {Object} [json] - JSON shortcut
* @prop {string} [method] - GET, POST, PUT, DELETE, etc.
* @prop {string} [base] - The base URL to use in case url is a relative URL
* @prop {Headers|Record<string, string>} [headers] - Request header.
* @prop {number} [timeout] - Amount of time until request should timeout in ms.
* @prop {AbortSignal} [signal] - Signal to abort the request.
* @prop {URLSearchParams|Object} [searchParams] - URL search param.
* @prop {string} [credentials]
* @prop {boolean} [throwHttpErrors]
* @prop {function(URLSearchParams): URLSearchParams } [transformSearchParams]
* @prop {function(any): any} [transform] - When iterating the response body, transform each chunk with this function.
* @prop {function(Response): Promise<void>} [handleError] - Handle errors
*/
class HTTP {
/**
*
* @param {APIOptions} options
*/
constructor (options = {}) {
/** @type {APIOptions} */
this.opts = merge(defaults, options)
this.opts.headers = new Headers(options.headers)
// connect internal abort to external
this.abortController = new AbortController()
if (this.opts.signal) {
this.opts.signal.addEventListener('abort', () => {
this.abortController.abort()
})
}
this.opts.signal = this.abortController.signal
}
/**
* Fetch
*
* @param {string | URL | Request} resource
* @param {APIOptions} options
* @returns {Promise<Response>}
*/
async fetch (resource, options = {}) {
/** @type {APIOptions} */
const opts = merge(this.opts, options)
opts.headers = new Headers(opts.headers)
// validate resource type
if (typeof resource !== 'string' && !(resource instanceof URL || resource instanceof Request)) {
throw new TypeError('`resource` must be a string, URL, or Request')
}
// validate resource format and normalize with prefixUrl
if (opts.base && typeof opts.base === 'string' && typeof resource === 'string') {
if (resource.startsWith('/')) {
throw new Error('`resource` must not begin with a slash when using `base`')
}
if (!opts.base.endsWith('/')) {
opts.base += '/'
}
resource = opts.base + resource
}
// TODO: try to remove the logic above or fix URL instance input without trailing '/'
const url = new URL(resource, opts.base)
if (opts.searchParams) {
url.search = opts.transformSearchParams(new URLSearchParams(opts.searchParams))
}
if (opts.json !== undefined) {
opts.body = JSON.stringify(opts.json)
opts.headers.set('content-type', 'application/json')
}
const response = await timeout(fetch(url, opts), opts.timeout, this.abortController)
if (!response.ok && opts.throwHttpErrors) {
if (opts.handleError) {
await opts.handleError(response)
}
throw new HTTPError(response)
}
response.iterator = function () {
const it = streamToAsyncIterator(response.body)
if (!isAsyncIterator(it)) {
throw new Error('Can\'t convert fetch body into a Async Iterator:')
}
return it
}
response.ndjson = async function * () {
for await (const chunk of ndjson(response.iterator())) {
if (options.transform) {
yield options.transform(chunk)
} else {
yield chunk
}
}
}
return response
}
/**
* @param {string | URL | Request} resource
* @param {APIOptions} options
* @returns {Promise<Response>}
*/
post (resource, options = {}) {
return this.fetch(resource, merge(this.opts, options, { method: 'POST' }))
}
/**
* @param {string | URL | Request} resource
* @param {APIOptions} options
* @returns {Promise<Response>}
*/
get (resource, options = {}) {
return this.fetch(resource, merge(this.opts, options, { method: 'GET' }))
}
/**
* @param {string | URL | Request} resource
* @param {APIOptions} options
* @returns {Promise<Response>}
*/
put (resource, options = {}) {
return this.fetch(resource, merge(this.opts, options, { method: 'PUT' }))
}
/**
* @param {string | URL | Request} resource
* @param {APIOptions} options
* @returns {Promise<Response>}
*/
delete (resource, options = {}) {
return this.fetch(resource, merge(this.opts, options, { method: 'DELETE' }))
}
/**
* @param {string | URL | Request} resource
* @param {APIOptions} options
* @returns {Promise<Response>}
*/
options (resource, options = {}) {
return this.fetch(resource, merge(this.opts, options, { method: 'OPTIONS' }))
}
}
/**
* Parses NDJSON chunks from an iterator
*
* @param {AsyncGenerator<Uint8Array, void, any>} source
* @returns {AsyncGenerator<Object, void, any>}
*/
const ndjson = async function * (source) {
const decoder = new TextDecoder()
let buf = ''
for await (const chunk of source) {
buf += decoder.decode(chunk, { stream: true })
const lines = buf.split(/\r?\n/)
for (let i = 0; i < lines.length - 1; i++) {
const l = lines[i].trim()
if (l.length > 0) {
yield JSON.parse(l)
}
}
buf = lines[lines.length - 1]
}
buf += decoder.decode()
buf = buf.trim()
if (buf.length !== 0) {
yield JSON.parse(buf)
}
}
const streamToAsyncIterator = function (source) {
if (isAsyncIterator(source)) {
// Workaround for https://github.com/node-fetch/node-fetch/issues/766
if (Object.prototype.hasOwnProperty.call(source, 'readable') && Object.prototype.hasOwnProperty.call(source, 'writable')) {
const iter = source[Symbol.asyncIterator]()
const wrapper = {
next: iter.next.bind(iter),
return: () => {
source.destroy()
return iter.return()
},
[Symbol.asyncIterator]: () => {
return wrapper
}
}
return wrapper
}
return source
}
const reader = source.getReader()
return {
next () {
return reader.read()
},
return () {
reader.releaseLock()
return {}
},
[Symbol.asyncIterator] () {
return this
}
}
}
const isAsyncIterator = (obj) => {
return typeof obj === 'object' &&
obj !== null &&
// typeof obj.next === 'function' &&
typeof obj[Symbol.asyncIterator] === 'function'
}
HTTP.HTTPError = HTTPError
HTTP.TimeoutError = TimeoutError
HTTP.streamToAsyncIterator = streamToAsyncIterator
/**
* @param {string | URL | Request} resource
* @param {APIOptions} options
* @returns {Promise<Response>}
*/
HTTP.post = (resource, options) => new HTTP(options).post(resource, options)
/**
* @param {string | URL | Request} resource
* @param {APIOptions} options
* @returns {Promise<Response>}
*/
HTTP.get = (resource, options) => new HTTP(options).get(resource, options)
/**
* @param {string | URL | Request} resource
* @param {APIOptions} options
* @returns {Promise<Response>}
*/
HTTP.put = (resource, options) => new HTTP(options).put(resource, options)
/**
* @param {string | URL | Request} resource
* @param {APIOptions} options
* @returns {Promise<Response>}
*/
HTTP.delete = (resource, options) => new HTTP(options).delete(resource, options)
/**
* @param {string | URL | Request} resource
* @param {APIOptions} options
* @returns {Promise<Response>}
*/
HTTP.options = (resource, options) => new HTTP(options).options(resource, options)
module.exports = HTTP