Skip to content

Commit

Permalink
Cache the theme file to avoid redundant reads
Browse files Browse the repository at this point in the history
Thanks to @alessioalex for the suggestion in #3!
  • Loading branch information
eladnava committed May 26, 2016
1 parent 0d9bc1d commit 0385c14
Showing 1 changed file with 16 additions and 18 deletions.
34 changes: 16 additions & 18 deletions index.js
Expand Up @@ -5,21 +5,8 @@ var juice = require('juice');
// Package constructor
function Mailgen(options) {
// Set options as instance members
this.theme = options.theme;
this.product = options.product;

// No theme provided - use default
if (!this.theme) {
this.theme = 'default';
}

// Build path to theme template
this.templatePath = __dirname + '/themes/' + this.theme + '.html';

// Bad theme?
if (!fs.existsSync(this.templatePath)) {
throw new Error('You have specified an invalid theme.');
}
this.theme = options.theme || 'default';

// No product?
if (!this.product || typeof this.product !== 'object') {
Expand All @@ -30,6 +17,17 @@ function Mailgen(options) {
if (!this.product.name || !this.product.link) {
throw new Error('Please provide the product name and link.');
}

// Build path to theme's template file
var templatePath = __dirname + '/themes/' + this.theme + '.html';

// Bad path?
if (!fs.existsSync(templatePath)) {
throw new Error('You have specified an invalid theme.');
}

// Load template (sync) and cache it for later
this.template = fs.readFileSync(templatePath, 'utf8');
}

// HTML e-mail generator
Expand All @@ -47,9 +45,6 @@ Mailgen.prototype.generate = function (params) {
throw new Error('Please provide the `body` parameter as an object.');
}

// Load it (sync)
var output = fs.readFileSync(this.templatePath, 'utf8');

// Prepare data to be passed to ejs engine
var templateData = {
product: this.product
Expand All @@ -59,7 +54,10 @@ Mailgen.prototype.generate = function (params) {
for (var k in body) {
templateData[k] = body[k];
}


// Fetch cached theme HTML
var output = this.template;

// Render the template with ejs
output = ejs.render(output, templateData);

Expand Down

0 comments on commit 0385c14

Please sign in to comment.