support streaming response

This commit is contained in:
Randall Schmidt 2021-06-10 11:28:05 -04:00
parent f92bd99968
commit 9c9d2b88e1
2 changed files with 30 additions and 3 deletions

@ -1,4 +1,5 @@
const fs = require('fs'); const fs = require('fs');
const stream = require('stream');
const Headers = require('./headers.js'); const Headers = require('./headers.js');
class Response { class Response {
@ -7,19 +8,23 @@ class Response {
this.cacheFilePath = cacheFilePath; this.cacheFilePath = cacheFilePath;
this.headers = new Headers(raw.headers); this.headers = new Headers(raw.headers);
this.fromCache = fromCache; this.fromCache = fromCache;
this.consumed = false; this.bodyUsed = false;
if (this.bodyBuffer.type === 'Buffer') { if (this.bodyBuffer.type === 'Buffer') {
this.bodyBuffer = Buffer.from(this.bodyBuffer); this.bodyBuffer = Buffer.from(this.bodyBuffer);
} }
} }
get body() {
return stream.Readable.from(this.bodyBuffer);
}
consumeBody() { consumeBody() {
if (this.consumed) { if (this.bodyUsed) {
throw new Error('Error: body used already'); throw new Error('Error: body used already');
} }
this.consumed = true; this.bodyUsed = true;
return this.bodyBuffer; return this.bodyBuffer;
} }

@ -246,4 +246,26 @@ describe('Data tests', function() {
assert.strictEqual(expectedPngBuffer.equals(body), true); assert.strictEqual(expectedPngBuffer.equals(body), true);
assert.strictEqual(res.fromCache, true); assert.strictEqual(res.fromCache, true);
}); });
it('Can stream a body', async function() {
res = await fetch(TEXT_BODY_URL);
body = '';
for await (const chunk of res.body) {
body += chunk.toString();
}
assert.strictEqual(TEXT_BODY_EXPECTED, body);
assert.strictEqual(res.fromCache, false);
res = await fetch(TEXT_BODY_URL);
body = '';
for await (const chunk of res.body) {
body += chunk.toString();
}
assert.strictEqual(TEXT_BODY_EXPECTED, body);
assert.strictEqual(res.fromCache, true);
});
}).timeout(10000); }).timeout(10000);