{"size": 1812, "ext": "js", "max_stars_repo_path": "apps/condo/domains/common/utils/localesLoader.js", "max_stars_repo_name": "open-condo-software/open-condo-platform", "max_stars_repo_stars_event_min_datetime": "2021-12-13T16:30:21.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-05T11:05:22.000Z", "max_issues_repo_path": "apps/condo/domains/common/utils/localesLoader.js", "max_issues_repo_name": "open-condo-software/open-condo-platform", "max_issues_repo_issues_event_min_datetime": "2021-12-10T21:47:39.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-21T21:57:26.000Z", "max_forks_repo_path": "apps/condo/domains/common/utils/localesLoader.js", "max_forks_repo_name": "open-condo-software/open-condo-platform", "max_forks_repo_forks_event_min_datetime": "2022-02-04T21:49:16.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-18T18:39:17.000Z"}
{"max_stars_count": 14, "max_issues_count": 3, "max_forks_count": 2, "avg_line_length": 27.8769230769, "max_line_length": 104, "alphanum_fraction": 0.6346578366}
const path = require('path')
const fs = require('fs')
const process = require('process')
const conf = require('@core/config')
const { get, template, isEmpty } = require('lodash')

const VARIABLE_REGEXP = /{([\s\S]+?)}/g

let translations = {}

const loadTranslations = () => {
    const translationsDir = path.join(process.cwd(), 'lang')
    const localeFolders = fs.readdirSync(translationsDir)
    translations = localeFolders
        .map(languageCode => ({
            [languageCode]: require(path.join(translationsDir, `${languageCode}/${languageCode}.json`)),
        }))
        .reduce((prev, curr) => ({ ...prev, ...curr }))
}

const maybeLoadTranslations = () => {
    if (isEmpty(translations)) {
        loadTranslations()
    }
}

const getTranslations = (lang = conf.DEFAULT_LOCALE) => {
    maybeLoadTranslations()
    return translations[lang] || translations[conf.DEFAULT_LOCALE]
}

const getAvailableLocales = () => {
    maybeLoadTranslations()
    return Object.keys(translations)
}

/**
 * @param {string} code - the translation code written in en.json, ru.json, ...
 * @param {{locale: string?, meta: Object?}?} options
 * @param {string?} options.locale - the language code
 * @param {Object?} options.meta - variables passing to the translation string
 * @returns {string} translated string
 * @example
 * // en.json:
 * {
 *   ...,
 *   "greeting": "Hello, {name}!",
 *   ...,
 * }
 *
 * i18n('greeting', { meta: { name: 'World' } })
 * // => "Hello, World!"
 */
const i18n = (code, options = { locale: conf.DEFAULT_LOCALE, meta: {} }) => {
    maybeLoadTranslations()
    const { locale, meta } = options
    return template(get(translations, [locale, code], code), { interpolate: VARIABLE_REGEXP })(meta)
}

module.exports = {
    getTranslations,
    getAvailableLocales,
    i18n,
}
