Skip to content

Latest commit

 

History

History
213 lines (181 loc) · 5.29 KB

File metadata and controls

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