| 6 | } |
| 7 | |
| 8 | export function useTranslate() { |
| 9 | const [translating, setTranslating] = useState(false); |
| 10 | const [outputText, setOutputText] = useState(""); |
| 11 | const [translationError, setTranslationError] = useState(""); |
| 12 | |
| 13 | const translate = async ({ |
| 14 | inputText, |
| 15 | tableSchema, |
| 16 | isHumanToSql, |
| 17 | }: { inputText: string; tableSchema: string; isHumanToSql: boolean }) => { |
| 18 | setTranslating(true); |
| 19 | try { |
| 20 | const requestBody: RequestBody = { inputText }; |
| 21 | if (tableSchema !== "") { |
| 22 | requestBody.tableSchema = tableSchema; |
| 23 | } |
| 24 | const response = await fetch( |
| 25 | `/api/${isHumanToSql ? "translate" : "sql-to-human"}`, |
| 26 | { |
| 27 | method: "POST", |
| 28 | body: JSON.stringify(requestBody), |
| 29 | headers: { "Content-Type": "application/json" }, |
| 30 | }, |
| 31 | ); |
| 32 | if (response.ok) { |
| 33 | const data = await response.json(); |
| 34 | setOutputText(data.outputText); |
| 35 | } else { |
| 36 | setTranslationError( |
| 37 | `Error translating ${isHumanToSql ? "to SQL" : "to human"}.`, |
| 38 | ); |
| 39 | } |
| 40 | } catch (error) { |
| 41 | console.error(error); |
| 42 | setTranslationError( |
| 43 | `Error translating ${isHumanToSql ? "to SQL" : "to human"}.`, |
| 44 | ); |
| 45 | } finally { |
| 46 | setTranslating(false); |
| 47 | } |
| 48 | }; |
| 49 | |
| 50 | return { |
| 51 | outputText, |
| 52 | setOutputText, |
| 53 | translate, |
| 54 | translating, |
| 55 | translationError, |
| 56 | }; |
| 57 | } |