Skip to content

Instantly share code, notes, and snippets.

@Wolfr
Created June 23, 2021 20:15
Show Gist options
  • Save Wolfr/6e2a7d2fb30ec0d447220e184e70b1d1 to your computer and use it in GitHub Desktop.
Save Wolfr/6e2a7d2fb30ec0d447220e184e70b1d1 to your computer and use it in GitHub Desktop.
import pMemoize from 'p-memoize'
import { LanguageKey, TextNodePlainObject } from './types.js'
export const translateAsync = pMemoize(async function (
{ characters, id }: TextNodePlainObject,
languageKey: LanguageKey
) {
// Old Google API
// const url = `https://translate.googleapis.com/translate_a/single?client=gtx&sl=auto&key=YOUR_API_KEY&tl=${languageKey}&dt=t&q=${encode(
// characters
// )}`
const url = `YOUR_CORS_SERVER_HERE/https://translation.googleapis.com/language/translate/v2?key=YOUR_API_KEY&target=${languageKey}&dt=t&q=${encode(
characters
)}`
const response = await window.fetch(url);
const result = await response.json()
// OLD result parsing
// const translated = result[0]
// .map(function (item: Array<string>) {
// return item[0]
// })
// .join('')
// NEW resulting parsing
const translated = parseResult(result.data.translations[0].translatedText)
return {
characters: translated,
id
}
})
const newlineRegex = /\n/
function encode(text: string) {
return encodeURI(text).replace(newlineRegex, '%0A')
}
// NEW parseResult function to deal with the ' character
function parseResult(text: string) {
return text.replace('&#39;','\'')
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment