diff options
author | Samuel (Flam3rboy) <github@samuelscheit.com> | 2023-03-30 18:13:34 +0200 |
---|---|---|
committer | GitHub <noreply@github.com> | 2023-03-30 18:13:34 +0200 |
commit | 69ea71aa9e0bd2e5a98904a66fba0ad3745707cb (patch) | |
tree | 807384e6d19111a4e038113854bb28791814a8c7 /src/api/middlewares/Translation.ts | |
parent | SPACEBAR (diff) | |
parent | feat: add DB_LOGGING env (diff) | |
download | server-69ea71aa9e0bd2e5a98904a66fba0ad3745707cb.tar.xz |
Merge pull request #1008 from spacebarchat/dev/samuel
Diffstat (limited to 'src/api/middlewares/Translation.ts')
-rw-r--r-- | src/api/middlewares/Translation.ts | 59 |
1 files changed, 40 insertions, 19 deletions
diff --git a/src/api/middlewares/Translation.ts b/src/api/middlewares/Translation.ts index 60ff4ad7..0ddc56bb 100644 --- a/src/api/middlewares/Translation.ts +++ b/src/api/middlewares/Translation.ts @@ -18,11 +18,20 @@ import fs from "fs"; import path from "path"; -import i18next from "i18next"; -import i18nextMiddleware from "i18next-http-middleware"; -import i18nextBackend from "i18next-node-fs-backend"; +import i18next, { TFunction } from "i18next"; +import i18nextBackend from "i18next-fs-backend"; import { Router } from "express"; +declare global { + // eslint-disable-next-line @typescript-eslint/no-namespace + namespace Express { + interface Request { + t: TFunction; + language?: string; + } + } +} + const ASSET_FOLDER_PATH = path.join(__dirname, "..", "..", "..", "assets"); export async function initTranslation(router: Router) { @@ -34,21 +43,33 @@ export async function initTranslation(router: Router) { .filter((x) => x.endsWith(".json")) .map((x) => x.slice(0, x.length - 5)); - await i18next - .use(i18nextBackend) - .use(i18nextMiddleware.LanguageDetector) - .init({ - preload: languages, - // debug: true, - fallbackLng: "en", - ns, - backend: { - loadPath: - path.join(ASSET_FOLDER_PATH, "locales") + - "/{{lng}}/{{ns}}.json", - }, - load: "all", - }); + await i18next.use(i18nextBackend).init({ + preload: languages, + // debug: true, + fallbackLng: "en", + ns, + backend: { + loadPath: + path.join(ASSET_FOLDER_PATH, "locales") + + "/{{lng}}/{{ns}}.json", + }, + load: "all", + }); + + router.use((req, res, next) => { + let lng = "en"; + if (req.headers["accept-language"]) { + lng = req.headers["accept-language"].split(",")[0]; + } + req.language = lng; - router.use(i18nextMiddleware.handle(i18next, {})); + // eslint-disable-next-line @typescript-eslint/no-explicit-any + req.t = (key: string | string[], options?: any) => { + return i18next.t(key, { + ...options, + lng, + }); + }; + next(); + }); } |