Skip to content

Commit 3e9d3af

Browse files
authored
Fix request body not being properly cached (#2150)
1 parent 6c7ebab commit 3e9d3af

File tree

2 files changed

+30
-0
lines changed

2 files changed

+30
-0
lines changed

source/core/index.ts

+1
Original file line numberDiff line numberDiff line change
@@ -1110,6 +1110,7 @@ export default class Request extends Duplex implements RequestEvents<Request> {
11101110
if (options.cache) {
11111111
(this._requestOptions as any)._request = request;
11121112
(this._requestOptions as any).cache = options.cache;
1113+
(this._requestOptions as any).body = options.body;
11131114
this._prepareCache(options.cache as StorageAdapter);
11141115
}
11151116

test/cache.ts

+29
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
import {Buffer} from 'buffer';
22
import {promisify} from 'util';
3+
import {Readable as ReadableStream} from 'stream';
34
import {Agent} from 'http';
45
import {gzip} from 'zlib';
56
import test from 'ava';
@@ -44,6 +45,34 @@ test('cacheable responses are cached', withServer, async (t, server, got) => {
4445
t.is(firstResponse.body, secondResponse.body);
4546
});
4647

48+
test('cacheable responses to POST requests are cached', withServer, async (t, server, got) => {
49+
server.post('/', cacheEndpoint);
50+
51+
const cache = new Map();
52+
53+
const firstResponse = await got({method: 'POST', body: 'test', cache});
54+
const secondResponse = await got({method: 'POST', body: 'test', cache});
55+
56+
t.is(cache.size, 1);
57+
t.is(firstResponse.body, secondResponse.body);
58+
});
59+
60+
test('non-cacheable responses to POST requests are not cached', withServer, async (t, server, got) => {
61+
server.post('/', cacheEndpoint);
62+
63+
const cache = new Map();
64+
65+
// POST requests with streams are not cached
66+
const body1 = ReadableStream.from(Buffer.from([1, 2, 3]));
67+
const body2 = ReadableStream.from(Buffer.from([1, 2, 3]));
68+
69+
const firstResponseInt = Number((await got({method: 'POST', body: body1, cache})).body);
70+
const secondResponseInt = Number((await got({method: 'POST', body: body2, cache})).body);
71+
72+
t.is(cache.size, 0);
73+
t.true(firstResponseInt < secondResponseInt);
74+
});
75+
4776
test('cached response is re-encoded to current encoding option', withServer, async (t, server, got) => {
4877
server.get('/', cacheEndpoint);
4978

0 commit comments

Comments
 (0)