Skip to content

Commit

Permalink
perf(dicts): improve google translate stability
Browse files Browse the repository at this point in the history
  • Loading branch information
crimx committed Jul 18, 2018
1 parent ad1f7c2 commit edd5fa9
Showing 1 changed file with 10 additions and 14 deletions.
24 changes: 10 additions & 14 deletions src/components/dictionaries/google/engine.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import { handleNoResult } from '../helpers'
import { AppConfig } from '@/app-config'
import { DictSearchResult } from '@/typings/server'
import { isContainChinese, isContainEnglish } from '@/_helpers/lang-check'
import { first } from '@/_helpers/promise-more'

export type GoogleResult = string

Expand All @@ -11,7 +12,7 @@ export default function search (
text: string,
config: AppConfig,
): Promise<GoogleSearchResult> {
const options = config.dicts.all.google.options

const chCode = config.langCode === 'zh-TW' ? 'zh-TW' : 'zh-CN'
let sl = 'auto'
let tl = chCode
Expand All @@ -23,18 +24,15 @@ export default function search (
tl = chCode
}

if (options.cnfirst) {
return fetchWithToken('https://translate.google.cn', sl, tl, text)
.catch(() => fetchWithToken('https://translate.google.com', sl, tl, text))
.catch(() => fetchWithoutToken(sl, tl, text))
} else {
return fetchWithToken('https://translate.google.com', sl, tl, text)
.catch(() => fetchWithToken('https://translate.google.cn', sl, tl, text))
.catch(() => fetchWithoutToken(sl, tl, text))
}
return first([
fetchWithToken('https://translate.google.com', sl, tl, text),
fetchWithToken('https://translate.google.cn', sl, tl, text),
])
.catch(() => fetchWithoutToken(sl, tl, text))
.then(handleText)
}

function fetchWithToken (base: string, sl: string, tl: string, text: string): Promise<GoogleSearchResult> {
function fetchWithToken (base: string, sl: string, tl: string, text: string): Promise<string> {
return fetch(base)
.then(r => r.text())
.then<Response>(body => {
Expand All @@ -50,13 +48,11 @@ function fetchWithToken (base: string, sl: string, tl: string, text: string): Pr
return handleNoResult()
})
.then(r => r.text())
.then(handleText)
}

function fetchWithoutToken (sl: string, tl: string, text: string): Promise<GoogleSearchResult> {
function fetchWithoutToken (sl: string, tl: string, text: string): Promise<string> {
return fetch(`https://translate.googleapis.com/translate_a/single?client=gtx&sl=${sl}&tl=${tl}&dt=t&q=${text}`)
.then(r => r.text())
.then(handleText)
}

function handleText (
Expand Down

0 comments on commit edd5fa9

Please sign in to comment.