Reputation: 177
I am using workbox routing for dynamic caching. I don't want to give fix url as it will change based on user interaction. how can i achieve this? I am using this like below but it is fixed with one state
let BASE_URL = location.protocol + "//" + location.host,
API_URL = BASE_URL + '/ab/abc/api/'
I want to cache all url which has /ab/abc/api/
workbox.routing.registerRoute(API_URL, workbox.strategies.networkFirst({
cacheName: 'abc',
plugins: [
new workbox.expiration.Plugin({
maxEntries: 1
}),
new workbox.cacheableResponse.Plugin({
statuses: [200]
})
]
}));
Upvotes: 3
Views: 1709
Reputation: 56044
There's some more background on how Workbox's routing works available in the documentation.
To answer your specific question, though, you can create a route that matches based on a regular expression, and that regular expression only needs to match a portion of the incoming URL (like, matching a common prefix or suffix).
Assuming your common prefix is /ab/abc/api/
and that your actual API calls are for URLs that exist under that path (e.g. /ab/abc/api/entries
, /ab/abc/api/latest?t=1
, etc.), you could create a route like:
workbox.routing.registerRoute(
new RegExp('/ab/abc/api'),
workbox.strategies.networkFirst({
cacheName: 'abc',
plugins: [
new workbox.expiration.Plugin({
maxEntries: 50
})
]
}));
The one other thing that I changed there is the maxEntries
for your cache expiration. Each unique URL that matches the RegExp
will get its own cache entry, and if you set maxEntries
to 1, then you'll only end up caching the very last URL used, with all the other entries expired after each time. I'm assuming that setting it to something higher (I used 50, but whatever makes sense for you) is more in keeping with what you intend.
Upvotes: 5