UNPKG

@ptkdev/node-module-boilerplate

Version:

Create your npm library with this user friendly boilerplate. Use this respository as template for your new node library/module

73 lines 2.8 kB
"use strict"; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", { value: true }); exports.translate = void 0; /** * Translate * ===================== * * @contributors: Patryk Rzucidło [@ptkdev] <support@ptkdev.io> (https://ptk.dev) * * @license: MIT License * */ const config_1 = __importDefault(require("../configs/config")); const translations_1 = __importDefault(require("../routes/translations")); /** * Replace Params * ===================== * If translation text is: hi {name} how are you? * This function replace {name} token with correct value * * @param {string} text - text of current phrase to translate (mandatory) * @param {Object} language_params - object with token to replace, example: {name:"alex"} (mandatory) * * @return {string} text - text with replaced token * */ const replaceParams = (text, language_params) => { for (const [key, value] of Object.entries(language_params)) { text = text.replace(`{{${key}}}`, value); } return text; }; /** * Check * ===================== * Check if exist translation in selected language, if not exist get string of phrase from "en" translation * * @param {string} lang - language from group/user (mandatory) * @param {string} language_id - key of translation phrase from /translations/*.json (mandatory) * * @return {string} text - text of available translation * */ const check = (lang, language_id) => { var _a, _b, _c, _d; return ((_d = (_b = (_a = translations_1.default === null || translations_1.default === void 0 ? void 0 : translations_1.default[lang]) === null || _a === void 0 ? void 0 : _a[language_id]) !== null && _b !== void 0 ? _b : (_c = translations_1.default === null || translations_1.default === void 0 ? void 0 : translations_1.default["en"]) === null || _c === void 0 ? void 0 : _c[language_id]) !== null && _d !== void 0 ? _d : `translation id: ${language_id} in ${lang}.json is undefined`); }; /** * Translate * ===================== * Get correct translation * * @param {string} lang - language from group/user (mandatory) * @param {string} language_id - key of translation phrase from /translations/*.json (mandatory) * @param {Object} language_params - object with token to replace, example: {name:"alex"} (optional) * * @return {string} text - text of available translation * */ const translate = (language_id, language_params) => { let text = ""; text = check(config_1.default.language, language_id); if (language_params) { text = replaceParams(text, language_params); } return text; }; exports.translate = translate; exports.default = translate; //# sourceMappingURL=translate.js.map