Spaces:
Running
on
CPU Upgrade
Running
on
CPU Upgrade
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<string, any>; | |
headers?: Record<string, any>; | |
body?: Options | undefined; | |
onCopyToClipboard: (e: string) => void; | |
}) => { | |
const [isCopied, setIsCopied] = useState<boolean>(false); | |
const generateCurlRequestFromEndpoint = () => { | |
const { method, path } = endpoint; | |
const fullpath = `${process.env.NEXT_PUBLIC_APP_APIURL}${path}`; | |
const removeEmptyValues = (data: Record<string, any>) => { | |
const formattedData = { ...data }; | |
Object.entries(formattedData).forEach(([key, value]) => { | |
if (!value) { | |
delete formattedData[key]; | |
} | |
}); | |
return formattedData; | |
}; | |
const Dict: Record<string, any> = { | |
GET: () => { | |
const filteredEmptyParameters = removeEmptyValues(parameters ?? {}); | |
return `curl -X ${method} "${fullpath}?${new URLSearchParams( | |
filteredEmptyParameters | |
).toString()}" \\ | |
-H ${JSON.stringify(headers)} | |
`; | |
}, | |
DELETE: () => { | |
return `curl -X ${method} "${fullpath}" \\ | |
-H ${JSON.stringify(headers)} \\ | |
-d ${JSON.stringify(body)} | |
`; | |
}, | |
DEFAULT: () => { | |
return `curl -X ${method} "${fullpath}" \\ | |
-H ${JSON.stringify(headers)} | |
-d ${JSON.stringify(body)} | |
`; | |
}, | |
}; | |
return Dict[method] ? Dict[method]() : Dict["DEFAULT"](); | |
}; | |
const handleCopy = () => { | |
onCopyToClipboard(generateCurlRequestFromEndpoint()); | |
setIsCopied(true); | |
setTimeout(() => { | |
setIsCopied(false); | |
}, 1000); | |
}; | |
return ( | |
<div className="bg-slate-950/50 rounded-xl overflow-hidden"> | |
<header className="bg-slate-950 flex items-center justify-start px-5 py-4 uppercase gap-2 text-slate-300"> | |
<BiCodeCurly className="text-xl" /> | |
<p className="text-xs font-semibold">Curl</p> | |
</header> | |
<main className="px-6 py-6"> | |
<Highlight className="curl text-xs font-code !bg-transparent !p-0 !whitespace-pre-wrap break-all !leading-relaxed"> | |
{generateCurlRequestFromEndpoint()} | |
</Highlight> | |
<div className="flex justify-end relative" onClick={handleCopy}> | |
<BiSolidCopy className="text-slate-500 cursor-pointer hover:text-slate-300 transition-all duration-75" /> | |
<div | |
className={classNames( | |
"bg-indigo-500/60 text-slate-100 text-xs font-semibold absolute bottom-0 right-0 z-10 rounded-lg px-2 py-1 pointer-events-none -translate-y-full transition-all duration-200", | |
{ | |
"opacity-0": !isCopied, | |
} | |
)} | |
> | |
Copied! | |
</div> | |
</div> | |
</main> | |
</div> | |
); | |
}; | |