Fix translation query overflow (#106)

This commit is contained in:
David
2022-05-04 21:11:44 +02:00
committed by GitHub
parent a8ed159bf4
commit ff1ad202ae

View File

@@ -12,8 +12,15 @@ export async function googleScrape(
errorMsg: string errorMsg: string
}> { }> {
const parsed = replaceBoth("mapping", { source, target }); 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( 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: { headers: {
"User-Agent": new UserAgent().toString() "User-Agent": new UserAgent().toString()
@@ -26,12 +33,12 @@ export async function googleScrape(
if (!res?.ok) if (!res?.ok)
return { return {
errorMsg: "An error occurred while retrieving the translation" errorMsg: "An error occurred while retrieving the translation"
} };
const html = await res.text(); const html = await res.text();
const translationRes = cheerio.load(html)(".result-container").text().trim(); const translationRes = cheerio.load(html)(".result-container").text().trim();
return translationRes return translationRes && !translationRes.includes("#af-error-page")
? { ? {
translationRes translationRes
} : { } : {