All files EmailModule.ts

100% Statements 18/18
100% Branches 0/0
100% Functions 4/4
100% Lines 18/18

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  2x 2x 2x 2x                                       2x   2x       6x 6x 6x             6x       6x       5x         6x 6x 6x 6x 6x 5x      
import nodemailer from 'nodemailer'
import { Commun, ConfigManager } from '@commun/core'
import path from 'path'
import fs from 'fs'
import { promisify } from 'util'
 
export type EmailTemplate = {
  enabled: boolean
  sendFrom?: string
  subject: string
  text: string
}
 
type EmailTemplates = {
  [key: string]: EmailTemplate
}
 
export type EmailConfig = {
  templates: EmailTemplates
  transporter: nodemailer.Transporter,
  sendFrom: string
}
 
let emailModuleOptions: EmailConfig
let emailTemplates: EmailTemplates = {}
 
export const EmailModule = {
  wasSetup: false,
 
  async setup (options: EmailConfig) {
    emailModuleOptions = options
    await registerTemplates()
    await Commun.registerPlugin('emails', {
      config: {
        templates: emailTemplates,
        ...options,
        transporter: undefined
      }
    })
    this.wasSetup = true
  },
 
  getOptions () {
    return emailModuleOptions
  },
 
  getTemplates () {
    return emailTemplates
  }
}
 
async function registerTemplates () {
  const readdir = promisify(fs.readdir)
  const pluginPath = ConfigManager.getPluginPath('emails')
  const templatesPath = path.join(pluginPath, 'templates')
  const templates = await readdir(templatesPath)
  for (const template of templates) {
    emailTemplates[template.replace(/\.json$/, '')] = require(path.join(templatesPath, template))
  }
}