import React, { useState } from "react"; import { useRouter } from "next/router"; import { mutate } from "swr"; import { Dialog, Transition } from "@headlessui/react"; // services import { APITokenService } from "services/api_token.service"; // hooks import useToast from "hooks/use-toast"; // components import { CreateApiTokenForm, GeneratedTokenDetails } from "components/api-token"; // helpers import { csvDownload } from "helpers/download.helper"; import { renderFormattedDate } from "helpers/date-time.helper"; // types import { IApiToken } from "@plane/types"; // fetch-keys import { API_TOKENS_LIST } from "constants/fetch-keys"; type Props = { isOpen: boolean; onClose: () => void; }; // services const apiTokenService = new APITokenService(); export const CreateApiTokenModal: React.FC = (props) => { const { isOpen, onClose } = props; // states const [neverExpires, setNeverExpires] = useState(false); const [generatedToken, setGeneratedToken] = useState(null); // router const router = useRouter(); const { workspaceSlug } = router.query; // toast alert const { setToastAlert } = useToast(); const handleClose = () => { onClose(); setTimeout(() => { setNeverExpires(false); setGeneratedToken(null); }, 350); }; const downloadSecretKey = (data: IApiToken) => { const csvData = { Title: data.label, Description: data.description, Expiry: data.expired_at ? renderFormattedDate(data.expired_at)?.replace(",", " ") ?? "" : "Never expires", "Secret key": data.token ?? "", }; csvDownload(csvData, `secret-key-${Date.now()}`); }; const handleCreateToken = async (data: Partial) => { if (!workspaceSlug) return; // make the request to generate the token await apiTokenService .createApiToken(workspaceSlug.toString(), data) .then((res) => { setGeneratedToken(res); downloadSecretKey(res); mutate( API_TOKENS_LIST(workspaceSlug.toString()), (prevData) => { if (!prevData) return; return [res, ...prevData]; }, false ); }) .catch((err) => { setToastAlert({ message: err.message, type: "error", title: "Error", }); throw err; }); }; return ( {}}>
{generatedToken ? ( ) : ( setNeverExpires((prevData) => !prevData)} onSubmit={handleCreateToken} /> )}
); };