tooot/src/utils/queryHooks/translate.ts

54 lines
1.2 KiB
TypeScript
Raw Normal View History

2021-05-26 23:30:15 +02:00
import haptics from '@components/haptics'
import { QueryFunctionContext, useQuery, UseQueryOptions } from '@tanstack/react-query'
import apiTooot from '@utils/api/tooot'
import { AxiosError } from 'axios'
2021-05-19 20:40:16 +02:00
2022-02-08 22:19:24 +01:00
type Translations =
| {
error: undefined
provider: string
sourceLanguage: string
text: string[]
}
| {
error: string
provider: undefined
sourceLanguage: undefined
text: undefined
}
2021-05-23 22:40:42 +02:00
2021-05-19 20:40:16 +02:00
export type QueryKeyTranslate = [
'Translate',
2021-05-23 22:40:42 +02:00
{
source: string
target: string
text: string[]
}
2021-05-19 20:40:16 +02:00
]
2021-12-18 19:59:38 +01:00
const queryFunction = async ({
queryKey
}: QueryFunctionContext<QueryKeyTranslate>) => {
const { source, target, text } = queryKey[1]
2021-05-23 22:40:42 +02:00
2021-06-21 11:59:29 +02:00
const res = await apiTooot<Translations>({
method: 'post',
url: 'translate',
2021-12-06 21:25:09 +01:00
body: { source, target, text }
2021-05-19 23:28:01 +02:00
})
2021-05-26 23:30:15 +02:00
haptics('Light')
2021-05-23 22:40:42 +02:00
return res.body
2021-05-19 20:40:16 +02:00
}
2021-05-19 23:28:01 +02:00
const useTranslateQuery = ({
options,
...queryKeyParams
}: QueryKeyTranslate[1] & {
2021-12-18 19:59:38 +01:00
options?: UseQueryOptions<Translations, AxiosError>
2021-05-19 23:28:01 +02:00
}) => {
2021-05-19 20:40:16 +02:00
const queryKey: QueryKeyTranslate = ['Translate', { ...queryKeyParams }]
2021-06-01 22:27:27 +02:00
return useQuery(queryKey, queryFunction, { ...options, retry: false })
2021-05-19 20:40:16 +02:00
}
export { useTranslateQuery }