import mustache from 'mustache'; import { Injectable } from '@travetto/di'; import { RuntimeResources } from '@travetto/runtime'; /** * Mail interpolation engine * * @concrete */ export interface MailInterpolator { /** * Resolved nested templates */ resolveNested(template: string): Promise; /** * Interpolate a string with a given context */ render(text: string, ctx: Record): Promise | string; } @Injectable() export class MustacheInterpolator implements MailInterpolator { /** * Resolved nested templates */ async resolveNested(template: string): Promise { const promises: Promise[] = []; template = template.replace(/[{]{2,3}>\s+(\S+)([.]html)?\s*[}]{2,3}/g, (all: string, name: string) => { promises.push( RuntimeResources.readUTF8(`${name}.html`) // Ensure html file .then(contents => this.resolveNested(contents)) ); return `$%${promises.length - 1}%$`; }); const resolved = await Promise.all(promises); return template.replace(/[$]%(\d+)%[$]/g, (__, idx) => resolved[+idx]); } /** * Interpolate text with data */ render(text: string, data: Record): string { return mustache.render(text, data); } }