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

I am using workbox v6.5.1 (with React, Redux, Node) to cache APIs requests and now just want to add or match 'header query' parameter for specific request. so that two different request differentiate with 'Query' parameter.

for example,
I have one api like '/getListForCategory' but two different request has different 'query'.

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

Is there any specific way to these header parameter match in API response?

Please respond, I am stuck in my current project.

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


Solution 1:[1]

Absolutely—you can implement any logic you'd like inside of the matchCallback used in registerRoute(). The one requirement is that the execution needs to be synchronous (i.e. it can't rely on the result of a Promise).

I think this code accomplishes what you describe; if there are some discrepancies with your actual use case, it should at least point you in the right direction.

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.
);

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Jeff Posnick