All files EmailClient.ts

90% Statements 18/20
84.62% Branches 11/13
100% Functions 2/2
90% Lines 18/20

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 482x 2x           2x   6x 1x   5x 5x 5x 5x 2x     3x         3x   3x         3x                   6x 8x 8x   6x    
import { EmailModule } from './EmailModule'
import { Commun } from '@commun/core'
 
type TemplateVariables = {
  [key: string]: any
}
 
export const EmailClient = {
  sendEmail (templateName: string, to: string, templateVariables: TemplateVariables = {}) {
    if (!EmailModule.wasSetup) {
      return
    }
    const { sendFrom, transporter } = EmailModule.getOptions()
    const templates = EmailModule.getTemplates()
    const template = templates[templateName]
    if (!template || !template.enabled) {
      return
    }
 
    Iif (!transporter) {
      console.warn('Skipping email send, transporter not set')
      return
    }
 
    const communOptions = Commun.getOptions()
 
    const templateVars = {
      ...communOptions,
      ...templateVariables,
    }
 
    return transporter.sendMail({
      from: template.sendFrom || sendFrom,
      to,
      subject: parseTemplateVariables(template.subject, templateVars),
      text: parseTemplateVariables(template.text, templateVars),
    })
  },
}
 
function parseTemplateVariables (template: string, variables: TemplateVariables) {
  for (const [key, value] of Object.entries(variables)) {
    const regexp = RegExp(`{\s*${key}\s*}`, 'g')
    template = template.replace(regexp, (value || '').toString())
  }
  return template
}