user should be able to resolve cloned body before original body

This commit is contained in:
David Frank 2016-05-26 01:01:56 +08:00
parent 8b8309fe0f
commit 419597fe13
2 changed files with 22 additions and 4 deletions

View File

@ -205,7 +205,7 @@ Body.prototype._convert = function(encoding) {
* @return Mixed
*/
Body.prototype._clone = function(instance) {
var pass;
var p1, p2;
var body = instance.body;
// don't allow cloning a used body
@ -216,9 +216,14 @@ Body.prototype._clone = function(instance) {
// check that body is a stream and not form-data object
// note: we can't clone the form-data object without having it as a dependency
if (bodyStream(body) && typeof body.getBoundary !== 'function') {
pass = new PassThrough();
body.pipe(pass);
body = pass;
// tee instance body
p1 = new PassThrough();
p2 = new PassThrough();
body.pipe(p1);
body.pipe(p2);
// set instance body to teed body and return the other teed body
instance.body = p1;
body = p2;
}
return body;

View File

@ -939,6 +939,19 @@ describe('node-fetch', function() {
});
});
it('should allow cloning a json response, first log as text response, then return json object', function() {
url = base + '/json';
return fetch(url).then(function(res) {
var r1 = res.clone();
return r1.text().then(function(result) {
expect(result).to.equal('{"name":"value"}');
return res.json().then(function(result) {
expect(result).to.deep.equal({name: 'value'});
});
});
});
});
it('should not allow cloning a response after its been used', function() {
url = base + '/hello';
return fetch(url).then(function(res) {