UNPKG

@khoativi/nestjs-class-validator-i18n

Version:

NestJS integration for class-validator with i18n support using Accept-Language headers and customizable locale files.

40 lines 1.49 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.I18n = void 0; const fs_1 = require("fs"); const path_1 = require("path"); class I18n { fallback; cache = new Map(); constructor(fallback = 'en') { this.fallback = fallback; const fallbackMessages = this.readMessagesFile(fallback); this.cache.set(fallback, fallbackMessages); } load(lang) { if (this.cache.has(lang)) return this.cache.get(lang); const filePath = (0, path_1.resolve)(__dirname, 'messages', `${lang}.json`); if ((0, fs_1.existsSync)(filePath)) { const messages = JSON.parse((0, fs_1.readFileSync)(filePath, 'utf8')); this.cache.set(lang, messages); return messages; } return this.cache.get(this.fallback); } translate(lang, key, property, constraints) { const messages = this.load(lang); const template = messages[key] || this.cache.get(this.fallback)?.[key] || key; return template .replace('$property', property) .replace(/\$constraint(\d+)/g, (_, i) => String(constraints[+i - 1])); } readMessagesFile(lang) { const filePath = (0, path_1.resolve)(__dirname, 'messages', `${lang}.json`); if (!(0, fs_1.existsSync)(filePath)) return {}; return JSON.parse((0, fs_1.readFileSync)(filePath, 'utf8')); } } exports.I18n = I18n; //# sourceMappingURL=i18n.js.map