Skip to content

Commit

Permalink
Warn when an async matchCallback is used (#2591)
Browse files Browse the repository at this point in the history
  • Loading branch information
jeffposnick committed Oct 7, 2020
1 parent a6751b9 commit ae29e17
Show file tree
Hide file tree
Showing 2 changed files with 34 additions and 0 deletions.
11 changes: 11 additions & 0 deletions packages/workbox-routing/src/Router.ts
Expand Up @@ -283,6 +283,17 @@ class Router {
let params;
const matchResult = route.match({url, sameOrigin, request, event});
if (matchResult) {
if (process.env.NODE_ENV !== 'production') {
// Warn developers that using an async matchCallback is almost always
// not the right thing to do.
if (matchResult instanceof Promise) {
logger.warn(`While routing ${getFriendlyURL(url)}, an async ` +
`matchCallback function was used. Please convert the ` +
`following route to use a synchronous matchCallback function:`,
route);
}
}

// See https://github.com/GoogleChrome/workbox/issues/2079
params = matchResult;
if (Array.isArray(matchResult) && matchResult.length === 0) {
Expand Down
23 changes: 23 additions & 0 deletions test/workbox-routing/sw/test-Router.mjs
Expand Up @@ -8,6 +8,8 @@

import {Route} from 'workbox-routing/Route.mjs';
import {Router} from 'workbox-routing/Router.mjs';
import {logger} from 'workbox-core/_private/logger.mjs';

import {dispatchAndWaitUntilDone} from '../../../infra/testing/helpers/extendable-event-utils.mjs';
import generateTestVariants from '../../../infra/testing/generate-variant-tests';

Expand Down Expand Up @@ -650,6 +652,27 @@ describe(`Router`, function() {
});

describe(`findMatchingRoute()`, function() {
it(`should log a warning in development when an async matchCallback is used`, function() {
if (process.env.NODE_ENV === 'production') return this.skip();

const loggerStub = sandbox.stub(logger, 'warn');

const router = new Router();
const route = new Route(async () => true, () => new Response());
router.registerRoute(route);

const url = new URL(location.href);
const request = new Request(url);
const event = new FetchEvent('fetch', {request});
const sameOrigin = true;

router.findMatchingRoute({url, sameOrigin, request, event});

expect(loggerStub.calledOnce).to.be.true;
// Just check for a snippet of the warning message.
expect(loggerStub.firstCall.args[0]).to.include('async');
});

it(`should return the first matching route`, function() {
const router = new Router();

Expand Down

0 comments on commit ae29e17

Please sign in to comment.