-
Notifications
You must be signed in to change notification settings - Fork 1
/
postmark-webhook-slack.js
88 lines (82 loc) · 2.55 KB
/
postmark-webhook-slack.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
addEventListener('fetch', event => {
event.respondWith(handleRequest(event.request))
})
/**
* gatherResponse awaits and returns a response body as a string.
* Use await gatherResponse(..) in an async function to get the response body
* @param {Response} response
*/
async function gatherResponse(response) {
const { headers } = response;
const contentType = headers.get('content-type') || '';
if (contentType.includes('application/json')) {
return JSON.stringify(await response.json());
} else if (contentType.includes('application/text')) {
return response.text();
} else if (contentType.includes('text/html')) {
return response.text();
} else {
return response.text();
}
}
async function handleRequest(request) {
// check for webhook auth
const headers = request.headers
if (headers.get("auth") !== "SECRET_AUTH_CODE") {
return new Response(":(", {
headers: {'content-type': 'text/plain'},
status: 401
})
}
// check we have a POST request
if (request.method !== "POST") {
return new Response(
"Only POST requests are handled.",
{status: 200}
)
}
try {
// receive input
const data = await request.json()
// get title and feed name
const RecordType = data.RecordType
const Type = data.Type
const MessageID = data.MessageID
const MessageStream = data.MessageStream
const Description = data.Description
const Details = data.Details
const Email = data.Email
const From = data.From
const Subject = data.Subject
const text = `New Alert - ${RecordType}/${Type}\nMessageID: ${MessageID}\nMessageStream: ${MessageStream}\nDescription: ${Description}\nDetails: ${Details}\nEmail: ${Email}\nFrom: ${From}\nSubject: ${Subject}`
const PostmarkJson = JSON.stringify(data, null, 2);
const json = {
"username":"Postmark",
"text": text,
"attachments": [
{
"mrkdwn_in": ["text"],
"color": "#36a64f",
"title": "JSON",
"text": PostmarkJson,
}
]
}
// Start end to slack
const url = '<ENTERURLHERE>';
const init = {
body: JSON.stringify(json),
method: 'POST',
headers: {
'content-type': 'application/json;charset=UTF-8',
},
};
//console.log `${init}`
const response = await fetch(url, init);
const results = await gatherResponse(response);
return new Response(results, init);
// End send to slack
} catch (e) {
return new Response(`Error: ${e}`, {status: 200})
}
}