| 1 | /*
|
|---|
| 2 | Copyright 2018 Google LLC
|
|---|
| 3 |
|
|---|
| 4 | Use of this source code is governed by an MIT-style
|
|---|
| 5 | license that can be found in the LICENSE file or at
|
|---|
| 6 | https://opensource.org/licenses/MIT.
|
|---|
| 7 | */
|
|---|
| 8 | import { assert } from 'workbox-core/_private/assert.js';
|
|---|
| 9 | import { defaultMethod, validMethods } from './utils/constants.js';
|
|---|
| 10 | import { normalizeHandler } from './utils/normalizeHandler.js';
|
|---|
| 11 | import './_version.js';
|
|---|
| 12 | /**
|
|---|
| 13 | * A `Route` consists of a pair of callback functions, "match" and "handler".
|
|---|
| 14 | * The "match" callback determine if a route should be used to "handle" a
|
|---|
| 15 | * request by returning a non-falsy value if it can. The "handler" callback
|
|---|
| 16 | * is called when there is a match and should return a Promise that resolves
|
|---|
| 17 | * to a `Response`.
|
|---|
| 18 | *
|
|---|
| 19 | * @memberof workbox-routing
|
|---|
| 20 | */
|
|---|
| 21 | class Route {
|
|---|
| 22 | /**
|
|---|
| 23 | * Constructor for Route class.
|
|---|
| 24 | *
|
|---|
| 25 | * @param {workbox-routing~matchCallback} match
|
|---|
| 26 | * A callback function that determines whether the route matches a given
|
|---|
| 27 | * `fetch` event by returning a non-falsy value.
|
|---|
| 28 | * @param {workbox-routing~handlerCallback} handler A callback
|
|---|
| 29 | * function that returns a Promise resolving to a Response.
|
|---|
| 30 | * @param {string} [method='GET'] The HTTP method to match the Route
|
|---|
| 31 | * against.
|
|---|
| 32 | */
|
|---|
| 33 | constructor(match, handler, method = defaultMethod) {
|
|---|
| 34 | if (process.env.NODE_ENV !== 'production') {
|
|---|
| 35 | assert.isType(match, 'function', {
|
|---|
| 36 | moduleName: 'workbox-routing',
|
|---|
| 37 | className: 'Route',
|
|---|
| 38 | funcName: 'constructor',
|
|---|
| 39 | paramName: 'match',
|
|---|
| 40 | });
|
|---|
| 41 | if (method) {
|
|---|
| 42 | assert.isOneOf(method, validMethods, { paramName: 'method' });
|
|---|
| 43 | }
|
|---|
| 44 | }
|
|---|
| 45 | // These values are referenced directly by Router so cannot be
|
|---|
| 46 | // altered by minificaton.
|
|---|
| 47 | this.handler = normalizeHandler(handler);
|
|---|
| 48 | this.match = match;
|
|---|
| 49 | this.method = method;
|
|---|
| 50 | }
|
|---|
| 51 | /**
|
|---|
| 52 | *
|
|---|
| 53 | * @param {workbox-routing-handlerCallback} handler A callback
|
|---|
| 54 | * function that returns a Promise resolving to a Response
|
|---|
| 55 | */
|
|---|
| 56 | setCatchHandler(handler) {
|
|---|
| 57 | this.catchHandler = normalizeHandler(handler);
|
|---|
| 58 | }
|
|---|
| 59 | }
|
|---|
| 60 | export { Route };
|
|---|