All files / src/presentation/stores altcha.store.ts

76.19% Statements 16/21
76.92% Branches 10/13
100% Functions 3/3
75% Lines 15/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    8x 8x                             8x         2x 2x                   2x 1x       2x         2x           2x 2x 1x 1x 1x   1x    
import { create } from 'zustand';
 
const ALTCHA_ENABLED = import.meta.env.VITE_ALTCHA_ENABLED === 'true';
const ALTCHA_TOKEN_EXPIRY_SECONDS = parseInt(import.meta.env.VITE_ALTCHA_TOKEN_EXPIRY_SECONDS);
 
type AltchaToken = {
  payload: string;
  expiresAt: number;
};
 
interface AltchaStore {
  token: AltchaToken | null;
  callback: ((payload: string) => void) | null;
  pending: boolean;
  setPayload: (payload: string) => void;
  setCallback: (callback: (() => void) | null) => void;
}
 
export const useAltchaStore = create<AltchaStore>((set, get) => ({
  token: ALTCHA_ENABLED ? null : {payload: '__altcha_disabled__', expiresAt: 0},
  pending: false,
  callback: null,
  setPayload: payload => {
    const { callback } = get();
    set(
      { 
        token:  {
          expiresAt: Date.now() + ALTCHA_TOKEN_EXPIRY_SECONDS * 1000,
          payload: payload
        },
        pending: false
      }
    );
 
    if (callback) {
      callback(payload);
    } 
  },
  setCallback: (callback: (() => void) | null) => {
    Iif (!callback) {
      set({ callback: null });
      return;
    }
 
    Iif(!ALTCHA_ENABLED) {
      set({ callback: null });
      callback();
      return;
    }
 
    const { token } = get();
    if (token && token.payload && Date.now() < token.expiresAt) {
      set({ callback: null });
      callback();
      return;
    }
    set({ token: null, callback, pending: true });
  }
}));