fix(translation): fall back when XDPL is rate limited
This commit is contained in:
1 parent
21d87b184c
commit
975e1dfc28
2 files changed
+44
-10
No files matched your search
+8
-10
@@ -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
|
||||
|
||||
@@ -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");
|
||||
|
||||
|
||||
Reference in new issue
Block a user