Skip to content

Latest commit

 

History

History
221 lines (188 loc) · 5.53 KB

File metadata and controls

221 lines (188 loc) · 5.53 KB
 
Jun 24, 2015
Jun 24, 2015
1
// var Base64 = require('Base64')
2
var capability = require('./capability')
Jul 2, 2015
Jul 2, 2015
3
var foreach = require('foreach')
4
var keys = require('object-keys')
Jun 24, 2015
Jun 24, 2015
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
Jul 2, 2015
Jul 2, 2015
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'
Jul 3, 2015
Jul 3, 2015
21
} else if (capability.vbArray && preferBinary) {
22
return 'text:vbarray'
Jul 2, 2015
Jul 2, 2015
23
} else {
24
return 'text'
25
}
26
}
27
Jun 24, 2015
Jun 24, 2015
28
var ClientRequest = module.exports = function (opts) {
29
var self = this
30
stream.Writable.call(self)
31
32
self._opts = opts
33
self._body = []
Jul 7, 2015
Jul 7, 2015
34
self._headers = {}
Jul 2, 2015
Jul 2, 2015
35
foreach(keys(opts.headers), function (name) {
Jun 24, 2015
Jun 24, 2015
36
self.setHeader(name, opts.headers[name])
37
})
38
Jul 2, 2015
Jul 2, 2015
39
var preferBinary
Jul 3, 2015
Jul 3, 2015
40
if (opts.mode === 'prefer-streaming') {
Jul 2, 2015
Jul 2, 2015
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)
Jun 24, 2015
Jun 24, 2015
53
Jul 2, 2015
Jul 2, 2015
54
self.on('finish', function () {
55
self._onFinish()
56
})
Jun 24, 2015
Jun 24, 2015
57
}
58
59
util.inherits(ClientRequest, stream.Writable)
60
61
ClientRequest.prototype.setHeader = function (name, value) {
62
var self = this
Jul 7, 2015
Jul 7, 2015
63
self._headers[name.toLowerCase()] = {
64
name: name,
65
value: value
66
}
Jun 24, 2015
Jun 24, 2015
67
}
68
69
ClientRequest.prototype.getHeader = function (name) {
70
var self = this
Jul 7, 2015
Jul 7, 2015
71
return self._headers[name.toLowerCase()].value
Jun 24, 2015
Jun 24, 2015
72
}
73
74
ClientRequest.prototype.removeHeader = function (name) {
75
var self = this
Jul 7, 2015
Jul 7, 2015
76
delete self._headers[name.toLowerCase()]
Jun 24, 2015
Jun 24, 2015
77
}
78
79
ClientRequest.prototype._onFinish = function () {
80
var self = this
81
82
var opts = self._opts
Jul 7, 2015
Jul 7, 2015
83
var url = ''
84
// If hostname is provided, include protocol, hostname, port
85
if (opts.hostname)
86
url = (opts.protocol || '') + '//' + opts.hostname + (opts.port ? (':' + opots.port) : '')
87
88
url += opts.path
Jun 24, 2015
Jun 24, 2015
89
90
var user, pass
91
if (opts.auth) {
Jul 1, 2015
Jul 1, 2015
92
var authMatch = opts.auth.match(/^([^:]*):(.*)$/)
Jun 24, 2015
Jun 24, 2015
93
user = authMatch[0]
94
pass = authMatch[1]
95
}
96
Jul 7, 2015
Jul 7, 2015
97
var headersObj = self._headers
Jun 24, 2015
Jun 24, 2015
98
var body
Jul 1, 2015
Jul 1, 2015
99
if (opts.method in ['PUT', 'POST']) {
Jul 7, 2015
Jul 7, 2015
100
if (util.isFunction(window.Blob)) {
Jul 1, 2015
Jul 1, 2015
101
body = new window.Blob(self._body.map(function (buffer) {
102
return buffer.toArrayBuffer()
103
}), {
Jul 7, 2015
Jul 7, 2015
104
type: (headersObj['content-type'] || {}).value || ''
Jul 1, 2015
Jul 1, 2015
105
})
106
} else {
107
// get utf8 string
108
body = Buffer.concat(self._body).toString()
109
}
Jun 24, 2015
Jun 24, 2015
110
}
111
112
if (self._mode === 'fetch') {
Jul 7, 2015
Jul 7, 2015
113
var headers = keys(headersObj).map(function (name) {
114
return [headersObj[name].name, headersObj[name].value]
Jun 24, 2015
Jun 24, 2015
115
})
116
Jul 1, 2015
Jul 1, 2015
117
window.fetch(url, {
Jun 24, 2015
Jun 24, 2015
118
method: self._opts.method,
119
headers: headers,
120
body: body,
121
mode: 'cors',
122
credentials: opts.credentials ? 'include' : 'omit'
123
}).then(function (response) {
124
self._fetchResponse = response
125
self._connect()
126
})
127
} else {
Jul 7, 2015
Jul 7, 2015
128
var xhr = self._xhr = new window.XMLHttpRequest()
Jun 24, 2015
Jun 24, 2015
129
xhr.open(self._opts.method, url, true, user, pass)
130
131
// Can't set responseType on really old browsers
132
if ('responseType' in xhr)
Jul 3, 2015
Jul 3, 2015
133
xhr.responseType = self._mode.split(':')[0]
Jun 24, 2015
Jun 24, 2015
134
135
if ('withCredentials' in xhr)
136
xhr.withCredentials = !!opts.credentials
137
138
if (self._mode === 'text' && 'overrideMimeType' in xhr)
139
xhr.overrideMimeType('text/plain; charset=x-user-defined')
140
Jul 7, 2015
Jul 7, 2015
141
foreach(keys(headersObj), function (name) {
142
xhr.setRequestHeader(headersObj[name].name, headersObj[name].value)
Jun 24, 2015
Jun 24, 2015
143
})
144
Jul 3, 2015
Jul 3, 2015
145
self._response = null
Jun 24, 2015
Jun 24, 2015
146
xhr.onreadystatechange = function () {
147
switch (xhr.readyState) {
148
case rStates.LOADING:
149
case rStates.DONE:
Jul 3, 2015
Jul 3, 2015
150
if (!self._response && statusValid(xhr))
151
self._connect()
152
if (self._response)
153
self._response._onXHRReadyStateChange()
Jun 24, 2015
Jun 24, 2015
154
break
155
}
156
}
Jul 2, 2015
Jul 2, 2015
157
// Necessary for streaming in Firefox, since xhr.response is ONLY defined
158
// in onprogress, not in onreadystatechange with xhr.readyState = 3
159
if (self._mode === 'moz-chunked-arraybuffer') {
160
xhr.onprogress = function () {
161
self._response._onXHRReadyStateChange()
162
}
163
}
Jun 24, 2015
Jun 24, 2015
164
165
xhr.send(body)
166
// This is the best approximation to where 'socket' should be fired
167
process.nextTick(function () {
168
self.emit('socket')
169
})
170
}
171
}
172
Jul 3, 2015
Jul 3, 2015
173
/**
174
* Checks if xhr.status is readable. Even though the spec says it should
175
* be available in readyState 3, accessing it throws an exception in IE8
176
*/
177
function statusValid (xhr) {
178
try {
179
return (xhr.status !== null)
180
} catch (e) {
181
return false
182
}
183
}
184
Jun 24, 2015
Jun 24, 2015
185
ClientRequest.prototype._connect = function () {
186
var self = this
187
188
self._response = new IncomingMessage(self._xhr, self._fetchResponse, self._mode)
189
self.emit('response', self._response)
190
}
191
192
ClientRequest.prototype._write = function (chunk, encoding, cb) {
193
var self = this
194
195
self._body.push(chunk)
196
cb()
197
}
198
199
ClientRequest.prototype.abort = function () {
200
var self = this
201
if (self._xhr)
202
self._xhr.abort()
203
}
204
205
ClientRequest.prototype.end = function (data, encoding, cb) {
206
var self = this
207
if (typeof data === 'function') {
208
cb = data
209
data = undefined
210
}
211
212
if (data)
213
stream.Writable.push.call(self, data, encoding)
214
215
stream.Writable.prototype.end.call(self, cb)
216
}
217
218
ClientRequest.prototype.flushHeaders = function () {}
219
ClientRequest.prototype.setTimeout = function () {}
220
ClientRequest.prototype.setNoDelay = function () {}
221
ClientRequest.prototype.setSocketKeepAlive = function () {}