簡體   English   中英

我們如何使用工作箱 v6.5.1 匹配 registerRoute 中的“查詢”參數

[英]how can we match the 'Query' parameter in registerRoute using workbox v6.5.1

我正在使用工作箱 v6.5.1(帶有 React、Redux、Node)來緩存 API 請求,現在只想為特定請求添加或匹配“標頭查詢”參數。 這樣兩個不同的請求就可以通過“查詢”參數來區分。

例如,
我有一個 api 像 '/getListForCategory' 但兩個不同的請求有不同的 '查詢'。

/getListForCategory => query: {"categoryId":2001,"start":1,"end":5}  
/getListForCategory => query: {"categoryId":2002,"start":5,"end":10}

在 API 響應中這些 header 參數匹配有什么具體的方法嗎?

請回復,我被困在我當前的項目中。

registerRoute(
  ({url,request}) => url.origin === self.location.origin && request.method === 'GET',
  new StaleWhileRevalidate({
    cacheName: 'apis',
    plugins: [
      new CacheableResponsePlugin({
        statuses: [0, 200]
      }),
      new ExpirationPlugin({
        maxAgeSeconds: 7 * 24 * 60 * 60, // for a week
        purgeOnQuotaError: true
      })
    ]
  })
)

當然可以——您可以在registerRoute()中使用的matchCallback中實現任何您喜歡的邏輯。 一個要求是執行需要同步(即它不能依賴Promise的結果)。

認為這段代碼完成了你所描述的; 如果與您的實際用例存在一些差異,它至少應該為您指明正確的方向。

const queryParamMatcher = ({sameOrigin, url}) => {
  if (!sameOrigin) {
    return false;
  }

  const queryJSON = url.searchParams.get('query');
  if (!queryJSON) {
    return false;
  }

  try {
    const query = JSON.parse(queryJSON);
    // Replace with the check you want to match the route.
    return query.categoryId === 2001;
  } catch (error) {
    // If there is bad JSON, don't match the route.
    return false;
  }
};

registerRoute(
  queryParamMatcher,
  new StaleWhileRevalidate({...}),
  'GET', // 'GET' is the default, and can be omitted.
);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM