All files / src/hooks/acquirer-api/merchants/stats findLastQueryKey.ts

0% Statements 0/20
0% Branches 0/14
0% Functions 0/5
0% Lines 0/20

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62                                                                                                                           
import isEqual from "lodash/isEqual";
import { useQueryClient } from "react-query";
 
export const useFindLastQueryKeyWithPrefix = () => {
  const queryClient = useQueryClient();
  const findLastQueryKeyWithPrefix = (
    prefix: string | string[],
    {
      shouldCleanQueries = false,
    }: { shouldCleanQueries?: boolean; shouldRefetchPageOne?: boolean } = {},
  ) => {
    const prefixArray = Array.isArray(prefix) ? prefix : [prefix];
 
    const queries = queryClient.getQueryCache().getAll();
 
    const matchingPrefixedQueriesKeys = [];
 
    for (const query of queries) {
      const queryKey = query.queryKey;
 
      // get if the query starts with the prefix
      const isMatchingPrefix =
        queryKey.length >= prefixArray.length &&
        prefixArray.every(
          (prefixPart, index) => queryKey[index] === prefixPart,
        );
 
      if (isMatchingPrefix) {
        matchingPrefixedQueriesKeys.push({
          key: query.queryKey,
          lastAccessTime: query.state.dataUpdatedAt || 0,
        });
      }
    }
 
    // this is to not set cacheTime: 0 and still stack the cached query
    // cause queries that are cached are not getting stacked so the last query would've been the last non cached query
    // which might be different.
    const sortedMatchingQueries = matchingPrefixedQueriesKeys.sort(
      (a, b) => b.lastAccessTime - a.lastAccessTime,
    );
 
    // if i modify something in one page
    // the other pages should not care (i do not think we have cross pages interconnected values that require a refetch)
    if (shouldCleanQueries) {
      for (const queryInfo of sortedMatchingQueries.slice(1)) {
        queryClient.removeQueries({
          predicate: (query) => isEqual(query.queryKey, queryInfo.key),
        });
      }
    }
 
    return sortedMatchingQueries.length > 0
      ? sortedMatchingQueries[0].key
      : undefined;
  };
 
  return {
    findLastQueryKeyWithPrefix,
  };
};