| 175 | }; |
| 176 | |
| 177 | const handleUpsertConnection = async () => { |
| 178 | if (isRequesting) { |
| 179 | return; |
| 180 | } |
| 181 | |
| 182 | setIsRequesting(true); |
| 183 | const tempConnection = cloneDeep(connection); |
| 184 | if (!showDatabaseField) { |
| 185 | tempConnection.database = undefined; |
| 186 | } |
| 187 | |
| 188 | try { |
| 189 | const response = await fetch("/api/connection/test", { |
| 190 | method: "POST", |
| 191 | headers: { |
| 192 | "Content-Type": "application/json", |
| 193 | }, |
| 194 | body: JSON.stringify({ |
| 195 | connection: tempConnection, |
| 196 | }), |
| 197 | }); |
| 198 | const result = (await response.json()) as ResponseObject<boolean>; |
| 199 | if (result.message) { |
| 200 | toast.error(result.message); |
| 201 | return; |
| 202 | } |
| 203 | } catch (error) { |
| 204 | console.error(error); |
| 205 | toast.error("Failed to test connection"); |
| 206 | } finally { |
| 207 | setIsRequesting(false); |
| 208 | } |
| 209 | |
| 210 | try { |
| 211 | let connection: Connection; |
| 212 | if (isEditing) { |
| 213 | connectionStore.updateConnection(tempConnection.id, tempConnection); |
| 214 | connection = tempConnection; |
| 215 | } else { |
| 216 | connection = connectionStore.createConnection(tempConnection); |
| 217 | } |
| 218 | |
| 219 | // Set the created connection as the current connection. |
| 220 | const databaseList = await connectionStore.getOrFetchDatabaseList(connection, true); |
| 221 | connectionStore.setCurrentConnectionCtx({ |
| 222 | connection: connection, |
| 223 | database: head(databaseList), |
| 224 | }); |
| 225 | } catch (error) { |
| 226 | console.error(error); |
| 227 | setIsRequesting(false); |
| 228 | toast.error("Failed to create connection"); |
| 229 | return; |
| 230 | } |
| 231 | |
| 232 | setIsRequesting(false); |
| 233 | close(); |
| 234 | }; |