From 8793716bb54cce4bfaeb3370fa456bac672303cd Mon Sep 17 00:00:00 2001 From: Jeff Posnick Date: Fri, 22 Nov 2019 11:57:42 -0500 Subject: [PATCH] Await an async cacheWillUpdate --- .../src/PrecacheController.ts | 2 +- .../sw/test-PrecacheController.mjs | 30 +++++++++++++++++++ 2 files changed, 31 insertions(+), 1 deletion(-) diff --git a/packages/workbox-precaching/src/PrecacheController.ts b/packages/workbox-precaching/src/PrecacheController.ts index f46d80b56..4969a0b26 100644 --- a/packages/workbox-precaching/src/PrecacheController.ts +++ b/packages/workbox-precaching/src/PrecacheController.ts @@ -262,7 +262,7 @@ class PrecacheController { // Use a callback if provided. It returns a truthy value if valid. // NOTE: invoke the method on the plugin instance so the `this` context // is correct. - cacheWillUpdatePlugin.cacheWillUpdate!({event, request, response}) : + await cacheWillUpdatePlugin.cacheWillUpdate!({event, request, response}) : // Otherwise, default to considering any response status under 400 valid. // This includes, by default, considering opaque responses valid. response.status < 400; diff --git a/test/workbox-precaching/sw/test-PrecacheController.mjs b/test/workbox-precaching/sw/test-PrecacheController.mjs index c68024518..283c09a86 100644 --- a/test/workbox-precaching/sw/test-PrecacheController.mjs +++ b/test/workbox-precaching/sw/test-PrecacheController.mjs @@ -656,6 +656,36 @@ describe(`PrecacheController`, function() { // This should succeed. await precacheController.install({plugins}); }); + + it(`should properly await an async cacheWillUpdate plugin`, async function() { + sandbox.stub(fetchWrapper, 'fetch').resolves(new Response('', { + status: 203, + })); + + const precacheController = new PrecacheController(); + const cacheList = [ + '/will-be-error.html', + ]; + precacheController.addToCacheList(cacheList); + + const plugins = [{ + cacheWillUpdate: async ({request, response}) => { + expect(request).to.exist; + + if (response.status === 203) { + return null; + } + return response; + }, + }]; + + // Assuming the async plugin function is properly await-ed, an error + // will be thrown. + return expectError( + () => precacheController.install({plugins}), + 'bad-precaching-response' + ); + }); }); describe(`activate()`, function() {