tooot/src/utils/queryHooks/translate.ts

58 lines
1.4 KiB
TypeScript
Raw Normal View History

2021-06-21 11:59:29 +02:00
import apiTooot from '@api/tooot'
2021-05-26 23:30:15 +02:00
import haptics from '@components/haptics'
2021-05-19 23:28:01 +02:00
import { AxiosError } from 'axios'
2021-08-22 00:17:24 +02:00
import * as Crypto from 'expo-crypto'
2021-05-19 23:28:01 +02:00
import { useQuery, UseQueryOptions } from 'react-query'
2021-05-19 20:40:16 +02:00
2021-05-23 22:40:42 +02:00
type Translations = {
provider: string
sourceLanguage: string
text: string[]
}
2021-05-19 20:40:16 +02:00
export type QueryKeyTranslate = [
'Translate',
2021-05-23 22:40:42 +02:00
{
uri: string
2021-05-23 22:40:42 +02:00
source: string
target: string
text: string[]
}
2021-05-19 20:40:16 +02:00
]
2021-05-19 23:28:01 +02:00
const queryFunction = async ({ queryKey }: { queryKey: QueryKeyTranslate }) => {
const { uri, source, target, text } = queryKey[1]
2021-08-22 00:17:24 +02:00
const uriEncoded = await Crypto.digestStringAsync(
Crypto.CryptoDigestAlgorithm.SHA256,
uri.replace(/https?:\/\//, ''),
{ encoding: Crypto.CryptoEncoding.HEX }
)
const original = await Crypto.digestStringAsync(
Crypto.CryptoDigestAlgorithm.SHA256,
JSON.stringify({ source, text }),
{ encoding: Crypto.CryptoEncoding.HEX }
)
2021-05-23 22:40:42 +02:00
2021-06-21 11:59:29 +02:00
const res = await apiTooot<Translations>({
2021-05-23 22:40:42 +02:00
method: 'get',
2021-06-21 11:59:29 +02:00
service: 'translate',
url: `source/${uriEncoded}/target/${target}`,
headers: { original }
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-05-23 22:40:42 +02:00
options?: UseQueryOptions<Translations, AxiosError, Translations>
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 }