Skip to content

Commit

Permalink
Fix request body not being properly cached (#2150)
Browse files Browse the repository at this point in the history
  • Loading branch information
AlCalzone authored Sep 27, 2022
1 parent 6c7ebab commit 3e9d3af
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 0 deletions.
1 change: 1 addition & 0 deletions source/core/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1110,6 +1110,7 @@ export default class Request extends Duplex implements RequestEvents<Request> {
if (options.cache) {
(this._requestOptions as any)._request = request;
(this._requestOptions as any).cache = options.cache;
(this._requestOptions as any).body = options.body;
this._prepareCache(options.cache as StorageAdapter);
}

Expand Down
29 changes: 29 additions & 0 deletions test/cache.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import {Buffer} from 'buffer';
import {promisify} from 'util';
import {Readable as ReadableStream} from 'stream';
import {Agent} from 'http';
import {gzip} from 'zlib';
import test from 'ava';
Expand Down Expand Up @@ -44,6 +45,34 @@ test('cacheable responses are cached', withServer, async (t, server, got) => {
t.is(firstResponse.body, secondResponse.body);
});

test('cacheable responses to POST requests are cached', withServer, async (t, server, got) => {
server.post('/', cacheEndpoint);

const cache = new Map();

const firstResponse = await got({method: 'POST', body: 'test', cache});
const secondResponse = await got({method: 'POST', body: 'test', cache});

t.is(cache.size, 1);
t.is(firstResponse.body, secondResponse.body);
});

test('non-cacheable responses to POST requests are not cached', withServer, async (t, server, got) => {
server.post('/', cacheEndpoint);

const cache = new Map();

// POST requests with streams are not cached
const body1 = ReadableStream.from(Buffer.from([1, 2, 3]));
const body2 = ReadableStream.from(Buffer.from([1, 2, 3]));

const firstResponseInt = Number((await got({method: 'POST', body: body1, cache})).body);
const secondResponseInt = Number((await got({method: 'POST', body: body2, cache})).body);

t.is(cache.size, 0);
t.true(firstResponseInt < secondResponseInt);
});

test('cached response is re-encoded to current encoding option', withServer, async (t, server, got) => {
server.get('/', cacheEndpoint);

Expand Down

0 comments on commit 3e9d3af

Please sign in to comment.