From 516e3b33ce7a51e906ffb131fa208ea01f9a7eca Mon Sep 17 00:00:00 2001 From: Jeongho Nam Date: Thu, 24 Oct 2024 15:47:29 +0900 Subject: [PATCH] Avoid bad language pair problem. --- package.json | 2 +- src/JsonTranslator.ts | 32 ++++++++++++++++--------- test/features/test_bad_language_pair.ts | 26 ++++++++++++++++++++ 3 files changed, 48 insertions(+), 12 deletions(-) create mode 100644 test/features/test_bad_language_pair.ts diff --git a/package.json b/package.json index e40e148..4c5b804 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "@samchon/json-translator", - "version": "2.1.2", + "version": "2.1.3", "description": "JSON Translator via Google Translation API with optimization strategies", "main": "lib/index.js", "types": "lib/index.d.ts", diff --git a/src/JsonTranslator.ts b/src/JsonTranslator.ts index 791820f..a74d6d7 100644 --- a/src/JsonTranslator.ts +++ b/src/JsonTranslator.ts @@ -58,14 +58,26 @@ export class JsonTranslator { let bytes: number = 0; const execute = async () => { if (queue.length) { - const [response] = await this.service_.translate( - queue.map((p) => p.text), - { - from, - to: props.target, - format: "html", - }, - ); + const complete = (texts: string[]) => { + translated.push(...texts); + queue = []; + bytes = 0; + }; + let response: string[] = []; + try { + [response] = await this.service_.translate( + queue.map((p) => p.text), + { + from, + to: props.target, + format: "html", + }, + ); + } catch (exp) { + if (exp instanceof Error && exp.message.includes("Bad language pair")) + return complete(queue.map((p) => p.text)); + throw exp; + } const expected: number = queue .map((p) => p.text.split(SEPARATOR).length) .reduce((x, y) => x + y, 0); @@ -88,10 +100,8 @@ export class JsonTranslator { `Mismatched translation count. Delivered ${expected} count string values to the Google Translate API, but received number is ${actual}.`, ); } - translated.push(...response); + return complete(response); } - queue = []; - bytes = 0; }; for (const text of collection.raw) { diff --git a/test/features/test_bad_language_pair.ts b/test/features/test_bad_language_pair.ts new file mode 100644 index 0000000..066fab8 --- /dev/null +++ b/test/features/test_bad_language_pair.ts @@ -0,0 +1,26 @@ +import { TestValidator } from "@nestia/e2e"; +import { JsonTranslator } from "@samchon/json-translator"; +import typia, { tags } from "typia"; + +import input from "../../assets/input/bbs.article.json"; + +export const test_bad_language_pair = async ( + translator: JsonTranslator, +): Promise => { + typia.assertGuard(input); + + const output: IBbsArticle = await translator.translate({ + input, + target: "en", + filter: ({ key }) => key === "title" || key === "body", + }); + TestValidator.equals("english to english")(input)(output); +}; + +interface IBbsArticle { + id: string & tags.Format<"uuid">; + title: string; + body: string; + created_at: string & tags.Format<"date-time">; + updated_at: string & tags.Format<"date-time">; +}