All files / app/features/donations useDonationAmounts.ts

100% Statements 15/15
100% Branches 11/11
100% Functions 5/5
100% Lines 15/15

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  2x         2x 2x 2x     44x         256x         44x 44x 44x   44x 12x 1x             44x     22x 22x          
import { JSONValue } from "@growthbook/growthbook";
import { useFeatureValue } from "@growthbook/growthbook-react";
import {
  DONATIONS_BOX_DEFAULT_VALUE_INDEX,
  DONATIONS_BOX_VALUES,
  DONATIONS_BOX_YEARLY_VALUES,
} from "features/donations/constants";
import Sentry from "platform/sentry";
import { useEffect } from "react";
 
function isValidAmounts(flag: JSONValue): flag is number[] {
  return (
    Array.isArray(flag) &&
    flag.length > DONATIONS_BOX_DEFAULT_VALUE_INDEX &&
    new Set(flag).size === flag.length &&
    // the backend rejects donations under $2
    flag.every((value) => typeof value === "number" && Number.isInteger(value) && value >= 2)
  );
}
 
function useAmountsFlag(key: string, fallback: number[]) {
  const flag = useFeatureValue<JSONValue>(key, fallback);
  const valid = isValidAmounts(flag);
  const flagJson = JSON.stringify(flag);
 
  useEffect(() => {
    if (!valid) {
      Sentry.captureException(new Error(`${key} is not a valid list of donation amounts`), {
        tags: { component: "DonationsBox" },
        extra: { flag: flagJson },
      });
    }
  }, [key, valid, flagJson]);
 
  return valid ? flag : fallback;
}
 
export default function useDonationAmounts() {
  return {
    monthly: useAmountsFlag("donation_amounts", DONATIONS_BOX_VALUES),
    yearly: useAmountsFlag("donation_amounts_yearly", DONATIONS_BOX_YEARLY_VALUES),
  };
}