-
Notifications
You must be signed in to change notification settings - Fork 9
/
index.js
63 lines (55 loc) · 2.01 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
const request = require('request');
const tableify = require('tableify');
const parseSnsRecord = snsRecord => ({
MessageId: snsRecord.MessageId,
TopicArn: snsRecord.TopicArn,
Subject: snsRecord.Subject,
Message: snsRecord.Message ? JSON.parse(snsRecord.Message) : null,
});
const formatAsHtmlTables = eventRecords => eventRecords
.filter(record => record.Sns)
.map(record => parseSnsRecord(record.Sns))
.map(record => tableify(record));
const sendToMicrosoftTeams = (snsRecordStrings, callback) => {
// Prepare HTTP request
const httpRequestConfig = {
uri: process.env.TEAMS_WEB_HOOK_URL,
method: 'POST',
json: {
text: snsRecordStrings.toString(),
},
};
// Send HTTP request
console.log('[INFO] Posting to Webhook...');
request(httpRequestConfig, (error, response) => {
const statusCode = (response && response.statusCode) ? response.statusCode : null;
const logLevel = (statusCode === 200) ? 'INFO' : 'ERROR';
const logMessage = `[${logLevel}] Posting to Webhook...done. HTTP status code: [${statusCode}]`;
console.log(logMessage, error || '');
callback(error, 'done');
});
};
//
// AWS Lambda handler (main function).
//
// Receives messages from an SNS topic containing SNS records.
// Formats them as HTML tables.
// Forwards them to Microsoft Teams via a Webhook.
//
exports.handler = (event, context, callback) => {
console.log('[INFO] Handler invoked. Event details:', event);
// Extract event payload (records)
const eventRecords = (event.Records ? event.Records : []);
console.log('[INFO] Event records: ', eventRecords);
// Format SNS records as HTML tables
const snsRecordStrings = formatAsHtmlTables(eventRecords);
// Abort if we didn't receive proper SNS records
if (snsRecordStrings.length === 0) {
const errorMessage = 'Ignoring event because it does not contain any SNS records';
console.log(`[ERROR] ${errorMessage}`);
callback(errorMessage);
return;
}
// Send HTTP request
sendToMicrosoftTeams(snsRecordStrings, callback);
};