Search code examples
javascriptworkbox

Workbox - using a custom handler


I'd like to have an array to configure part of the path (to cache the response when it matches a requested URL) and the expiration (to expire the cache after X seconds) but I can't make the 'handler' to work properly.

This is the array to config the path and expiration:

const PATHS_TO_CACHE = [
    { url: 'api/v1/destination', expiration: THIRTY_DAYS },
    { url: 'api/v1/hotel', expiration: THIRTY_MINUTES },
];

This is the method to cache that calls cachePath to match and pathHandler to handle:

function cachePaths() {
    workbox.routing.registerRoute(cachePath, pathHandler);
}

The match method:

function cachePath({ url, event }) {
    const match = PATHS_TO_CACHE.find(function(path) {
        return url.href.includes(path.url);
    });

    return match || false;
}

And the handler method:

function pathHandler({ url, event, params }) {
    return workbox.strategies.staleWhileRevalidate({
        cacheName: 'url-cache',
        plugins: [
            new workbox.cacheableResponse.Plugin({
                statuses: [0, 200],
            }),
            new workbox.expiration.Plugin({
                maxAgeSeconds: params.expiration,
            }),
        ],
    });
}

Well, the pathHandler is not working and several tries led me to frustration... throwing errors where I need a return new Response(something) (did that with url and event), incorrect get requests and incorrect object responses.

So, how may I build the pathHandler method to cache the response for X seconds and still get the correct response?

Thanks in advance!


Solution

  • You are slightly mis-using the API.

    workbox.strategies.staleWhileRevalidate({...}) <- Returns a Route

    Sadly the docs here aren't clear about this: https://developers.google.com/web/tools/workbox/reference-docs/latest/workbox.strategies

    What you want to do is outlined here: https://developers.google.com/web/tools/workbox/modules/workbox-strategies#advanced_usage

    function pathHandler({ url, event, params }) {
        const staleWhileRevalidate = new workbox.strategies.StaleWhileRevalidate({
            plugins:[...],
        });
        return staleWhileRevalidate.handle({event});
    })