Skip to content

Commit

Permalink
Add a cache listener message response (#1906)
Browse files Browse the repository at this point in the history
  • Loading branch information
philipwalton authored and jeffposnick committed Feb 19, 2019
1 parent 3033185 commit 8496e07
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 8 deletions.
17 changes: 11 additions & 6 deletions packages/workbox-routing/Router.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -74,7 +74,6 @@ class Router {
* ```
* {
* type: 'CACHE_URLS',
* meta: 'workbox-window',
* payload: {
* urlsToCache: [
* './script1.js',
Expand All @@ -86,21 +85,27 @@ class Router {
* ```
*/
addCacheListener() {
self.addEventListener('message', (event) => {
const {type, meta, payload} = event.data;
self.addEventListener('message', async (event) => {
const {type, payload} = event.data;

if (type === 'CACHE_URLS' && meta === 'workbox-window') {
if (type === 'CACHE_URLS') {
if (process.env.NODE_ENV !== 'production') {
logger.debug(`Caching URLs from the window`, payload.urlsToCache);
}

for (let entry of payload.urlsToCache) {
const requestPromises = payload.urlsToCache.map((entry) => {
if (typeof entry === 'string') {
entry = [entry];
}

const request = new Request(...entry);
this.handleRequest({request, event});
return this.handleRequest({request, event});
});

// If a MessageChannel was used, reply to the message on success.
if (event.ports) {
await requestPromises;
event.ports[0].postMessage(true);
}
}
});
Expand Down
5 changes: 3 additions & 2 deletions test/workbox-routing/node/test-Router.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -194,12 +194,13 @@ describe(`[workbox-routing] Router`, function() {
const event = new ExtendableMessageEvent('message', {
data: {
type: 'CACHE_URLS',
meta: 'workbox-window',
payload: {
urlsToCache: ['/one', '/two', '/three'],
},
},
});
event.ports = [{postMessage: sinon.spy()}];

sandbox.spy(router, 'handleRequest');
self.dispatchEvent(event);

Expand All @@ -212,6 +213,7 @@ describe(`[workbox-routing] Router`, function() {
expect(router.handleRequest.args[1][0].event).to.equal(event);
expect(router.handleRequest.args[2][0].request.url).to.equal('/three');
expect(router.handleRequest.args[2][0].event).to.equal(event);
expect(event.ports[0].postMessage.callCount).to.equal(1);
});

it(`should accept URL strings or request URL+requestInit tuples`, async function() {
Expand All @@ -225,7 +227,6 @@ describe(`[workbox-routing] Router`, function() {
const event = new ExtendableMessageEvent('message', {
data: {
type: 'CACHE_URLS',
meta: 'workbox-window',
payload: {
urlsToCache: [
'/one',
Expand Down

0 comments on commit 8496e07

Please sign in to comment.