JaBa/helpers/languages.js

52 lines
1.2 KiB
JavaScript
Raw Normal View History

2024-12-05 20:15:07 +05:00
import { use, init, getFixedT } from "i18next";
import Backend from "i18next-fs-backend";
import { join, resolve } from "path";
import { promises as fs } from "fs";
2022-01-04 02:18:28 +05:00
async function walkDirectory(dir, namespaces = [], folderName = "") {
const files = await fs.readdir(dir);
const languages = [];
for (const file of files) {
2024-12-05 20:15:07 +05:00
const stat = await fs.stat(join(dir, file));
2022-01-04 02:18:28 +05:00
if (stat.isDirectory()) {
const isLanguage = file.includes("-");
if (isLanguage) languages.push(file);
2024-12-05 20:15:07 +05:00
const folder = await walkDirectory(join(dir, file), namespaces, isLanguage ? "" : `${file}/`);
2022-01-04 02:18:28 +05:00
namespaces = folder.namespaces;
} else {
namespaces.push(`${folderName}${file.substr(0, file.length - 5)}`);
2022-01-13 00:26:23 +05:00
}
}
2022-01-04 02:18:28 +05:00
return {
namespaces: [...new Set(namespaces)],
languages,
2022-01-04 02:18:28 +05:00
};
2022-01-13 00:26:23 +05:00
}
2022-01-04 02:18:28 +05:00
2024-12-05 20:15:07 +05:00
export default async () => {
2022-01-04 02:18:28 +05:00
const options = {
2024-12-05 20:15:07 +05:00
loadPath: resolve(__dirname, "../languages/{{lng}}/{{ns}}.json"),
2022-01-04 02:18:28 +05:00
};
2024-12-05 20:15:07 +05:00
const { namespaces, languages } = await walkDirectory(resolve(__dirname, "../languages/"));
2022-01-04 02:18:28 +05:00
2024-12-05 20:15:07 +05:00
use(Backend);
2022-01-04 02:18:28 +05:00
2024-12-05 20:15:07 +05:00
await init({
2022-01-04 02:18:28 +05:00
backend: options,
debug: false,
2023-06-26 17:25:17 +05:00
fallbackLng: "en-US",
2022-01-04 02:18:28 +05:00
initImmediate: false,
interpolation: { escapeValue: false },
load: "all",
ns: namespaces,
preload: languages,
2022-01-04 02:18:28 +05:00
});
2024-12-05 20:15:07 +05:00
return new Map(languages.map(item => [item, getFixedT(item)]));
2023-07-05 00:58:06 +05:00
};