import { join } from 'path'; import { URL } from 'url'; import { createLogger } from '../log'; export type TranslateFunction = ( token: string, ...args: Array ) => string; type Locale = Record; type LocaleFlorp = Record; 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; constructor(locales: Array, 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 { const template = this.find(locale, token); return args.reduce( (value, arg, n) => value.replace(`$${n}`, arg.toString()), template, ); } createT(locale: string): TranslateFunction { return (token: string, ...args: Array) => this.t(locale, token, ...args); } }