💾 Archived View for iich.space › src › modules › mission-control › i18n.ts captured on 2022-03-01 at 16:04:47.

View Raw

More Information

⬅️ Previous capture (2021-12-03)

-=-=-=-=-=-=-

import { join } from 'path';
import { URL } from 'url';

import { createLogger } from '../log';

export type TranslateFunction = (
  token: string,
  ...args: Array<string | number>
) => string;

type Locale = Record<string, string>;
type LocaleFlorp = Record<string, Locale>;

const log = createLogger();

export const getLocaleFromUrl = (url: URL): string => {
  const [locale] = url.hostname.split('.');

  if (locale.length === 2) {
    return locale;
  }

  return 'default';
};

export class I18n {
  defaultLocale: string;
  lists: Record<string, Locale>;

  constructor(locales: Array<string>, directory: string) {
    this.defaultLocale = locales[0];
    this.lists = locales.reduce((acc, locale) => {
      const path = join(process.cwd(), directory, `${locale}.json`);
      acc[locale] = require(path);
      return acc;
    }, {} as LocaleFlorp);
  }

  find(locale: string, token: string): string {
    const list = this.lists[locale];

    if (list !== undefined && list[token] !== undefined) {
      return list[token];
    }

    const fallback = this.lists[this.defaultLocale];

    if (fallback !== undefined && fallback[token] !== undefined) {
      return fallback[token];
    }

    log.debug(`missing token [${locale}] ${token}`);

    return token;
  }

  t(locale: string, token: string, ...args: Array<string | number>): string {
    const template = this.find(locale, token);

    return args.reduce<string>(
      (value, arg, n) => value.replace(`${n}`, arg.toString()),
      template,
    );
  }

  createT(locale: string): TranslateFunction {
    return (token: string, ...args: Array<string | number>) =>
      this.t(locale, token, ...args);
  }
}