diff --git a/src/index.ts b/src/index.ts index 8a986eb..e2c3bfc 100644 --- a/src/index.ts +++ b/src/index.ts @@ -165,18 +165,16 @@ async function handleTranslation(c: any, provider: "deepl" | "google") { let result; - // Choose translation provider if (provider === "google") { - result = await translateWithGoogle(validatedParams, { - env, - clientIP, - }); + result = await translateWithGoogle(validatedParams, { env, clientIP }); } else { - // Use DeepL as default - result = await query(validatedParams, { - env, - clientIP, - }); + result = await query(validatedParams, { env, clientIP }); + + // ponytail: the anonymous DeepL API now rate-limits XDPL; keep the + // compatible endpoint available via the existing provider. + if (result.code === 429) { + result = await translateWithGoogle(validatedParams, { env, clientIP }); + } } // Cache successful translations diff --git a/tests/index.test.ts b/tests/index.test.ts index 8f030d7..4eab95c 100644 --- a/tests/index.test.ts +++ b/tests/index.test.ts @@ -21,6 +21,10 @@ jest.mock("../src/lib/security", () => ({ .mockImplementation((code) => code?.toLowerCase()), })); +jest.mock("../src/lib/services/googleTranslate", () => ({ + translateWithGoogle: jest.fn(), +})); + jest.mock("../src/lib/env", () => ({ validateEnvironment: jest.fn().mockReturnValue([]), })); @@ -296,6 +300,38 @@ describe("Main App", () => { expect(response.status).toBe(500); }); + it("should fall back to Google when XDPL is rate limited", async () => { + const { getCachedTranslation, query } = require("../src/lib"); + const { translateWithGoogle } = require("../src/lib/services/googleTranslate"); + + getCachedTranslation.mockResolvedValueOnce(null); + query.mockResolvedValueOnce({ code: 429, data: null }); + translateWithGoogle.mockResolvedValueOnce({ + code: 200, + data: "你好,世界", + id: 12345, + source_lang: "EN", + target_lang: "ZH", + }); + + const response = await app.fetch( + new Request("http://localhost/deepl", { + method: "POST", + headers: { "Content-Type": "application/json" }, + body: JSON.stringify({ + text: "Hello world", + source_lang: "en", + target_lang: "zh", + }), + }), + mockEnv + ); + + expect(response.status).toBe(200); + expect(translateWithGoogle).toHaveBeenCalledTimes(1); + expect((await response.json()).data).toBe("你好,世界"); + }); + it("should use default language codes", async () => { const { query, getCachedTranslation } = require("../src/lib");