Created
June 23, 2021 20:15
-
-
Save Wolfr/6e2a7d2fb30ec0d447220e184e70b1d1 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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(''','\'') | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment