Skip to content

Commit

Permalink
feat: implement method to differentiate browser from node and use the…
Browse files Browse the repository at this point in the history
… correct api and update translation logic
  • Loading branch information
gabriel-logan committed Nov 1, 2024
1 parent 1965a2b commit 2482822
Show file tree
Hide file tree
Showing 8 changed files with 533 additions and 74 deletions.
Binary file modified .yarn/install-state.gz
Binary file not shown.
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,7 @@
"eslint": "^8",
"eslint-config-universe": "^13.0.0",
"jest": "^29.7.0",
"jest-environment-jsdom": "^29.7.0",
"prettier": "^3.3.3",
"ts-jest": "^29.2.5",
"ts-node": "^10.9.2",
Expand Down
3 changes: 2 additions & 1 deletion src/index.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import translate, { translateText } from "./translate";
import translate from "./translate";
import translateText from "./translate/translateText";
import translateToMultipleFolders from "./translateToMultipleFolders";
import translateToUnicFolder from "./translateToUnicFolder";
import updateTranslationsMulti from "./updateTranslationMulti";
Expand Down
68 changes: 2 additions & 66 deletions src/translate/index.ts
Original file line number Diff line number Diff line change
@@ -1,69 +1,5 @@
import axios from "axios";
import { v4 as uuidv4 } from "uuid";

import type { JSONValue, TranslationType } from "../types";

interface Translation {
text: TranslationType;
to: TranslationType;
}

interface TranslationResponse {
translations: Translation[];
}

type TranslateResponseData = TranslationResponse[];

/**
*
* @param text
* @param from
* @param to
* @param endpoint
* @param key
* @param location
* @returns A Promise that resolves to the translated text.
* @example
* from: "en"
* to: ["es", "fr"]
*
* translateText("Hello", "en", ["es", "fr"], "https://api.cognitive.microsofttranslator.com", "key", "location")
*
* Returns: [ { text: 'Hola', to: 'es' }, { text: 'Bonjour', to: 'fr' } ]
*/
export async function translateText(
text: string,
from: string,
to: string[],
endpoint: string,
key: string,
location: string,
) {
const filteredEndpoint = endpoint.replace(/\/$/, "");

const toDestructured = to.map((lang) => `to=${lang}`).join("&");

const url = `${filteredEndpoint}/translate?api-version=3.0&from=${from}&${toDestructured}`;

const response = await axios.post<TranslateResponseData>(
url,
[
{
text,
},
],
{
headers: {
"Ocp-Apim-Subscription-Key": key,
"Ocp-Apim-Subscription-Region": location,
"Content-type": "application/json",
"X-ClientTraceId": uuidv4().toString(),
},
},
);

return response;
}
import translateText from "./translateText";

/**
* Translates a JSON object from one language to another using the Azure Translator service.
Expand Down Expand Up @@ -177,7 +113,7 @@ async function translateString(
location,
);

const translations = response.data[0].translations;
const translations = response[0].translations;

const translatedValues = translations.map((translation) => {
return translation.text;
Expand Down
78 changes: 78 additions & 0 deletions src/translate/translateText.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,78 @@
import axios from "axios";
import { v4 as uuidv4 } from "uuid";

import type { TranslationType } from "../types";

interface Translation {
text: TranslationType;
to: TranslationType;
}

interface TranslationResponse {
translations: Translation[];
}

type TranslateResponseData = TranslationResponse[];

/**
*
* @param text - The text to translate.
* @param from - The language code of the source language.
* @param to - The languages code of the target languages.
* @param endpoint - The Azure Translator endpoint URL.
* @param key - The Azure Translator subscription key.
* @param location - The Azure Translator subscription region.
* @returns A Promise that resolves to the translated text.
* @example
* from: "en"
* to: ["es", "fr"]
*
* translateText("Hello", "en", ["es", "fr"], "https://api.cognitive.microsofttranslator.com", "key", "location")
*
* Returns example:
[
{
translations: [
{ text: "Hola", to: "es" },
{ text: "Bonjour", to: "fr" }
]
}
]
*/
export default async function translateText(
text: string,
from: string,
to: string[],
endpoint: string,
key: string,
location: string,
): Promise<TranslateResponseData> {
const filteredEndpoint = endpoint.replace(/\/$/, "");
const toDestructured = to.map((lang) => `to=${lang}`).join("&");
const url = `${filteredEndpoint}/translate?api-version=3.0&from=${from}&${toDestructured}`;

const headers = {
"Ocp-Apim-Subscription-Key": key,
"Ocp-Apim-Subscription-Region": location,
"Content-type": "application/json",
"X-ClientTraceId": uuidv4(),
};

const payload = [{ text }];

if (typeof window !== "undefined" && typeof window.fetch === "function") {
const response = await fetch(url, {
method: "POST",
headers,
body: JSON.stringify(payload),
});

return await response.json();
} else {
const response = await axios.post<TranslateResponseData>(url, payload, {
headers,
});

return response.data;
}
}
5 changes: 3 additions & 2 deletions tests/translate/index.test.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import axios from "axios";

import translate, { translateText } from "../../src/translate";
import translate from "../../src/translate";
import translateText from "../../src/translate/translateText";
import type { TranslationType } from "../../src/types";

describe("translate", () => {
Expand Down Expand Up @@ -44,7 +45,7 @@ describe("translate", () => {

expect(spyOnAxios).toHaveBeenCalled();

expect(result.data[0].translations[0].text).toEqual("Bem-vindo");
expect(result[0].translations[0].text).toEqual("Bem-vindo");
});
});

Expand Down
47 changes: 47 additions & 0 deletions tests/translate/translateText.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
/**
* @jest-environment jsdom
*/

import { translateText } from "../../src";

describe("translateText", () => {
let fromLang: string;
let toLangs: string[];
let endpoint: string;
let key: string;
let location: string;

beforeAll(() => {
fromLang = "en";
toLangs = ["pt"];
endpoint = "https://api.cognitive.microsofttranslator.com/translate";
key = "12345";
location = "eastus";
});

it("window.fetch is defined and should be called", async () => {
global.fetch = jest.fn(() =>
Promise.resolve({
json: () =>
Promise.resolve({
translations: [
{
text: "Bem-vindo",
},
],
}),
}),
) as jest.Mock;

const result: any = await translateText(
"Welcome",
fromLang,
toLangs,
endpoint,
key,
location,
);

expect(result.translations[0].text).toEqual("Bem-vindo");
});
});
Loading

0 comments on commit 2482822

Please sign in to comment.