support streaming response
This commit is contained in:
parent
f92bd99968
commit
9c9d2b88e1
@ -1,4 +1,5 @@
|
||||
const fs = require('fs');
|
||||
const stream = require('stream');
|
||||
const Headers = require('./headers.js');
|
||||
|
||||
class Response {
|
||||
@ -7,19 +8,23 @@ class Response {
|
||||
this.cacheFilePath = cacheFilePath;
|
||||
this.headers = new Headers(raw.headers);
|
||||
this.fromCache = fromCache;
|
||||
this.consumed = false;
|
||||
this.bodyUsed = false;
|
||||
|
||||
if (this.bodyBuffer.type === 'Buffer') {
|
||||
this.bodyBuffer = Buffer.from(this.bodyBuffer);
|
||||
}
|
||||
}
|
||||
|
||||
get body() {
|
||||
return stream.Readable.from(this.bodyBuffer);
|
||||
}
|
||||
|
||||
consumeBody() {
|
||||
if (this.consumed) {
|
||||
if (this.bodyUsed) {
|
||||
throw new Error('Error: body used already');
|
||||
}
|
||||
|
||||
this.consumed = true;
|
||||
this.bodyUsed = true;
|
||||
return this.bodyBuffer;
|
||||
}
|
||||
|
||||
|
@ -246,4 +246,26 @@ describe('Data tests', function() {
|
||||
assert.strictEqual(expectedPngBuffer.equals(body), 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);
|
||||
|
Reference in New Issue
Block a user