import { useState } from "react"; import { useCopyToClipboard } from "react-use"; import classNames from "classnames"; import Highlight from "react-highlight"; import { Options } from "redaxios"; import { BiSolidCopy, BiLogoJavascript, BiLogoPython, BiCodeCurly, } from "react-icons/bi"; import { ApiRoute } from "@/utils/type"; const LANGUAGES = [ { value: "curl", icon: , }, { value: "javascript", icon: , }, { value: "python", icon: , }, ]; export const Snippet = ({ endpoint, parameters, body, }: { endpoint: ApiRoute; parameters?: Record; body?: Options | undefined; }) => { const [_, copyToClipboard] = useCopyToClipboard(); const [isCopied, setIsCopied] = useState(false); const generateRequestFromEndpoint = (language: string) => { const { method, path } = endpoint; const needBody = ["post", "put", "patch", "delete"].includes( method.toLocaleLowerCase() ); if (language === "curl") { if (needBody && body) { return ( `curl -X ${method.toLocaleUpperCase()} ${path} \\` + "\n" + ` -H "Content-Type: application/json" \\` + "\n" + ` -d '${JSON.stringify(body, null, 2)}'` ); } if (parameters) { return ( `curl -X ${method.toLocaleUpperCase()} ${path}?` + Object.entries(parameters) .map(([key, value]) => `${key}=${value}`) .join("&") ); } return `curl -X ${method.toLocaleUpperCase()} ${path}`; } if (language === "javascript") { if (needBody && body) { return `const response = await fetch("${path}", { method: "${method.toLocaleUpperCase()}", headers: { "Content-Type": "application/json", }, body: JSON.stringify(${JSON.stringify(body, null, 2)}), });`; } if (parameters) { return `const response = await fetch("${path}?${Object.entries( parameters ) .map(([key, value]) => `${key}=${value}`) .join("&")}", { method: "${method.toLocaleUpperCase()}", });`; } } if (language === "python") { if (needBody && body) { return `import requests response = requests.${method.toLocaleLowerCase()}("${path}", json=${JSON.stringify( body, null, 2 )})`; } if (parameters) { return `import requests response = requests.${method.toLocaleLowerCase()}("${path}", params={ ${Object.entries(parameters) .map(([key, value]) => `${key}: ${value}`) .join(",\n ")} })`; } } return ""; }; const handleCopyToClipboard = (language: string) => { copyToClipboard(generateRequestFromEndpoint(language)); setIsCopied(true); setTimeout(() => { setIsCopied(false); }, 2000); }; return ( {LANGUAGES.map((lang, key) => ( {lang.icon} {lang.value} {generateRequestFromEndpoint(lang.value)} handleCopyToClipboard(lang.value)} > Copied! ))} ); };
{lang.value}