Skip to content

Commit

Permalink
Allow cacheKeyWillBeUsed to influence the request method check (#2616)
Browse files Browse the repository at this point in the history
* Fixes #2615 by allowing developers to cache post requests by returning a get request cache key from cacheKeyWillBeUsed.

* Validate effectiveRequest instead of the original request.
  • Loading branch information
markbrocato committed Aug 28, 2020
1 parent c1610d0 commit 6d38919
Show file tree
Hide file tree
Showing 2 changed files with 67 additions and 10 deletions.
20 changes: 10 additions & 10 deletions packages/workbox-strategies/src/StrategyHandler.ts
Expand Up @@ -197,22 +197,22 @@ class StrategyHandler {
*/
async cachePut(key: RequestInfo, response: Response): Promise<void> {
const request: Request = toRequest(key);


// Run in the next task to avoid blocking other cache reads.
// https://github.com/w3c/ServiceWorker/issues/1397
await timeout(0);

const effectiveRequest = await this._getEffectiveRequest(request, 'write');

if (process.env.NODE_ENV !== 'production') {
if (request.method && request.method !== 'GET') {
if (effectiveRequest.method && effectiveRequest.method !== 'GET') {
throw new WorkboxError('attempt-to-cache-non-get-request', {
url: getFriendlyURL(request.url),
method: request.method,
url: getFriendlyURL(effectiveRequest.url),
method: effectiveRequest.method,
});
}
}

// Run in the next task to avoid blocking other cache reads.
// https://github.com/w3c/ServiceWorker/issues/1397
await timeout(0);

const effectiveRequest = await this._getEffectiveRequest(request, 'write');

if (!response) {
if (process.env.NODE_ENV !== 'production') {
logger.error(`Cannot cache non-existent response for ` +
Expand Down
57 changes: 57 additions & 0 deletions test/workbox-strategies/sw/test-StrategyHandler.mjs
Expand Up @@ -587,6 +587,63 @@ describe(`StrategyHandler`, function() {
expect(cachePutStub.args[0][1]).to.eql(response);
});

it(`should allow caching of posts if cacheKeyWillBeUsed returns a get request`, async function() {
const cacheName = 'cacheKeyWillBeUsed-test-cache';
const cache = await caches.open(cacheName);
sandbox.stub(caches, 'open').resolves(cache);
const cachePutStub = sandbox.stub(cache, 'put').resolves();

const firstPluginReturnValue = new Request('/firstPlugin', {
method: 'get',
});

const firstPlugin = {
cacheKeyWillBeUsed: () => firstPluginReturnValue,
};

const secondPlugin = {
// This string will be converted to a Request.
cacheKeyWillBeUsed: () => '/secondPlugin',
};

const spyOne = sandbox.spy(firstPlugin, 'cacheKeyWillBeUsed');
const spyTwo = sandbox.spy(secondPlugin, 'cacheKeyWillBeUsed');

const initialRequest = new Request('/noPlugin', {
method: 'post',
});

const response = new Response('Test response.');

const handler = createStrategyHandler({
cacheName,
plugins: [
firstPlugin,
{}, // Intentionally empty to ensure it's filtered out.
secondPlugin,
],
});

await handler.cachePut(initialRequest, response);

expect(spyOne.calledOnceWith(sinon.match({
mode: 'write',
request: initialRequest,
}))).to.be.true;
expect(spyOne.thisValues[0]).to.eql(firstPlugin);

expect(spyTwo.calledOnceWith(sinon.match({
mode: 'write',
request: firstPluginReturnValue,
}))).to.be.true;
expect(spyTwo.thisValues[0]).to.eql(secondPlugin);

expect(cachePutStub.calledOnce).to.be.true;
// Check the url of the Request passed to cache.put().
expect(cachePutStub.args[0][0].url).to.eql(`${self.location.origin}/secondPlugin`);
expect(cachePutStub.args[0][1]).to.eql(response);
});

it(`should call the quota exceeded callbacks when there's a QuotaExceeded error`, async function() {
const callback1 = sandbox.stub();
registerQuotaErrorCallback(callback1);
Expand Down

0 comments on commit 6d38919

Please sign in to comment.