Skip to content

Commit

Permalink
Merge a2020f9 into 7a49ce7
Browse files Browse the repository at this point in the history
  • Loading branch information
szmarczak committed Jul 14, 2018
2 parents 7a49ce7 + a2020f9 commit e65ab32
Showing 1 changed file with 38 additions and 2 deletions.
40 changes: 38 additions & 2 deletions source/as-stream.js
Expand Up @@ -9,6 +9,8 @@ module.exports = options => {
const input = new PassThrough();
const output = new PassThrough();
const proxy = duplexer3(input, output);
const piped = new Set();
let finished = false;

options.gotRetry.retries = () => 0;

Expand Down Expand Up @@ -52,13 +54,27 @@ module.exports = options => {
proxy.emit('error', new ReadError(error, options));
});

response.pipe(output);

if (options.throwHttpErrors && statusCode !== 304 && (statusCode < 200 || statusCode > 299)) {
proxy.emit('error', new HTTPError(statusCode, response.statusMessage, response.headers, options), null, response);
return;
}

finished = true;

response.pipe(output);

for (const destination of piped) {
if (!destination.headersSent) {
for (const [key, value] of Object.entries(response.headers)) {
if (key.toLowerCase() !== 'content-encoding') {
destination.setHeader(key, value);
}
}

destination.statusCode = response.statusCode;
}
}

proxy.emit('response', response);
});

Expand All @@ -69,5 +85,25 @@ module.exports = options => {
'downloadProgress'
].forEach(event => emitter.on(event, (...args) => proxy.emit(event, ...args)));

const pipe = proxy.pipe.bind(proxy);
const unpipe = proxy.unpipe.bind(proxy);
proxy.pipe = (destination, options) => {
if (finished) {
throw new Error('Failed to pipe. The response has been emitted already.');
}

const result = pipe(destination, options);

if (Reflect.has(destination, 'setHeader')) {
piped.add(destination);
}

return result;
};
proxy.unpipe = stream => {
piped.delete(stream);
return unpipe(stream);
};

return proxy;
};

0 comments on commit e65ab32

Please sign in to comment.