Пользовательские плагины в Google Workbox - PullRequest
0 голосов
/ 21 апреля 2020

Я довольно новичок в Google Workbox и пытаюсь добавить пользовательский плагин. (Руководство по работе с Google: Использование плагинов )

Я зарегистрировал маршруты - пример:

/**
 * Caching routes .de .com .test and .html
 */
workbox.routing.registerRoute(
    new RegExp('\\.(?:html|de/|com/|test/)$'),
    new workbox.strategies.StaleWhileRevalidate({
        // Use a custom cache name.
        cacheName: 'html-cache',
        plugins: [
            ... <- here should be my plugin
            new workbox.expiration.ExpirationPlugin({
                // Cache for a maximum of 3 days.
                maxAgeSeconds: 3 * 24 * 60 * 60,
            }),
        ],
    })
);

и пример файла плагина от Google:

const myPlugin = {
  cacheWillUpdate: async ({request, response, event}) => {
    // Return `response`, a different `Response` object, or `null`.
    return response;
  },
  cacheDidUpdate: async ({cacheName, request, oldResponse, newResponse, event}) => {
    // No return expected
    // Note: `newResponse.bodyUsed` is `true` when this is called,
    // meaning the body has already been read. If you need access to
    // the body of the fresh response, use a technique like:
    // const freshResponse = await caches.match(request, {cacheName});
  },
  cacheKeyWillBeUsed: async ({request, mode}) => {
    // `request` is the `Request` object that would otherwise be used as the cache key.
    // `mode` is either 'read' or 'write'.
    // Return either a string, or a `Request` whose `url` property will be used as the cache key.
    // Returning the original `request` will make this a no-op.
    return request;
  },
  cachedResponseWillBeUsed: async ({cacheName, request, matchOptions, cachedResponse, event}) => {
    // Return `cachedResponse`, a different `Response` object, or null.
    return cachedResponse;
  },
  requestWillFetch: async ({request}) => {
    // Return `request` or a different `Request` object.
    return request;
  },
  fetchDidFail: async ({originalRequest, request, error, event}) => {
    // No return expected.
    // NOTE: `originalRequest` is the browser's request, `request` is the
    // request after being passed through plugins with
    // `requestWillFetch` callbacks, and `error` is the exception that caused
    // the underlying `fetch()` to fail.
  },
  fetchDidSucceed: async ({request, response}) => {
    // Return `response` to use the network response as-is,
    // or alternatively create and return a new `Response` object.
    return response;
  }
};

Моя проблема в том, что я не могу добавить это в раздел плагинов. Я попробовал несколько обозначений, и ничего не работает.

Что бы я хотел сделать?
Я хочу сравнить старое содержимое из кэша с более новым ответом. (Я знаю, что есть класс, который может сделать это -> BroadcastCacheUpdate). Но это также не работает для меня. Если у кого-то есть примеры конфигурации (для версии 5), я был бы признателен.

Надеюсь, вы, ребята, сможете мне помочь.

Привет, Саймон

1 Ответ

0 голосов
/ 21 апреля 2020

Я вполне уверен, что вы делаете правильные шаги, поэтому я не уверен, что не работает. Но в основном, только с соответствующими битами, это должно выглядеть следующим образом:

const customPlugin = {
  cacheDidUpdate: async (args) => {
    console.debug('cacheDidUpdate called with', args);
    // Do something with args.oldResponse and args.newResponse
  },
};

workbox.routing.registerRoute(
  new RegExp('\\.(?:html|de/|com/|test/)$'),
  new workbox.strategies.StaleWhileRevalidate({
    cacheName: 'html-cache',
    plugins: [
      customPlugin,
    ],
  })
);

Предполагая, что это работает для вас, и вы видите зарегистрированное сообщение, которое должно помочь вам выбрать правильный путь.

...