From ff1ad202aee94cd68cb6f797f23c0976985d4400 Mon Sep 17 00:00:00 2001 From: David Date: Wed, 4 May 2022 21:11:44 +0200 Subject: [PATCH] Fix translation query overflow (#106) --- utils/translate.ts | 13 ++++++++++--- 1 file changed, 10 insertions(+), 3 deletions(-) diff --git a/utils/translate.ts b/utils/translate.ts index 63acdf7..34302f2 100644 --- a/utils/translate.ts +++ b/utils/translate.ts @@ -12,8 +12,15 @@ export async function googleScrape( errorMsg: string }> { const parsed = replaceBoth("mapping", { source, target }); + const encodedQuery = encodeURIComponent(query); + + if (encodedQuery.length > 7500) + return { + errorMsg: "The translation query is too long" + }; + const res = await fetch( - `https://translate.google.com/m?sl=${parsed.source}&tl=${parsed.target}&q=${encodeURIComponent(query)}`, + `https://translate.google.com/m?sl=${parsed.source}&tl=${parsed.target}&q=${encodedQuery}`, { headers: { "User-Agent": new UserAgent().toString() @@ -26,12 +33,12 @@ export async function googleScrape( if (!res?.ok) return { errorMsg: "An error occurred while retrieving the translation" - } + }; const html = await res.text(); const translationRes = cheerio.load(html)(".result-container").text().trim(); - return translationRes + return translationRes && !translationRes.includes("#af-error-page") ? { translationRes } : {