tooot/src/utils/queryHooks/translate.ts

66 lines
1.6 KiB
TypeScript
Raw Normal View History

2021-05-19 20:40:16 +02:00
import apiGeneral from '@api/general'
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-05-23 22:40:42 +02:00
import { Buffer } from 'buffer'
import Constants from 'expo-constants'
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-23 22:40:42 +02:00
export const TRANSLATE_SERVER = __DEV__
? 'testtranslate.tooot.app'
: 'translate.tooot.app'
2021-05-19 23:28:01 +02:00
const queryFunction = async ({ queryKey }: { queryKey: QueryKeyTranslate }) => {
2021-05-23 22:40:42 +02:00
const key = Constants.manifest.extra?.translateKey
if (!key) {
return Promise.reject()
}
const { uri, source, target, text } = queryKey[1]
const uriEncoded = Buffer.from(uri.replace(/https?:\/\//, ''))
.toString('base64')
.replace('+', '-')
.replace('/', '_')
.replace(/=+$/, '')
const original = Buffer.from(JSON.stringify({ source, text })).toString(
'base64'
)
2021-05-23 22:40:42 +02:00
const res = await apiGeneral<Translations>({
domain: TRANSLATE_SERVER,
method: 'get',
url: `v1/translate/${uriEncoded}/${target}`,
headers: { key, 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-05-19 23:28:01 +02:00
return useQuery(queryKey, queryFunction, options)
2021-05-19 20:40:16 +02:00
}
export { useTranslateQuery }