-
Notifications
You must be signed in to change notification settings - Fork 64
Expand file tree
/
Copy pathrequest.js
More file actions
202 lines (171 loc) · 5.09 KB
/
request.js
File metadata and controls
202 lines (171 loc) · 5.09 KB
Edit and raw actions
OlderNewer
1
// var Base64 = require('Base64')
2
var capability = require('./capability')
3
var foreach = require('foreach')
4
var keys = require('object-keys')
5
var response = require('./response')
6
var stream = require('stream')
7
var util = require('util')
8
9
var IncomingMessage = response.IncomingMessage
10
var rStates = response.readyStates
11
12
function decideMode (preferBinary) {
13
if (capability.fetch) {
14
return 'fetch'
15
} else if (capability.mozchunkedarraybuffer) {
16
return 'moz-chunked-arraybuffer'
17
} else if (capability.msstream) {
18
return 'ms-stream'
19
} else if (capability.arraybuffer && preferBinary) {
20
return 'arraybuffer'
21
} else if (capability.vbArray && preferBinary) {
22
return 'text:vbarray'
23
} else {
24
return 'text'
25
}
26
}
27
28
var ClientRequest = module.exports = function (opts) {
29
var self = this
30
stream.Writable.call(self)
31
32
self._opts = opts
33
self._body = []
34
self._fullHeaders = {}
35
foreach(keys(opts.headers), function (name) {
36
self.setHeader(name, opts.headers[name])
37
})
38
39
var preferBinary
40
if (opts.mode === 'prefer-streaming') {
41
// If streaming is a high priority but binary compatibility isn't
42
preferBinary = false
43
} else if (opts.mode === 'prefer-binary') {
44
// If binary compatibility is the highest priority
45
preferBinary = true
46
} else if (!opts.mode || opts.mode === 'default') {
47
// By default, use binary if text streaming may corrupt data
48
preferBinary = !capability.overrideMimeType
49
} else {
50
throw new Error('Invalid value for opts.mode')
51
}
52
self._mode = decideMode(preferBinary)
53
54
self.on('finish', function () {
55
self._onFinish()
56
})
57
}
58
59
util.inherits(ClientRequest, stream.Writable)
60
61
ClientRequest.prototype.setHeader = function (name, value) {
62
var self = this
63
self._fullHeaders[name.toLowerCase()] = value
64
}
65
66
ClientRequest.prototype.getHeader = function (name) {
67
var self = this
68
return self._fullHeaders[name.toLowerCase()]
69
}
70
71
ClientRequest.prototype.removeHeader = function (name) {
72
var self = this
73
delete self._fullHeaders[name.toLowerCase()]
74
}
75
76
ClientRequest.prototype._onFinish = function () {
77
var self = this
78
79
var opts = self._opts
80
var url = opts.protocol + '//' + opts.hostname +
81
(opts.port ? ':' + opts.port : '') + opts.path
82
83
var user, pass
84
if (opts.auth) {
85
var authMatch = opts.auth.match(/^([^:]*):(.*)$/)
86
user = authMatch[0]
87
pass = authMatch[1]
88
}
89
90
// process and send data
91
var fullHeaders = self._fullHeaders
92
var body
93
if (opts.method in ['PUT', 'POST']) {
94
if (typeof window.Blob === 'function') {
95
body = new window.Blob(self._body.map(function (buffer) {
96
return buffer.toArrayBuffer()
97
}), {
98
type: fullHeaders['content-type'] || ''
99
})
100
} else {
101
// get utf8 string
102
body = Buffer.concat(self._body).toString()
103
}
104
}
105
106
if (self._mode === 'fetch') {
107
var headers = keys(fullHeaders).map(function (name) {
108
return [name, fullHeaders[name]]
109
})
110
111
window.fetch(url, {
112
method: self._opts.method,
113
headers: headers,
114
body: body,
115
mode: 'cors',
116
credentials: opts.credentials ? 'include' : 'omit'
117
}).then(function (response) {
118
self._fetchResponse = response
119
self._connect()
120
})
121
} else {
122
var xhr = self._xhr = new window.XMLHttpRequest() // TODO: old IE
123
xhr.open(self._opts.method, url, true, user, pass)
124
125
// Can't set responseType on really old browsers
126
if ('responseType' in xhr)
127
xhr.responseType = self._mode.split(':')[0]
128
129
if ('withCredentials' in xhr)
130
xhr.withCredentials = !!opts.credentials
131
132
if (self._mode === 'text' && 'overrideMimeType' in xhr)
133
xhr.overrideMimeType('text/plain; charset=x-user-defined')
134
135
keys(fullHeaders, function (name) {
136
xhr.setRequestHeader(name, headers[name])
137
})
138
139
xhr.onreadystatechange = function () {
140
switch (xhr.readyState) {
141
case rStates.LOADING:
142
if (!self._response)
143
self._connect()
144
// falls through
145
case rStates.DONE:
146
self._response._onXHRReadyStateChange()
147
break
148
}
149
}
150
// Necessary for streaming in Firefox, since xhr.response is ONLY defined
151
// in onprogress, not in onreadystatechange with xhr.readyState = 3
152
if (self._mode === 'moz-chunked-arraybuffer') {
153
xhr.onprogress = function () {
154
self._response._onXHRReadyStateChange()
155
}
156
}
157
158
xhr.send(body)
159
// This is the best approximation to where 'socket' should be fired
160
process.nextTick(function () {
161
self.emit('socket')
162
})
163
}
164
}
165
166
ClientRequest.prototype._connect = function () {
167
var self = this
168
169
self._response = new IncomingMessage(self._xhr, self._fetchResponse, self._mode)
170
self.emit('response', self._response)
171
}
172
173
ClientRequest.prototype._write = function (chunk, encoding, cb) {
174
var self = this
175
176
self._body.push(chunk)
177
cb()
178
}
179
180
ClientRequest.prototype.abort = function () {
181
var self = this
182
if (self._xhr)
183
self._xhr.abort()
184
}
185
186
ClientRequest.prototype.end = function (data, encoding, cb) {
187
var self = this
188
if (typeof data === 'function') {
189
cb = data
190
data = undefined
191
}
192
193
if (data)
194
stream.Writable.push.call(self, data, encoding)
195
196
stream.Writable.prototype.end.call(self, cb)
197
}
198
199
ClientRequest.prototype.flushHeaders = function () {}
200
ClientRequest.prototype.setTimeout = function () {}
201
ClientRequest.prototype.setNoDelay = function () {}
202
ClientRequest.prototype.setSocketKeepAlive = function () {}