File: /var/www/indoadvisory_new/web/webapp/middleware/i18n.js
const fs = require('fs');
const path = require('path');
// Load translation files
const loadTranslations = () => {
const translations = {};
const localesDir = path.join(__dirname, '..', 'locales');
try {
const localeFiles = fs.readdirSync(localesDir);
for (const file of localeFiles) {
if (file.endsWith('.json')) {
const locale = path.basename(file, '.json');
const filePath = path.join(localesDir, file);
translations[locale] = JSON.parse(fs.readFileSync(filePath, 'utf8'));
}
}
} catch (error) {
console.warn('Could not load translations:', error.message);
}
return translations;
};
let translations = loadTranslations();
// Internationalization middleware
const i18n = (req, res, next) => {
// Get language from query parameter, session, or default to English
let lang = req.query.lang || req.session.lang || 'en';
// Validate language (only allow en or id)
if (!['en', 'id'].includes(lang)) {
lang = 'en';
}
// Store language in session
req.session.lang = lang;
// Translation function
req.__ = (key, params = {}) => {
const translation = translations[lang] && translations[lang][key];
if (!translation) {
// Fallback to English if key not found in current language
const fallback = translations['en'] && translations['en'][key];
if (!fallback) {
console.warn(`Translation key not found: ${key}`);
return key; // Return the key itself if no translation found
}
return interpolate(fallback, params);
}
return interpolate(translation, params);
};
// Make translation function available in templates
res.locals.__ = req.__;
res.locals.currentLang = lang;
res.locals.otherLang = lang === 'en' ? 'id' : 'en';
next();
};
// Simple string interpolation
const interpolate = (template, params) => {
return template.replace(/\{\{(\w+)\}\}/g, (match, key) => {
return params[key] || match;
});
};
// Get bilingual content based on current language
const getBilingualContent = (req, contentEn, contentId) => {
const lang = req.session.lang || 'en';
return lang === 'id' ? (contentId || contentEn) : contentEn;
};
// Format bilingual content for database queries
const formatBilingualQuery = (fields, lang = 'en') => {
return fields.map(field => {
if (field.includes('_en') || field.includes('_id')) {
const baseField = field.replace('_en', '').replace('_id', '');
const suffix = lang === 'id' ? '_id' : '_en';
return `${baseField}${suffix} as ${baseField}`;
}
return field;
}).join(', ');
};
// Reload translations (useful for development)
const reloadTranslations = () => {
translations = loadTranslations();
console.log('Translations reloaded');
};
module.exports = {
i18n,
getBilingualContent,
formatBilingualQuery,
reloadTranslations
};