Spaces:
Running
on
CPU Upgrade
Running
on
CPU Upgrade
File size: 3,027 Bytes
ca0baae |
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 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 |
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>
);
};
|