All files / src/features/MerchantPortal/DeveloperApi/hooks useMerchantsApiKeysActions.tsx

86.36% Statements 19/22
90% Branches 9/10
80% Functions 4/5
86.36% Lines 19/22

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 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84                        2x             2x                 10x 10x 10x   10x 2x 2x 2x       2x             10x 2x       2x 2x 1x           2x 2x             2x                 10x              
import { showMessage } from "@common/Toast";
import {
  QKEY_GET_API_KEY,
  QKEY_MERCHANTS_API_KEYS,
} from "@constants/queryKeys";
import NiceModal from "@ebay/nice-modal-react";
import { useGetCurrentMerchantId } from "@hooks/common";
import { customInstance } from "@services/api";
import { useState } from "react";
import { useMutation, useQueryClient } from "react-query";
import { MERCHANT_API_KEY_SUCCESS_MODAL } from "modals/modal_names";
 
const actionMapper: Record<string, string> = {
  roll: "rolled",
  delete: "deleted",
  activate: "active",
  revoke: "revoked",
};
 
export const useActions = ({
  keyId,
  onClose,
  successMessage,
}: {
  keyId: string;
  onClose: () => void;
  successMessage?: string;
}) => {
  const queryClient = useQueryClient();
  const { merchantId } = useGetCurrentMerchantId();
  const [nextActionIsClose, setNextActionIsClose] = useState<boolean>(false);
 
  const updateKey = useMutation((data: any) => {
    const isDelete = data?.status === "deleted";
    const method = isDelete ? "DELETE" : "PATCH";
    const url = `/merchants/${merchantId}/api-keys/${keyId}${
      isDelete ? "" : "/status"
    }`;
 
    return customInstance({
      url,
      method,
      data,
    });
  });
 
  const fireAction = (actionId: string) => {
    updateKey.mutate(
      { status: actionMapper[actionId] },
      {
        onSuccess: (res) => {
          queryClient.invalidateQueries([QKEY_MERCHANTS_API_KEYS]);
          if (actionId !== "delete") {
            queryClient.invalidateQueries([
              QKEY_GET_API_KEY,
              keyId,
              merchantId,
            ]);
          }
          onClose();
          Iif (actionId === "roll") {
            NiceModal.show(MERCHANT_API_KEY_SUCCESS_MODAL, {
              apiKey: res.apiKey,
            });
 
            setNextActionIsClose(true);
          }
          successMessage && showMessage("Success", successMessage);
        },
        onError: (e) => {
          showMessage("Error", (e as Error).message);
        },
      },
    );
  };
 
  return {
    fireAction,
    nextActionIsClose,
    isLoading: updateKey.isLoading,
    isSuccess: updateKey.isSuccess,
  };
};