-
Notifications
You must be signed in to change notification settings - Fork 106
/
nodejs.js
174 lines (163 loc) · 4.67 KB
/
nodejs.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
'use strict'
const http = require('http')
const https = require('https')
const { URL } = require('url')
const isStream = require('is-stream')
const caseless = require('caseless')
const bytes = require('bytesish')
const bent = require('./core')
const zlib = require('zlib')
const { PassThrough } = require('stream')
const compression = {}
/* istanbul ignore else */
if (zlib.createBrotliDecompress) compression.br = () => zlib.createBrotliDecompress()
/* istanbul ignore else */
if (zlib.createGunzip) compression.gzip = () => zlib.createGunzip()
/* istanbul ignore else */
if (zlib.createInflate) compression.deflate = () => zlib.createInflate()
const acceptEncoding = Object.keys(compression).join(', ')
const getResponse = resp => {
const ret = new PassThrough()
ret.statusCode = resp.statusCode
ret.status = resp.statusCode
ret.statusMessage = resp.statusMessage
ret.headers = resp.headers
ret._response = resp
if (ret.headers['content-encoding']) {
const encodings = ret.headers['content-encoding'].split(', ').reverse()
while (encodings.length) {
const enc = encodings.shift()
if (compression[enc]) {
resp = resp.pipe(compression[enc]())
} else {
break
}
}
}
return resp.pipe(ret)
}
class StatusError extends Error {
constructor (res, ...params) {
super(...params)
Error.captureStackTrace(this, StatusError)
this.message = `Incorrect statusCode: ${res.statusCode}`
this.statusCode = res.statusCode
this.json = res.json
this.text = res.text
this.arrayBuffer = res.arrayBuffer
this.headers = res.headers
let buffer
const get = () => {
if (!buffer) buffer = this.arrayBuffer()
return buffer
}
Object.defineProperty(this, 'responseBody', { get })
}
}
const getBuffer = stream => new Promise((resolve, reject) => {
const parts = []
stream.on('error', reject)
stream.on('end', () => resolve(Buffer.concat(parts)))
stream.on('data', d => parts.push(d))
})
const decodings = res => {
let _buffer
res.arrayBuffer = () => {
if (!_buffer) {
_buffer = getBuffer(res)
return _buffer
} else {
throw new Error('body stream is locked')
}
}
res.text = () => res.arrayBuffer().then(buff => buff.toString())
res.json = async () => {
const str = await res.text()
try {
return JSON.parse(str)
} catch (e) {
e.message += `str"${str}"`
throw e
}
}
}
const mkrequest = (statusCodes, method, encoding, headers, baseurl) => (_url, body = null, _headers = {}) => {
_url = baseurl + (_url || '')
const parsed = new URL(_url)
let h
if (parsed.protocol === 'https:') {
h = https
} else if (parsed.protocol === 'http:') {
h = http
} else {
throw new Error(`Unknown protocol, ${parsed.protocol}`)
}
const request = {
path: parsed.pathname + parsed.search,
port: parsed.port,
method: method,
headers: { ...(headers || {}), ..._headers },
hostname: parsed.hostname
}
if (parsed.username || parsed.password) {
request.auth = [parsed.username, parsed.password].join(':')
}
const c = caseless(request.headers)
if (encoding === 'json') {
if (!c.get('accept')) {
c.set('accept', 'application/json')
}
}
if (!c.has('accept-encoding')) {
c.set('accept-encoding', acceptEncoding)
}
return new Promise((resolve, reject) => {
const req = h.request(request, async res => {
res = getResponse(res)
decodings(res)
res.status = res.statusCode
if (!statusCodes.has(res.statusCode)) {
return reject(new StatusError(res))
}
if (!encoding) return resolve(res)
else {
/* istanbul ignore else */
if (encoding === 'buffer') {
resolve(res.arrayBuffer())
} else if (encoding === 'json') {
resolve(res.json())
} else if (encoding === 'string') {
resolve(res.text())
}
}
})
req.on('error', reject)
if (body) {
if (body instanceof ArrayBuffer || ArrayBuffer.isView(body)) {
body = bytes.native(body)
}
if (Buffer.isBuffer(body)) {
// noop
} else if (typeof body === 'string') {
body = Buffer.from(body)
} else if (isStream(body)) {
body.pipe(req)
body = null
} else if (typeof body === 'object') {
if (!c.has('content-type')) {
req.setHeader('content-type', 'application/json')
}
body = Buffer.from(JSON.stringify(body))
} else {
reject(new Error('Unknown body type.'))
}
if (body) {
req.setHeader('content-length', body.length)
req.end(body)
}
} else {
req.end()
}
})
}
module.exports = bent(mkrequest)