diff --git a/fetch.js b/fetch.js index c1ff6df..9f1f569 100644 --- a/fetch.js +++ b/fetch.js @@ -178,8 +178,12 @@ } else if (!body) { this._bodyText = '' } else if (support.arrayBuffer && ArrayBuffer.prototype.isPrototypeOf(body)) { - // Only support ArrayBuffers for POST method. - // Receiving ArrayBuffers happens via Blobs, instead. + if (body.slice) { + this._bodyArrayBuffer = new Uint8Array(body.slice(0)) + } else { + this._bodyArrayBuffer = new Uint8Array(body.byteLength) + this._bodyArrayBuffer.set(new Uint8Array(body)) + } } else { throw new Error('unsupported BodyInit type') } @@ -211,10 +215,6 @@ } } - this.arrayBuffer = function() { - return this.blob().then(readBlobAsArrayBuffer) - } - this.text = function() { var rejected = consumed(this) if (rejected) { @@ -231,8 +231,17 @@ } } else { this.text = function() { - var rejected = consumed(this) - return rejected ? rejected : Promise.resolve(this._bodyText) + return consumed(this) || Promise.resolve(this._bodyText) + } + } + + if (support.arrayBuffer) { + this.arrayBuffer = function() { + if (this._bodyArrayBuffer) { + return consumed(this) || Promise.resolve(this._bodyArrayBuffer.buffer) + } else { + return this.blob().then(readBlobAsArrayBuffer) + } } } diff --git a/test/test.js b/test/test.js index d5fb33f..fed12b4 100644 --- a/test/test.js +++ b/test/test.js @@ -444,6 +444,28 @@ suite('Request', function() { }) }) + featureDependent(suite, support.arrayBuffer, 'type ArrayBuffer', function() { + test('consume as array buffer', function() { + var text = 'name=Hubot' + + var buf = new ArrayBuffer(text.length) + var view = new Uint8Array(buf) + + for(var i = 0; i < text.length; i++) { + view[i] = text.charCodeAt(i) + } + + var request = new Request('', {method: 'POST', body: buf}) + return request.arrayBuffer().then(function(buffer) { + var bufView = new Uint8Array(buffer) + assert.equal(bufView.byteLength, view.length) + for(var i = 0; i < bufView.length; i++) { + assert.equal(bufView[i], view[i]) + } + }) + }) + }) + suite('type USVString', function() { test('consume as text', function() { var request = new Request('', {method: 'POST', body: 'hello'}) @@ -482,6 +504,28 @@ suite('Response', function() { }) }) + featureDependent(suite, support.arrayBuffer, 'type ArrayBuffer', function() { + test('consume as array buffer', function() { + var text = 'name=Hubot' + + var buf = new ArrayBuffer(text.length) + var view = new Uint8Array(buf) + + for(var i = 0; i < text.length; i++) { + view[i] = text.charCodeAt(i) + } + + var response = new Response(buf) + return response.arrayBuffer().then(function(buffer) { + var bufView = new Uint8Array(buffer) + assert.equal(bufView.byteLength, view.byteLength) + for(var i = 0; i < bufView.byteLength; i++) { + assert.equal(bufView[i], view[i]) + } + }) + }) + }) + suite('type USVString', function() { test('consume as text', function() { var response = new Response('hello')