workbox-routing. Route
A Route
allows you to tell a service worker that it should handle certain network requests using a specific response strategy.
A consists or a matcher and a handler. A matcher needs to determine if a route should be used for a request. A handler should handle the request if it does match a Router.
Instead of implementing your own handlers, you can use one of the pre-defined runtime caching strategies from the workbox-runtime-caching module.
There are also pre-defined Route's provided by this library:
RegExpRoute and ExpressRoute subclasses which provide a convenient wrapper with a nicer interface for using regular expressions
or Express-style routes as the match
criteria.
Constructor
Route
new Route(input)
Constructor for Route class.
Parameter |
|||||||||
---|---|---|---|---|---|---|---|---|---|
input |
Object Values in
|
Example
// Any navigate requests for URLs that start with /path/to/ will match.
const route = new workbox.routing.Route({
match: ({url, event}) => {
return event.request.mode === 'navigate' &&
url.pathname.startsWith('/path/to/');
},
handler: ({event}) => {
// Do something that returns a Promise.<Response>, like:
return caches.match(event.request);
},
});
const router = new workbox.routing.Router();
router.registerRoute({route});
Abstract types
handlerCallback
handlerCallback(input) returns Promise containing Response
This is the definition of the handler
callback that can be passed into the
Route
constructor.
The handler
callback is called when a request has been matched by a Route
and should return a Promise that resolves with a Response
.
Parameter |
|||||||||
---|---|---|---|---|---|---|---|---|---|
input |
Object Values in
|
- Returns
-
Promise containing Response
The response that will fulfill the request.
matchCallback
matchCallback(input) returns (Object or null)
This is the definition of the match
callback passed into the
Route
constructor.
This callback is used to determine if a new fetch
event can be served by this Route
. Returning a truthy value indicates that this Route
can handle this fetch
event. Return null
if this shouldn't match against the fetch
event.
If you do return a truthy value, the object will be passed to the Route's handler
(see the
Route Constructor).
Parameter |
|||||||
---|---|---|---|---|---|---|---|
input |
Object Values in
|
- Returns
-
(Object or null)
To signify a match, return a truthy value, otherwise return null if the route shouldn't match. If you return an Object with contents it will be passed to thehandler
in theRoute
constructor.