I have an public API endpoint like this:
https://data.weather.gov.hk/weatherAPI/opendata/weather.php?dataType=warnsum&lang=en
And I want to runtime cache its response with service worker. This is how I defined the route:
registerRoute(
new RegExp('.+/weatherAPI/opendata/weather.php?dataType=warnsum&lang=en'),
new StaleWhileRevalidate({
cacheName: 'weatherApi',
plugins: [
new ExpirationPlugin({
maxAgeSeconds: 60 * 60 * 24
}),
new BackgroundSyncPlugin('getWeatherAPI', {
maxRetentionTime: 24 * 60 // Retry for max of 24 Hours (specified in minutes)
})
]
})
)
However, this doesn't work and the response of this url was not saved into the cache. I wonder if query parameter would be the issue here, or if I have missed something?
The query parameters are included when performing a RegExpRoute
match in Workbox.
I think it's more likely that you need to escape the characters that are "special" in a regular expression, like ?
.
Using something other than a regular expression might actually be easier. You can use a matchCallback
, for instance, like:
registerRoute(
({url}) => url.href.endsWith('/weatherAPI/opendata/weather.php?dataType=warnsum&lang=en'),
new StaleWhileRevalidate({...}),
)