@454creative/easy-email
Version:
A framework-agnostic email service library for Node.js with observability and monitoring
139 lines • 5.65 kB
JavaScript
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.TemplateEngine = void 0;
const fs_1 = __importDefault(require("fs"));
const path_1 = __importDefault(require("path"));
const errors_1 = require("../errors");
const logger_1 = require("../utils/logger");
class TemplateEngine {
constructor(templatesDir, options = {}) {
var _a;
this.templatesDir = templatesDir;
this.templates = new Map();
this.compiledTemplates = new Map();
this.options = {
engine: options.engine || 'handlebars',
cache: (_a = options.cache) !== null && _a !== void 0 ? _a : true,
defaultLocale: options.defaultLocale || 'en',
};
this.logger = logger_1.Logger.getInstance();
this.validateTemplatesDir();
}
validateTemplatesDir() {
if (!fs_1.default.existsSync(this.templatesDir)) {
throw new errors_1.TemplateError(`Templates directory not found: ${this.templatesDir}`);
}
}
getTemplatePath(name, locale) {
const localeDir = locale || this.options.defaultLocale;
const templatePath = path_1.default.join(this.templatesDir, localeDir, `${name}.${this.options.engine}`);
if (!fs_1.default.existsSync(templatePath)) {
throw new errors_1.TemplateNotFoundError(name, { locale, path: templatePath });
}
return templatePath;
}
loadTemplate(name, locale) {
const cacheKey = `${locale || this.options.defaultLocale}:${name}`;
if (this.options.cache && this.templates.has(cacheKey)) {
return this.templates.get(cacheKey);
}
const templatePath = this.getTemplatePath(name, locale);
try {
const template = fs_1.default.readFileSync(templatePath, 'utf-8');
if (this.options.cache) {
this.templates.set(cacheKey, template);
}
return template;
}
catch (error) {
throw new errors_1.TemplateError(`Failed to load template: ${name}`, { error });
}
}
compileTemplate(template) {
try {
switch (this.options.engine) {
case 'handlebars':
return this.compileHandlebars(template);
case 'ejs':
return this.compileEjs(template);
case 'pug':
return this.compilePug(template);
default:
throw new errors_1.InvalidTemplateError(`Unsupported template engine: ${this.options.engine}`);
}
}
catch (error) {
throw new errors_1.InvalidTemplateError(`Failed to compile template`, { error });
}
}
compileHandlebars(template) {
// TODO: In a real implementation, you would import and use the Handlebars library
return (context) => {
return template.replace(/\{\{([^}]+)\}\}/g, (_match, key) => {
return context[key.trim()] || '';
});
};
}
compileEjs(template) {
// TODO: In a real implementation, you would import and use the EJS library
return (context) => {
return template.replace(/<%=([^%>]+)%>/g, (_match, key) => {
return context[key.trim()] || '';
});
};
}
compilePug(_template) {
// TODO: In a real implementation, you would import and use the Pug library
throw new Error('Pug compilation not implemented');
}
render(name, context, locale) {
this.logger.debug(`Rendering template: ${name}`, { locale, context });
try {
const template = this.loadTemplate(name, locale);
const cacheKey = `${locale || this.options.defaultLocale}:${name}`;
let compiledTemplate;
if (this.options.cache && this.compiledTemplates.has(cacheKey)) {
compiledTemplate = this.compiledTemplates.get(cacheKey);
}
else {
compiledTemplate = this.compileTemplate(template);
if (this.options.cache) {
this.compiledTemplates.set(cacheKey, compiledTemplate);
}
}
const result = compiledTemplate(context);
this.logger.debug(`Template rendered successfully: ${name}`);
return result;
}
catch (error) {
this.logger.error(`Failed to render template: ${name}`, { error, locale, context });
throw error;
}
}
clearCache() {
this.templates.clear();
this.compiledTemplates.clear();
this.logger.debug('Template cache cleared');
}
setOptions(options) {
this.options = Object.assign(Object.assign({}, this.options), options);
this.logger.debug('Template options updated', { options });
}
getAvailableTemplates(locale) {
const localeDir = path_1.default.join(this.templatesDir, locale || this.options.defaultLocale);
try {
return fs_1.default
.readdirSync(localeDir)
.filter(file => file.endsWith(`.${this.options.engine}`))
.map(file => path_1.default.basename(file, `.${this.options.engine}`));
}
catch (error) {
throw new errors_1.TemplateError(`Failed to list templates`, { error, locale });
}
}
}
exports.TemplateEngine = TemplateEngine;
//# sourceMappingURL=template-engine.js.map