* Easily register a RegExp, string, or function with a caching * strategy to a singleton Router instance. * * This method will generate a Route for you if needed and * call workbox-routing.Router#registerRoute. * * @param {RegExp|string|workbox-routing.Route~matchCallback|workbox-routi
( capture: RegExp | string | RouteMatchCallback | Route, handler?: RouteHandler, method?: HTTPMethod, )
| 36 | * @memberof workbox-routing |
| 37 | */ |
| 38 | function registerRoute( |
| 39 | capture: RegExp | string | RouteMatchCallback | Route, |
| 40 | handler?: RouteHandler, |
| 41 | method?: HTTPMethod, |
| 42 | ): Route { |
| 43 | let route; |
| 44 | |
| 45 | if (typeof capture === 'string') { |
| 46 | const captureUrl = new URL(capture, location.href); |
| 47 | |
| 48 | if (process.env.NODE_ENV !== 'production') { |
| 49 | if (!(capture.startsWith('/') || capture.startsWith('http'))) { |
| 50 | throw new WorkboxError('invalid-string', { |
| 51 | moduleName: 'workbox-routing', |
| 52 | funcName: 'registerRoute', |
| 53 | paramName: 'capture', |
| 54 | }); |
| 55 | } |
| 56 | |
| 57 | // We want to check if Express-style wildcards are in the pathname only. |
| 58 | // TODO: Remove this log message in v4. |
| 59 | const valueToCheck = capture.startsWith('http') |
| 60 | ? captureUrl.pathname |
| 61 | : capture; |
| 62 | |
| 63 | // See https://github.com/pillarjs/path-to-regexp#parameters |
| 64 | const wildcards = '[*:?+]'; |
| 65 | if (new RegExp(`${wildcards}`).exec(valueToCheck)) { |
| 66 | logger.debug( |
| 67 | `The '$capture' parameter contains an Express-style wildcard ` + |
| 68 | `character (${wildcards}). Strings are now always interpreted as ` + |
| 69 | `exact matches; use a RegExp for partial or wildcard matches.`, |
| 70 | ); |
| 71 | } |
| 72 | } |
| 73 | |
| 74 | const matchCallback: RouteMatchCallback = ({url}) => { |
| 75 | if (process.env.NODE_ENV !== 'production') { |
| 76 | if ( |
| 77 | url.pathname === captureUrl.pathname && |
| 78 | url.origin !== captureUrl.origin |
| 79 | ) { |
| 80 | logger.debug( |
| 81 | `${capture} only partially matches the cross-origin URL ` + |
| 82 | `${url.toString()}. This route will only handle cross-origin requests ` + |
| 83 | `if they match the entire URL.`, |
| 84 | ); |
| 85 | } |
| 86 | } |
| 87 | |
| 88 | return url.href === captureUrl.href; |
| 89 | }; |
| 90 | |
| 91 | // If `capture` is a string then `handler` and `method` must be present. |
| 92 | route = new Route(matchCallback, handler!, method); |
| 93 | } else if (capture instanceof RegExp) { |
| 94 | // If `capture` is a `RegExp` then `handler` and `method` must be present. |
| 95 | route = new RegExpRoute(capture, handler!, method); |
no test coverage detected