Skip to content

Commit

Permalink
Fix incorrect response.complete when using cache
Browse files Browse the repository at this point in the history
  • Loading branch information
szmarczak committed Jul 2, 2021
1 parent 8d6a680 commit 9e15d88
Show file tree
Hide file tree
Showing 2 changed files with 51 additions and 5 deletions.
18 changes: 13 additions & 5 deletions source/core/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -987,16 +987,24 @@ export default class Request extends Duplex implements RequestEvents<Request> {

let request: ClientRequest | Promise<ClientRequest>;

// This is ugly
const cacheRequest = cacheableStore.get((options as any).cache)!(options, async response => {
// TODO: Fix `cacheable-response`
(response as any)._readableState.autoDestroy = false;
// TODO: Fix `cacheable-response`. This is ugly.
const cacheRequest = cacheableStore.get((options as any).cache)!(options, async (response: any) => {
response._readableState.autoDestroy = false;

if (request) {
const fix = () => {
if (response.req) {
response.complete = response.req.res.complete;
}
};

response.prependOnceListener('end', fix);
fix();

(await request).emit('cacheableResponse', response);
}

resolve(response as unknown as ResponseLike);
resolve(response);
});

cacheRequest.once('error', reject);
Expand Down
38 changes: 38 additions & 0 deletions test/cache.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import {promisify} from 'util';
import {Agent} from 'http';
import {gzip} from 'zlib';
import test from 'ava';
import pEvent from 'p-event';
Expand Down Expand Up @@ -403,3 +404,40 @@ test('allows internal modifications', async t => {

await t.notThrowsAsync(client.get('http://example.com/test'));
});

test('response.complete is true when using keepalive agent', withServer, async (t, server, got) => {
const agent = {
http: new Agent({keepAlive: true})
};

const etag = 'foobar';

const payload = JSON.stringify({foo: 'bar'});
const compressed = await promisify(gzip)(payload);

server.get('/', (request, response) => {
if (request.headers['if-none-match'] === etag) {
response.statusCode = 304;
response.end();
} else {
response.setHeader('content-encoding', 'gzip');
response.setHeader('cache-control', 'public, max-age=60');
response.setHeader('etag', etag);
response.end(compressed);
}
});

const cache = new Map();

const first = await got({
cache,
responseType: 'json',
decompress: true,
retry: {
limit: 2
},
agent
});

t.true(first.complete);
});

0 comments on commit 9e15d88

Please sign in to comment.