fix(google): fail over between compatible hosts

This commit is contained in:
xixu-me committed 2026-08-19 16:54:57 +08:00
1 parent d885923253
commit 4e854481e1
2 files changed
+39 -5

No files matched your search

+15 -5
View File
@@ -40,8 +40,7 @@ export async function translateWithGoogle(
googleApiUrl.searchParams.append("dt", "t"); // 't' for translation of text
googleApiUrl.searchParams.append("q", text); // The text to translate
// Make the fetch call to Google Translate
const googleResponse = await fetch(googleApiUrl.toString(), {
const requestInit = {
method: "GET",
headers: {
"User-Agent":
@@ -50,11 +49,22 @@ export async function translateWithGoogle(
"Accept-Language": "en-US,en;q=0.9",
Referer: "https://translate.google.com/",
},
});
};
if (!googleResponse.ok) {
let googleResponse: Response | undefined;
for (const hostname of ["translate.googleapis.com", "translate.google.com"]) {
googleApiUrl.hostname = hostname;
try {
googleResponse = await fetch(googleApiUrl.toString(), requestInit);
if (googleResponse.ok) break;
} catch {
// Try the compatible fallback host.
}
}
if (!googleResponse?.ok) {
throw new Error(
`Google Translate API responded with status ${googleResponse.status}`
`Google Translate API responded with status ${googleResponse?.status || 500}`
);
}
@@ -75,6 +75,30 @@ describe("Google Translate Service", () => {
expect(result.data).toBeNull();
});
it("should use the compatible host when the primary is unavailable", async () => {
global.fetch = jest
.fn()
.mockResolvedValueOnce({ ok: false, status: 429 })
.mockResolvedValueOnce({
ok: true,
json: () =>
Promise.resolve([[["Hola", "Hello", null, null, 10]], null, "en"]),
});
const result = await translateWithGoogle({
text: "Hello",
source_lang: "en",
target_lang: "es",
});
expect(result.code).toBe(200);
expect(fetch).toHaveBeenCalledTimes(2);
expect(fetch).toHaveBeenLastCalledWith(
expect.stringContaining("translate.google.com"),
expect.any(Object)
);
});
it("should handle network errors", async () => {
// Mock fetch for network error
global.fetch = jest.fn(() =>