import { cloneDeep, head } from "lodash-es"; import { useEffect, useState } from "react"; import { toast } from "react-hot-toast"; import { testConnection, useConnectionStore } from "@/store"; import { Connection, Engine } from "@/types"; import Icon from "./Icon"; interface Props { show: boolean; close: () => void; } const defaultConnection: Connection = { id: "", title: "", engineType: Engine.MySQL, host: "", port: "", username: "", password: "", }; const CreateConnectionModal = (props: Props) => { const { show, close } = props; const connectionStore = useConnectionStore(); const [connection, setConnection] = useState(defaultConnection); const [isRequesting, setIsRequesting] = useState(false); const showDatabaseField = connection.engineType === Engine.PostgreSQL; useEffect(() => { if (show) { setConnection(defaultConnection); } }, [show]); const setPartialConnection = (state: Partial) => { setConnection({ ...connection, ...state, }); }; const handleCreateConnection = async () => { if (isRequesting) { return; } setIsRequesting(true); const connectionCreate = cloneDeep(connection); if (!showDatabaseField) { connectionCreate.database = undefined; } const result = await testConnection(connectionCreate); setIsRequesting(false); if (!result) { toast.error("Failed to connect"); return; } const createdConnection = connectionStore.createConnection(connectionCreate); // Set the created connection as the current connection. const databaseList = await connectionStore.getOrFetchDatabaseList(createdConnection); connectionStore.setCurrentConnectionCtx({ connection: createdConnection, database: head(databaseList), }); close(); }; return (

Create Connection

setPartialConnection({ host: e.target.value })} />
setPartialConnection({ port: e.target.value })} />
setPartialConnection({ username: e.target.value })} />
setPartialConnection({ password: e.target.value })} />
{showDatabaseField && (
setPartialConnection({ database: e.target.value })} />
)}
); }; export default CreateConnectionModal;