Skip to content

Commit

Permalink
refactor: improving code, cleaner code, improving type safety and cha…
Browse files Browse the repository at this point in the history
…nging axios to fetch
  • Loading branch information
gabriel-logan committed Oct 30, 2024
1 parent ad01e59 commit 1965a2b
Show file tree
Hide file tree
Showing 16 changed files with 347 additions and 297 deletions.
3 changes: 1 addition & 2 deletions docs/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,6 @@
"dependencies": {
"@vercel/analytics": "^1.3.1",
"ace-builds": "^1.34.2",
"azure-translator-code": "^1.1.16",
"next": "14.2.3",
"next-international": "^1.2.4",
"react": "^18",
Expand All @@ -20,7 +19,7 @@
"react-icons": "^5.2.1",
"react-syntax-highlighter": "^15.5.0",
"sharp": "^0.33.4",
"uuid": "^10.0.0"
"uuid": "^11.0.2"
},
"devDependencies": {
"@types/node": "^20",
Expand Down
154 changes: 35 additions & 119 deletions docs/src/actions/index.ts
Original file line number Diff line number Diff line change
@@ -1,13 +1,13 @@
"use server";

import { translate, TranslationType } from "azure-translator-code";
import { v4 as uuidv4 } from "uuid";

import localesCodes from "@/lib/localesCode";
import translate from "@/lib/translate";
import { translateText } from "@/lib/translateText";
import { getScopedI18n } from "@/locales/server";
import { Langs } from "@/types/locales";

// Cache to store translations
const translationCache: { [key: string]: TranslationType } = {};
const key = process.env.AZURE_API_KEY ?? "";
const endpoint = process.env.AZURE_ENDPOINT ?? "";
const location = process.env.AZURE_LOCATION ?? "";

export async function makeTranslation(prevState: any, formData: FormData) {
const scopedT = await getScopedI18n("Actions");
Expand All @@ -18,16 +18,6 @@ export async function makeTranslation(prevState: any, formData: FormData) {
jsonFileText: formData.get("jsonfile"),
};

// Cache key
const cacheKey = `${data.fromLang}-${data.toLang}-${data.jsonFileText}`;

// Check if the translation is in the cache
if (translationCache[cacheKey]) {
return {
message: translationCache[cacheKey],
};
}

if (!data) {
return {
message: scopedT("MakeTranslations.Invalid or missing request body"),
Expand All @@ -54,39 +44,29 @@ export async function makeTranslation(prevState: any, formData: FormData) {
};
}

const key = process.env.AZURE_API_KEY ?? ""; // REPLACE WITH YOUR OWN KEY HERE
const endpoint = process.env.AZURE_ENDPOINT ?? "";
const location = process.env.AZURE_LOCATION ?? "";
const fromLang = data.fromLang as string;
const toLang = data.toLang as string;

let translatedValues: TranslationType;

const valuesToTranslate = data.jsonFileText;

const toLangs = [toLang];
const valuesToTranslate = data.jsonFileText;

try {
translatedValues = await translate(
const translatedValues = await translate(
key,
endpoint,
location,
fromLang,
toLangs,
JSON.parse(valuesToTranslate as string),
);

return {
message: translatedValues,
};
} catch {
return {
message: scopedT("MakeTranslations.Invalid json text passed"),
};
}

// Save the translation in the cache
translationCache[cacheKey] = translatedValues;

return {
message: translatedValues,
};
}

export async function makeTranslationMultilang(
Expand All @@ -95,10 +75,6 @@ export async function makeTranslationMultilang(
) {
const scopedT = await getScopedI18n("Actions");

const key = process.env.AZURE_API_KEY ?? "";
const endpoint = process.env.AZURE_ENDPOINT ?? "";
const location = process.env.AZURE_LOCATION ?? "";

const toTranslate = formData.get("toTranslate") as string;

if (!toTranslate) {
Expand All @@ -116,78 +92,34 @@ export async function makeTranslationMultilang(
}

const fromLang = formData.get("fromLang") as string;

const languageCodes: Langs[] = [
"en",
"pt",
"es",
"de",
"fr",
"it",
"ja",
"ko",
"ru",
"zh",
"ar",
"tr",
"vi",
"th",
"sv",
"pl",
"nl",
"da",
"fi",
"no",
"cs",
"hu",
"el",
"id",
"ms",
];

const toLangs = languageCodes.filter((code) => formData.get(code) === "on");
const toLangs = localesCodes.filter((code) => formData.get(code) === "on");

if (!toLangs.length) {
return {
message: scopedT("makeTranslationMultilang.No languages selected"),
};
}

let url = `/translate?api-version=3.0&from=${fromLang ?? "en"}`;
for (const lang of toLangs) {
url += `&to=${lang}`;
}

let data: any;

try {
const pega = await fetch(endpoint + url, {
method: "POST",
headers: {
"Ocp-Apim-Subscription-Key": key,
"Ocp-Apim-Subscription-Region": location,
"Content-type": "application/json",
"X-ClientTraceId": uuidv4().toString(),
},
body: JSON.stringify([
{
text: toTranslate,
},
]),
});
const data = await translateText(
toTranslate,
fromLang,
toLangs,
endpoint,
key,
location,
);

data = await pega.json();
return {
message: data[0].translations,
};
} catch {
return {
message: scopedT(
"makeTranslationMultilang.Error while translating the text. Please try again.",
),
};
}

return {
message: data[0].translations,
};
}

export async function makeLiveTranslation(prevState: any, formData: FormData) {
Expand Down Expand Up @@ -225,37 +157,21 @@ export async function makeLiveTranslation(prevState: any, formData: FormData) {
};
}

const key = process.env.AZURE_API_KEY ?? ""; // REPLACE WITH YOUR OWN KEY HERE
const endpoint = process.env.AZURE_ENDPOINT ?? "";
const location = process.env.AZURE_LOCATION ?? "";
const fromLang = data.fromLang;
const toLang = data.toLang;
const text = data.text;

let translatedText: string;
const fromLang = data.fromLang as string;
const toLang = data.toLang as string;
const text = data.text as string;

try {
const pega = await fetch(
`${endpoint}/translate?api-version=3.0&from=${String(fromLang)}&to=${String(toLang)}`,
{
method: "POST",
headers: {
"Ocp-Apim-Subscription-Key": key,
"Ocp-Apim-Subscription-Region": location,
"Content-type": "application/json",
"X-ClientTraceId": uuidv4().toString(),
},
body: JSON.stringify([
{
text,
},
]),
},
const data = await translateText(
text,
fromLang,
[toLang],
endpoint,
key,
location,
);

const data = await pega.json();

translatedText = data[0].translations[0].text;
const translatedText = data[0].translations[0].text;

return {
message: translatedText,
Expand Down
2 changes: 1 addition & 1 deletion docs/src/app/not-found.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,7 @@ export default async function NotFound() {
alignSelf: "center",
margin: "auto",
}}
></iframe>
/>
</div>
</main>
</body>
Expand Down
32 changes: 2 additions & 30 deletions docs/src/app/sitemap.ts
Original file line number Diff line number Diff line change
@@ -1,36 +1,8 @@
import { MetadataRoute } from "next";

import { Langs } from "@/types/locales";
import languageCodes from "@/lib/localesCode";

const langs: Langs[] = [
"en",
"pt",
"es",
"de",
"fr",
"it",
"ja",
"ko",
"ru",
"zh",
"ar",
"tr",
"vi",
"th",
"sv",
"pl",
"nl",
"da",
"fi",
"no",
"cs",
"hu",
"el",
"id",
"ms",
];

const routes: MetadataRoute.Sitemap = langs.map((lang) => ({
const routes: MetadataRoute.Sitemap = languageCodes.map((lang) => ({
url: `${process.env.NEXT_PUBLIC_WEBSITE_URL}/${lang}`,
lastModified: new Date(),
changeFrequency: "monthly",
Expand Down
8 changes: 6 additions & 2 deletions docs/src/components/FormTransLiveText/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,8 @@ import { useFormState } from "react-dom";

import { makeLiveTranslation } from "@/actions";
import { useScopedI18n } from "@/locales/client";
import { Locale } from "@/types/locales";
import type { Locale } from "@/types/locales";
import type { LanguagesCode } from "@/types/translations";

import InputResult from "./InputResult";

Expand All @@ -25,7 +26,10 @@ export default function FormTransLiveText({ locale }: Readonly<Locale>) {

const [response, action] = useFormState(makeLiveTranslation, initialState);

const languages = [
const languages: {
id: LanguagesCode;
name: string;
}[] = [
{ id: "en", name: scopedT("Langs.English") },
{ id: "pt", name: scopedT("Langs.Portuguese") },
{ id: "es", name: scopedT("Langs.Spanish") },
Expand Down
8 changes: 6 additions & 2 deletions docs/src/components/FormTransMultiText/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,8 @@ import { useFormState } from "react-dom";

import { makeTranslationMultilang } from "@/actions";
import { useScopedI18n } from "@/locales/client";
import { Locale } from "@/types/locales";
import type { Locale } from "@/types/locales";
import type { LanguagesCode } from "@/types/translations";

import { ButtonCopyUnicText } from "../ButtonCopy";
import ButtonSubmit from "../ButtonSubmit";
Expand All @@ -25,7 +26,10 @@ export default function FormTransMultiText({ locale }: Readonly<Locale>) {

const [textToTranslate, setTextToTranslate] = useState("");

const languages = [
const languages: {
id: LanguagesCode;
name: string;
}[] = [
{ id: "en", name: scopedT("Langs.English") },
{ id: "pt", name: scopedT("Langs.Portuguese") },
{ id: "es", name: scopedT("Langs.Spanish") },
Expand Down
14 changes: 7 additions & 7 deletions docs/src/components/FormTransUnicJson/ResultDiv.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -23,13 +23,13 @@ export default function ResultDiv({

{pending ? (
<div className="animate-pulse overflow-x-auto rounded bg-gray-100 p-2">
<div className="mb-2 h-4 w-3/4 animate-pulse bg-gray-400"></div>
<div className="mb-2 ml-4 h-4 w-1/2 animate-pulse bg-gray-400"></div>
<div className="mb-2 ml-8 h-4 w-2/3 animate-pulse bg-gray-400"></div>
<div className="mb-2 ml-8 h-4 w-1/2 animate-pulse bg-gray-400"></div>
<div className="mb-2 ml-12 h-4 w-2/3 animate-pulse bg-gray-400"></div>
<div className="mb-2 ml-12 h-4 w-1/2 animate-pulse bg-gray-400"></div>
<div className="h-4 w-3/4 animate-pulse bg-gray-400"></div>
<div className="mb-2 h-4 w-3/4 animate-pulse bg-gray-400" />
<div className="mb-2 ml-4 h-4 w-1/2 animate-pulse bg-gray-400" />
<div className="mb-2 ml-8 h-4 w-2/3 animate-pulse bg-gray-400" />
<div className="mb-2 ml-8 h-4 w-1/2 animate-pulse bg-gray-400" />
<div className="mb-2 ml-12 h-4 w-2/3 animate-pulse bg-gray-400" />
<div className="mb-2 ml-12 h-4 w-1/2 animate-pulse bg-gray-400" />
<div className="h-4 w-3/4 animate-pulse bg-gray-400" />
</div>
) : (
<pre className="overflow-x-auto text-black">
Expand Down
6 changes: 3 additions & 3 deletions docs/src/components/FormTransUnicJson/Textarea.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -39,10 +39,10 @@ export default function Textarea() {
name="jsonfileAce"
fontSize={14}
lineHeight={19}
showPrintMargin={true}
showGutter={true}
showPrintMargin
showGutter
width="100%"
highlightActiveLine={true}
highlightActiveLine
value={jsonFileText}
onChange={(value) => {
setJsonFileText(value);
Expand Down
6 changes: 2 additions & 4 deletions docs/src/components/Header/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ export default async function Header() {
<header className="flex flex-col items-center bg-gray-100 p-2 sm:p-6 md:p-10">
<div className="mb-2">
<Image
src={"/logo.png"}
src="/logo.png"
alt="logo"
width={64}
height={64}
Expand All @@ -24,9 +24,7 @@ export default async function Header() {
{scopedT("Read the")}{" "}
<Link
className="mb-10 text-blue-500 hover:underline"
href={
"https://github.com/gabriel-logan/Azure-translator-code/blob/main/README.md"
}
href="https://github.com/gabriel-logan/Azure-translator-code/blob/main/README.md"
target="_blank"
>
README.md{" "}
Expand Down
Loading

0 comments on commit 1965a2b

Please sign in to comment.