-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathmain.js
77 lines (68 loc) · 2.76 KB
/
main.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
const Apify = require('apify');
const typeCheck = require('type-check').typeCheck;
const Handlebars = require('handlebars');
const rp = require('request-promise');
const querystring = require('querystring');
// Input data attributes types
const INPUT_DATA_TYPES = `{
to: String,
subject: String,
text: Maybe String,
html: Maybe String,
attachResults: Maybe [Object],
textContext: Maybe Object,
}`;
const processHandlebars = (textTemplate, context) => {
const compiler = Handlebars.compile(textTemplate);
const text = compiler(context);
return text;
};
Apify.main(async () => {
// Get input of your act
const input = await Apify.getValue('INPUT');
const { _id: executionId, datasetId } = input;
const data = input.data ? JSON.parse(input.data) : {};
const attachments = [];
// Checks input
if (!(data.text || data.html)) throw new Error('Invalid input data, text or html missing.');
if (!typeCheck(INPUT_DATA_TYPES, data)) {
console.log(`Invalid input:\n${JSON.stringify(input)}\nData types:\n${INPUT_DATA_TYPES}\nAct failed!`);
throw new Error('Invalid input data');
}
// Replace handlebars
const textContext = data.textContext ? Object.assign(data.textContext, { executionId, ...input }) : { executionId, ...input };
const text = data.text ? processHandlebars(data.text, textContext) : null;
const html = data.html ? processHandlebars(data.html, textContext) : null;
const subject = processHandlebars(data.subject, textContext);
// Download results and create attachments
if (data.attachResults) {
for (let attachOpts of data.attachResults) {
const getResultsOpts = Object.assign(attachOpts, { attachment: 1 });
let results;
let fileAttachment;
if (executionId) {
results = await rp(`https://api.apify.com/v1/execs/${executionId}/results?${querystring.stringify(getResultsOpts)}`, { encoding: null });
fileAttachment = {
filename: `${executionId}.${attachOpts.format}`,
data: results.toString('base64'),
}
} else {
results = await rp(`https://api.apify.com/v2/datasets/${datasetId}/items?${querystring.stringify(getResultsOpts)}`, { encoding: null });
fileAttachment = {
filename: `${datasetId}.${attachOpts.format}`,
data: results.toString('base64'),
}
}
attachments.push(fileAttachment)
}
}
// Send mail
const result = await Apify.call('apify/send-mail', {
to: data.to,
subject,
text,
html,
attachments,
});
console.log(result);
});