Skip to content

Commit 9e15d88

Browse files
committedJul 2, 2021
Fix incorrect response.complete when using cache
1 parent 8d6a680 commit 9e15d88

File tree

2 files changed

+51
-5
lines changed

2 files changed

+51
-5
lines changed
 

‎source/core/index.ts

+13-5
Original file line numberDiff line numberDiff line change
@@ -987,16 +987,24 @@ export default class Request extends Duplex implements RequestEvents<Request> {
987987

988988
let request: ClientRequest | Promise<ClientRequest>;
989989

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

995994
if (request) {
995+
const fix = () => {
996+
if (response.req) {
997+
response.complete = response.req.res.complete;
998+
}
999+
};
1000+
1001+
response.prependOnceListener('end', fix);
1002+
fix();
1003+
9961004
(await request).emit('cacheableResponse', response);
9971005
}
9981006

999-
resolve(response as unknown as ResponseLike);
1007+
resolve(response);
10001008
});
10011009

10021010
cacheRequest.once('error', reject);

‎test/cache.ts

+38
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
import {promisify} from 'util';
2+
import {Agent} from 'http';
23
import {gzip} from 'zlib';
34
import test from 'ava';
45
import pEvent from 'p-event';
@@ -403,3 +404,40 @@ test('allows internal modifications', async t => {
403404

404405
await t.notThrowsAsync(client.get('http://example.com/test'));
405406
});
407+
408+
test('response.complete is true when using keepalive agent', withServer, async (t, server, got) => {
409+
const agent = {
410+
http: new Agent({keepAlive: true})
411+
};
412+
413+
const etag = 'foobar';
414+
415+
const payload = JSON.stringify({foo: 'bar'});
416+
const compressed = await promisify(gzip)(payload);
417+
418+
server.get('/', (request, response) => {
419+
if (request.headers['if-none-match'] === etag) {
420+
response.statusCode = 304;
421+
response.end();
422+
} else {
423+
response.setHeader('content-encoding', 'gzip');
424+
response.setHeader('cache-control', 'public, max-age=60');
425+
response.setHeader('etag', etag);
426+
response.end(compressed);
427+
}
428+
});
429+
430+
const cache = new Map();
431+
432+
const first = await got({
433+
cache,
434+
responseType: 'json',
435+
decompress: true,
436+
retry: {
437+
limit: 2
438+
},
439+
agent
440+
});
441+
442+
t.true(first.complete);
443+
});

0 commit comments

Comments
 (0)
Please sign in to comment.