All files Email.js

100% Statements 19/19
100% Branches 2/2
100% Functions 7/7
100% Lines 17/17

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 701x 1x 1x 1x 1x               1x     1x                         4x 4x                 1x   1x   1x   1x               3x   3x               1x           1x  
const mjmlLib = require('mjml');
const stampit = require('stampit');
const fetch = require('node-fetch');
const handlebars = require('handlebars');
require('handlebars-helpers')({ handlebars });
 
/**
 * Fetch the template file from a URL
 * @param {string} url
 * @return {Promise<string>}
 */
function getTemplateFile(url) {
  return fetch(url).then(res => res.text()).then(res => res);
}
 
const Email = stampit({
  props: {
    config: undefined,
    feeds: undefined,
    mjmlContent: undefined,
  },
 
  /**
   * Instantiate a new email object
   * @param {{object, array}} config, feeds
   * @return {void}
   */
  init({ config, feeds }) {
    this.config = config;
    this.feeds = feeds;
  },
 
  methods: {
    /**
     * Generate mjmlContent from the config and feeds set in the constructor
     * @returns {Email}
     */
    async generate() {
      const source = await getTemplateFile(this.config.templateUrl);
 
      const template = handlebars.compile(source);
 
      this.mjmlContent = template({ ...this.config, feeds: this.feeds });
 
      return this;
    },
 
    /**
     * Get the MJML email as a string.
     * @return {string}
     */
    async getMjml() {
      this.mjmlContent || await this.generate();
 
      return this.mjmlContent;
    },
 
    /**
     * Get the HTML email as a string.
     * @return {string}
     */
    async getHtml() {
      return mjmlLib(await this.getMjml()).html;
    },
  },
});
 
 
module.exports = Email;