提交 46705f79 编写于 作者: K Kirill Konshin 提交者: Mislav Marohnić

Add `Request.clone()` and `Response.clone()` methods

https://fetch.spec.whatwg.org/#dom-response-clone
上级 eb4aec25
......@@ -236,6 +236,27 @@
this._initBody(body)
}
function cloneBody(body) {
if (body._bodyText) {
return body._bodyText
} else if (body._bodyBlob) {
return body._bodyBlob
} else if (body._bodyFormData) {
return body._bodyFormData
}
return null
}
Request.prototype.clone = function() {
return new Request(cloneBody(this), {
method: this.method,
mode: this.mode,
credentials: this.credentials,
headers: new Headers(this.headers),
url: this.url
})
}
function decode(body) {
var form = new FormData()
body.trim().split('&').forEach(function(bytes) {
......@@ -279,6 +300,15 @@
Body.call(Response.prototype)
Response.prototype.clone = function() {
return new Response(cloneBody(this), {
status: this.status,
statusText: this.statusText,
headers: new Headers(this.headers),
url: this.url
})
}
Response.error = function() {
var response = new Response(null, {status: 0, statusText: ''})
response.type = 'error'
......
......@@ -385,6 +385,35 @@ suite('Response', function() {
})
})
test('clone text response', function() {
var res = new Response('{"foo":"bar"}', {
headers: {'content-type': 'application/json'}
})
var clone = res.clone()
assert.notEqual(clone.headers, res.headers, 'headers were cloned')
assert.equal(clone.headers.get('content-type'), 'application/json')
return Promise.all([clone.json(), res.json()]).then(function(jsons){
assert.deepEqual(jsons[0], jsons[1], 'json of cloned object is the same as original')
})
})
;(Response.prototype.arrayBuffer ? test : test.skip)('clone blob response', function() {
return fetch('/binary').then(function(response) {
return Promise.all([response.clone().arrayBuffer(), response.arrayBuffer()]).then(function(bufs){
bufs.forEach(function(buf){
assert(buf instanceof ArrayBuffer, 'buf is an ArrayBuffer instance')
assert.equal(buf.byteLength, 256, 'buf.byteLength is correct')
var view = new Uint8Array(buf)
for (var i = 0; i < 256; i++) {
assert.equal(view[i], i)
}
})
})
})
})
test('error creates error Response', function() {
var r = Response.error()
assert(r instanceof Response)
......
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册