Skip to content

Commit

Permalink
feat: auto retry 3 times when failing to request & enable the `tryFet…
Browse files Browse the repository at this point in the history
…chingGenderDebiasedTranslations` option to follow the website
  • Loading branch information
plainheart committed Nov 17, 2023
1 parent e1007ad commit 926e2e7
Showing 1 changed file with 42 additions and 6 deletions.
48 changes: 42 additions & 6 deletions src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,9 @@ const MAX_TEXT_LEN = 1000
// PENDING
const MAX_CORRECT_TEXT_LEN = 50

// PENDING: make it configurable?
const MAX_RETRY_COUNT = 3

/**
* @typedef {{
* IG: string,
Expand Down Expand Up @@ -79,7 +82,11 @@ async function fetchGlobalConfig(userAgent, proxyAgents) {
headers: {
'user-agent': userAgent || USER_AGENT
},
agent: proxyAgents
agent: proxyAgents,
retry: {
limit: MAX_RETRY_COUNT,
methods: ['GET']
}
}
)

Expand Down Expand Up @@ -126,13 +133,30 @@ async function fetchGlobalConfig(userAgent, proxyAgents) {
}
}

/**
* @param {boolean} isSpellCheck
*/
function makeRequestURL(isSpellCheck) {
const { IG, IID, subdomain } = globalConfig
return replaceSubdomain(isSpellCheck ? TRANSLATE_API_SPELL_CHECK : TRANSLATE_API, subdomain)
+ '&IG=' + IG
+ '&IID=' + (IID + '.' + (++globalConfig.count))
+ '&IID=' + (IID + (isSpellCheck ? '.' + (++globalConfig.count) : ''))
}

/**
* @param {boolean} isSpellCheck
* @param {string} text
* @param {string} fromLang
* @param {string} toLang
* @returns {{
* fromLang: string,
* to?: string,
* text: string,
* token: string,
* key: number,
* tryFetchingGenderDebiasedTranslations?: true
* }}
*/
function makeRequestBody(isSpellCheck, text, fromLang, toLang) {
const { token, key } = globalConfig
const body = {
Expand All @@ -141,8 +165,10 @@ function makeRequestBody(isSpellCheck, text, fromLang, toLang) {
token,
key
}
if (!isSpellCheck && toLang) {
body.to = toLang
if (!isSpellCheck) {
toLang && (body.to = toLang)

body.tryFetchingGenderDebiasedTranslations = true
}
return body
}
Expand Down Expand Up @@ -203,12 +229,21 @@ async function translate(text, from, to, correct, raw, userAgent, proxyAgents) {
cookie: globalConfig.cookie
}

/**
* @type {import('got').Options['retry']}
*/
const retryConfig = {
limit: MAX_RETRY_COUNT,
methods: ['POST']
}

const { body } = await got.post(requestURL, {
headers: requestHeaders,
// got will set CONTENT_TYPE as `application/x-www-form-urlencoded`
form: requestBody,
responseType: 'json',
agent: proxyAgents
agent: proxyAgents,
retry: retryConfig
})

if (body.ShowCaptcha) {
Expand Down Expand Up @@ -262,7 +297,8 @@ async function translate(text, from, to, correct, raw, userAgent, proxyAgents) {
headers: requestHeaders,
form: requestBody,
responseType: 'json',
agent: proxyAgents
agent: proxyAgents,
retry: retryConfig
})

res.correctedText = body && body.correctedText
Expand Down

0 comments on commit 926e2e7

Please sign in to comment.