Skip to content

Commit

Permalink
feat: support lazy-reading from response stream (#74)
Browse files Browse the repository at this point in the history
  • Loading branch information
stephenplusplus authored Aug 9, 2019
1 parent 6ec812e commit f6db420
Show file tree
Hide file tree
Showing 3 changed files with 39 additions and 2 deletions.
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,7 @@
"dependencies": {
"https-proxy-agent": "^2.2.1",
"node-fetch": "^2.2.0",
"stream-events": "^1.0.5",
"uuid": "^3.3.2"
},
"devDependencies": {
Expand Down
18 changes: 16 additions & 2 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ import {Agent} from 'https';
import fetch, * as f from 'node-fetch';
import {PassThrough, Readable} from 'stream';
import * as uuid from 'uuid';
const streamEvents = require('stream-events');

export interface CoreOptions {
method?:
Expand Down Expand Up @@ -265,11 +266,24 @@ function teenyRequest(

if (callback === undefined) {
// Stream mode
const requestStream = new PassThrough();
const requestStream = streamEvents(new PassThrough());
// tslint:disable-next-line no-any
let responseStream: any;
requestStream.once('reading', () => {
if (responseStream) {
responseStream.pipe(requestStream);
} else {
requestStream.once('response', () => {
responseStream.pipe(requestStream);
});
}
});
options.compress = false;
fetch(uri, options).then(
res => {
res.body.on('error', err => {
responseStream = res.body;

responseStream.on('error', (err: Error) => {
requestStream.emit('error', err);
});

Expand Down
22 changes: 22 additions & 0 deletions test/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -172,4 +172,26 @@ describe('teeny', () => {
return done();
});
});

it('should pipe response stream to user', done => {
const scope = mockJson();
teenyRequest({uri})
.on('error', done)
.on('data', () => {
done();
});
});

it('should not pipe response stream to user unless they ask for it', done => {
const scope = mockJson();
const stream = teenyRequest({uri}).on('error', done);
stream.on('response', responseStream => {
assert.strictEqual(responseStream.body._readableState.pipesCount, 0);

stream.on('data', () => {
assert.strictEqual(responseStream.body._readableState.pipesCount, 1);
done();
});
});
});
});

0 comments on commit f6db420

Please sign in to comment.