工作箱 - 使用自定义处理程序

Workbox - using a custom handler

我想要一个数组来配置部分路径(当响应与请求匹配时缓存响应 URL)和过期(在 X 秒后使缓存过期)但我可以'使 'handler' 正常工作。

这是配置路径和过期时间的数组:

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

这是调用cachePath匹配和pathHandler处理的缓存方法:

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

匹配方法:

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

    return match || false;
}

和处理程序方法:

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,
            }),
        ],
    });
}

好吧,pathHandler 不起作用,几次尝试让我感到沮丧......在我需要 return new Response(something) 的地方抛出错误(用 urlevent), 不正确的获取请求和不正确的对象响应。

那么,我如何构建 pathHandler 方法来将响应缓存 X 秒并仍然获得正确的响应?

提前致谢!

您有点误用了 API。

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

遗憾的是,这里的文档对此并不清楚:https://developers.google.com/web/tools/workbox/reference-docs/latest/workbox.strategies

此处列出了您要执行的操作: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});
})