import { ApiRoute } from "@/utils/type"; import classNames from "classnames"; import { useState } from "react"; import Highlight from "react-highlight"; import { BiCodeCurly, BiSolidCopy } from "react-icons/bi"; import { Options } from "redaxios"; export const CurlSnippet = ({ endpoint, headers, parameters, body, onCopyToClipboard, }: { endpoint: ApiRoute; parameters?: Record; headers?: Record; body?: Options | undefined; onCopyToClipboard: (e: string) => void; }) => { const [isCopied, setIsCopied] = useState(false); const generateCurlRequestFromEndpoint = () => { const { method, path } = endpoint; const fullpath = `${process.env.NEXT_PUBLIC_APP_APIURL}${path}`; const removeEmptyValues = (data: Record) => { const formattedData = { ...data }; Object.entries(formattedData).forEach(([key, value]) => { if (!value) { delete formattedData[key]; } }); return formattedData; }; const formatHeaders = () => { return headers ? Object.entries(headers) .map(([key, value]) => `-H "${key}: ${value}"`) .join(" \\\n ") : ""; }; const Dict: Record = { GET: () => { const filteredEmptyParameters = removeEmptyValues(parameters ?? {}); const headerString = formatHeaders(); return `curl -X ${method} "${fullpath}?${new URLSearchParams( filteredEmptyParameters ).toString()}" \\ ${headerString} `; }, DELETE: () => { const headerString = formatHeaders(); return `curl -X ${method} "${fullpath}" \\ ${headerString} \\ -d ${JSON.stringify(body)} `; }, DEFAULT: () => { const headerString = formatHeaders(); return `curl -X ${method} "${fullpath}" \\ ${headerString} \\ -d ${JSON.stringify(body)} `; }, }; return Dict[method] ? Dict[method]() : Dict["DEFAULT"](); }; const handleCopy = () => { onCopyToClipboard(generateCurlRequestFromEndpoint()); setIsCopied(true); setTimeout(() => { setIsCopied(false); }, 1000); }; return (

Curl

{generateCurlRequestFromEndpoint()}
Copied!
); };