Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: pass request body to cache handler #2150

Merged
merged 4 commits into from
Sep 27, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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