All files / src/services/api GlobalGroupIdempotencyKey.tsx

96.29% Statements 26/27
70% Branches 7/10
100% Functions 7/7
100% Lines 24/24

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    533x     533x   533x 52x 52x     533x 111x 111x       533x     533x   7456x     533x 146967x 146967x     533x 52x 52x   52x 52x   52x 52x       533x 59x 59x    
import { v4 as uuidv4 } from "uuid";
 
const METHODS_REQUIRING_KEY = ["POST", "PATCH", "PUT"] as const;
type Method = (typeof METHODS_REQUIRING_KEY)[number];
 
const IDEM_KEY = "give_idem_key:";
 
const safeSet = (k: string, v: string) => {
  try {
    sessionStorage.setItem(k, v);
  } catch {}
};
const safeRemove = (k: string) => {
  try {
    sessionStorage.removeItem(k);
  } catch {}
};
 
const uuid = () => (typeof crypto !== "undefined" && crypto.randomUUID ? crypto.randomUUID() : uuidv4());
 
// single global key (per tab)
let currentGlobalKey: string | null = null;
 
export const getGlobalGroupKey = (): string | undefined => currentGlobalKey ?? undefined;
 
// only POST and PUT
export const shouldInjectWriteMethod = (method?: string): method is Method => {
  Iif (!method) return false as any;
  return METHODS_REQUIRING_KEY.includes(method.toUpperCase() as Method);
};
 
export const createFreshGlobalKey = (persist: boolean) => {
  currentGlobalKey = null;
  safeRemove(IDEM_KEY);
 
  const newKey = uuid();
  currentGlobalKey = newKey;
 
  Eif (persist) {
    safeSet(IDEM_KEY, newKey);
  }
};
 
export const clearGlobalKey = () => {
  currentGlobalKey = null;
  safeRemove(IDEM_KEY);
};