Route.ts 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. /*
  2. Copyright 2018 Google LLC
  3. Use of this source code is governed by an MIT-style
  4. license that can be found in the LICENSE file or at
  5. https://opensource.org/licenses/MIT.
  6. */
  7. import {assert} from 'workbox-core/_private/assert.js';
  8. import {HTTPMethod, defaultMethod, validMethods} from './utils/constants.js';
  9. import {normalizeHandler} from './utils/normalizeHandler.js';
  10. import {Handler, HandlerObject, MatchCallback} from './_types.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 module:workbox-routing
  20. */
  21. class Route {
  22. handler: HandlerObject;
  23. match: MatchCallback;
  24. method: HTTPMethod;
  25. /**
  26. * Constructor for Route class.
  27. *
  28. * @param {module:workbox-routing~matchCallback} match
  29. * A callback function that determines whether the route matches a given
  30. * `fetch` event by returning a non-falsy value.
  31. * @param {module:workbox-routing~handlerCallback} handler A callback
  32. * function that returns a Promise resolving to a Response.
  33. * @param {string} [method='GET'] The HTTP method to match the Route
  34. * against.
  35. */
  36. constructor(
  37. match: MatchCallback,
  38. handler: Handler,
  39. method: HTTPMethod = defaultMethod) {
  40. if (process.env.NODE_ENV !== 'production') {
  41. assert!.isType(match, 'function', {
  42. moduleName: 'workbox-routing',
  43. className: 'Route',
  44. funcName: 'constructor',
  45. paramName: 'match',
  46. });
  47. if (method) {
  48. assert!.isOneOf(method, validMethods, {paramName: 'method'});
  49. }
  50. }
  51. // These values are referenced directly by Router so cannot be
  52. // altered by minificaton.
  53. this.handler = normalizeHandler(handler);
  54. this.match = match;
  55. this.method = method;
  56. }
  57. }
  58. export {Route};