-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathindex.js
106 lines (95 loc) · 2.84 KB
/
index.js
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
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
"use strict";
const fs = require("fs");
const path = require("path");
const mjml2html = require("mjml");
const tempWrite = require("temp-write");
const opn = require("opn");
class ServerlessSesMjmlPlugin {
constructor(serverless, options) {
this.serverless = serverless;
this.options = options;
this.commands = {
"preview-template": {
usage: "Preview your html template in a browser",
options: {
template: {
usage:
"Specify the template you want to preview (e.g. --template myTemplate)",
shortcut: "t",
required: true
}
},
lifecycleEvents: ["preview"]
}
};
this.hooks = {
"preview-template:preview": () => this.buildAndPreview(),
"before:deploy:deploy": () => this.addResources(),
};
}
buildAndPreview() {
const { location, templates } = this.getConfig();
const template = templates.find(
({ name }) => name === this.options.template
);
const { HtmlPart, TextPart } = this.generateParts(location, template);
const filePath = tempWrite.sync(HtmlPart || TextPart, "template.html");
this.serverless.cli.log(`Template Created - ${filePath}`);
opn(filePath);
return filePath;
}
addResources() {
const config = this.getConfig();
const resources = this.serverless.service.provider
.compiledCloudFormationTemplate.Resources;
Object.assign(resources, this.getTemplateResources(config));
}
getConfig() {
return Object.assign(
{
location: "email-templates",
templates: []
},
this.serverless.service.custom.sesTemplates
);
}
getTemplateResources({ location, templates }) {
return templates.reduce(
(acc, template) =>
Object.assign({}, acc, {
[`SESTemplate${this.getCfnName(template.name)}`]: {
Type: 'AWS::SES::Template',
Properties: {
Template: this.generateParts(location, template)
}
}
}),
{}
);
}
generateParts(location, { name, subject, mjml, text }) {
const textString = fs.readFileSync(path.join(location, text), "utf8");
const mjmlString = fs.readFileSync(path.join(location, mjml), "utf8");
const htmlString = mjml2html(mjmlString, {
keepComments: false,
minify: true
});
if (htmlString.errors && htmlString.errors.length) {
htmlString.errors.forEach(error => {
this.serverless.cli.log(JSON.stringify(error));
});
throw new this.serverless.classes.Error("Cannot process invalid mjml");
} else {
return {
TemplateName: name,
SubjectPart: subject,
HtmlPart: htmlString.html,
TextPart: textString
};
}
}
getCfnName(name) {
return name.replace(/[^a-zA-Z0-9]/g, "");
}
}
module.exports = ServerlessSesMjmlPlugin;