-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathindex.js
More file actions
79 lines (57 loc) · 2.08 KB
/
index.js
File metadata and controls
79 lines (57 loc) · 2.08 KB
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
/* -----------------------------------------------------------
MJML4-Lambda
- A simple lambda that accepts mjml + options and returns the generated markup
example:
{
"body": {
"mjml":"<mj-text>hi</mj-text>",
"options":""
}
}
----------------------------------------------------------- */
const os = require('os');
const mjml2html = require('mjml');
const isString = function(val) {
return typeof val === 'string' || ((!!val && typeof val === 'object') && Object.prototype.toString.call(val) === '[object String]');
}
exports.handler = async (event, context, callback) => {
// Log the event details so that they're viewable in the CloudWatch Logs
process.stdout.write(JSON.stringify(event));
// console.log('DATA:', event.body);
const data = isString(event.body) ? JSON.parse(event.body) : event.body;
const htmlOutput = mjml2html(data.mjml, data.options);
// onError
if(htmlOutput.errors.length){
let errorList = JSON.stringify(htmlOutput.errors);
process.stderr.write(errorList);
return callback( errorList, sendRes(500, htmlOutput.html) );
}
// success
return callback(null, sendRes(htmlOutput.errors.length ? 500 : 200, htmlOutput.html) );
};
const sendRes = (status, body) => {
var response = {
statusCode: status,
headers: {
"Access-Control-Allow-Origin":"*",
"Content-Type":"application/json"
},
body: body
};
return response;
};
/* -----------------------------------------------------------
For Local testing only (darwin=mac || win32=windows)
$> node index.js
----------------------------------------------------------- */
if (os.platform() === "darwin" || os.platform() === "win32") {
console.log("~~ TEST MODE ~~");
let mockEvent = {};
mockEvent['body'] = {
"mjml": "<mjml version=\"4.1.2\" lang=\"en\">",
"options":{
"validationLevel": "strict"
}
};
exports.handler(mockEvent, null, (error, result) => { return console.log(error, result) });
};