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

Cleaner way to create generic Route instances via registerRoute() #644

Merged
merged 2 commits into from
Jun 27, 2017
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
Original file line number Diff line number Diff line change
Expand Up @@ -280,7 +280,7 @@ class BaseCacheManager {
* @return {Promise} Returns a Promise that resolves once the work is done.
*/
_onEntryDeleted(url) {
throw ErrorFactory.createError('should-override');
throw new WorkboxError('requires-overriding');
}
}

Expand Down
4 changes: 2 additions & 2 deletions packages/workbox-sw/src/lib/error-factory.js
Original file line number Diff line number Diff line change
Expand Up @@ -17,8 +17,8 @@ import ErrorFactory from '../../../../lib/error-factory';

const errors = {
'not-in-sw': 'workbox-sw must be loaded in your service worker file.',
'unsupported-route-type': 'Routes must be either a express style route ' +
'string, a Regex to capture request URLs or a Route instance.',
'unsupported-route-type': 'The first parameter to registerRoute() should be' +
' either an Express-style path string, a RegExp, or a function.',
'empty-express-string': 'The Express style route string must have some ' +
'characters, an empty string is invalid.',
'bad-revisioned-cache-list': `The 'precache()' method expects` +
Expand Down
22 changes: 13 additions & 9 deletions packages/workbox-sw/src/lib/router.js
Original file line number Diff line number Diff line change
Expand Up @@ -70,22 +70,26 @@ class Router extends SWRoutingRouter {
}

/**
* @param {String|RegExp|Route} capture The capture for a route can be one
* of three types.
* 1. It can be an Express style route, like `'/path/to/:anything'` for
* @param {String|RegExp|module:workbox-routing.matchCallback} capture
* The capture for a route can be one of three types:
* 1. An Express-style route, like `'/path/to/:anything'` for
* same-origin or `'https://cross-origin.com/path/to/:anything'` for
* cross-origin routes.
* 1. A regular expression that will be tested against request URLs. For
* cross-origin routes, you must use a RegExp that matches the start of the
* full URL, like `new RegExp('https://cross-origin\.com/')`.
* 1. A [Route]{@link module:workbox-routing.Route} instance.
* 1. A [function]{@link module:workbox-routing.matchCallback} which is
* passed the URL and `FetchEvent`, and should returns a truthy value if
* the route matches.
* @param {function|module:workbox-runtime-caching.Handler} handler The
* handler to use to provide a response if the route matches. The handler
* argument is ignored if you pass in a Route object, otherwise it's required.
* @param {String} [method] Only match requests that use this HTTP method.
+ Defaults to `'GET'`.
* @return {module:workbox-routing.Route} The Route object that was
* registered.
*/
registerRoute(capture, handler) {
registerRoute(capture, handler, method = 'GET') {
if (typeof handler === 'function') {
handler = {
handle: handler,
Expand All @@ -97,11 +101,11 @@ class Router extends SWRoutingRouter {
if (capture.length === 0) {
throw ErrorFactory.createError('empty-express-string');
}
route = new ExpressRoute({path: capture, handler});
route = new ExpressRoute({path: capture, handler, method});
} else if (capture instanceof RegExp) {
route = new RegExpRoute({regExp: capture, handler});
} else if (capture instanceof Route) {
route = capture;
route = new RegExpRoute({regExp: capture, handler, method});
} else if (typeof capture === 'function') {
route = new Route({match: capture, handler, method});
} else {
throw ErrorFactory.createError('unsupported-route-type');
}
Expand Down
39 changes: 18 additions & 21 deletions packages/workbox-sw/src/lib/workbox-sw.js
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,6 @@ import logHelper from '../../../../lib/log-helper';
import {BroadcastCacheUpdatePlugin} from
'../../../workbox-broadcast-cache-update/src/index.js';
import {RevisionedCacheManager} from '../../../workbox-precaching/src/index.js';
import {Route} from '../../../workbox-routing/src/index.js';
import {
getDefaultCacheName} from '../../../workbox-runtime-caching/src/index.js';

Expand Down Expand Up @@ -303,29 +302,27 @@ class WorkboxSW {
plugins,
});

const route = new Route({
match: ({url}) => {
const cachedUrls = this._revisionedCacheManager.getCachedUrls();
if (cachedUrls.indexOf(url.href) !== -1) {
return true;
}
const capture = ({url}) => {
const cachedUrls = this._revisionedCacheManager.getCachedUrls();
if (cachedUrls.indexOf(url.href) !== -1) {
return true;
}

let strippedUrl =
this._removeIgnoreUrlParams(url.href, ignoreUrlParametersMatching);
if (cachedUrls.indexOf(strippedUrl.href) !== -1) {
return true;
}
let strippedUrl =
this._removeIgnoreUrlParams(url.href, ignoreUrlParametersMatching);
if (cachedUrls.indexOf(strippedUrl.href) !== -1) {
return true;
}

if (directoryIndex && strippedUrl.pathname.endsWith('/')) {
url.pathname += directoryIndex;
return cachedUrls.indexOf(url.href) !== -1;
}
if (directoryIndex && strippedUrl.pathname.endsWith('/')) {
url.pathname += directoryIndex;
return cachedUrls.indexOf(url.href) !== -1;
}

return false;
},
handler: cacheFirstHandler,
});
this.router.registerRoute(route);
return false;
};

this.router.registerRoute(capture, cacheFirstHandler);
}

/**
Expand Down
24 changes: 24 additions & 0 deletions packages/workbox-sw/test/sw/router.js
Original file line number Diff line number Diff line change
Expand Up @@ -119,4 +119,28 @@ describe('Test workboxSW.router', function() {
expect(thrownError).to.exist;
expect(thrownError.name).to.equal('navigation-route-url-string');
});

it(`should throw when the method passed in to registerRoute() isn't valid`, function() {
const workboxSW = new WorkboxSW();
try {
workboxSW.router.registerRoute(/123/, () => {}, 'INVALID_METHOD');
throw new Error();
} catch(error) {
expect(error.name).to.eql('assertion-failed',
`The expected assertion-failed error wasn't thrown.`);
}
});

it(`should use the valid method passed in to registerRoute()`, function() {
const workboxSW = new WorkboxSW();
const method = 'POST';
const route = workboxSW.router.registerRoute(/123/, () => {}, method);
expect(route.method).to.eql(method);
});

it(`should support calling registerRoute() with a function as the capture parameter`, function() {
const workboxSW = new WorkboxSW();
const route = workboxSW.router.registerRoute(() => {}, () => {});
expect(route).to.exist;
});
});