forked from probot/adapter-aws-lambda-serverless
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
108 lines (94 loc) · 2.64 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
107
108
const { Probot } = require("probot");
const { resolve } = require("probot/lib/helpers/resolve-app-function");
const { findPrivateKey } = require("probot/lib/helpers/get-private-key");
const { template } = require("./views/probot");
let probot;
const loadProbot = (appFn) => {
probot =
probot ||
new Probot({
id: process.env.APP_ID,
secret: process.env.WEBHOOK_SECRET,
privateKey: findPrivateKey(),
});
if (typeof appFn === "string") {
appFn = resolve(appFn);
}
probot.load(appFn);
return probot;
};
const lowerCaseKeys = (obj = {}) =>
Object.keys(obj).reduce(
(accumulator, key) =>
Object.assign(accumulator, { [key.toLocaleLowerCase()]: obj[key] }),
{}
);
module.exports.serverless = (appFn) => {
return async (event, context) => {
// 🤖 A friendly homepage if there isn't a payload
if (event.httpMethod === "GET" && event.path === "/probot") {
const res = {
statusCode: 200,
headers: {
"Content-Type": "text/html",
},
body: template,
};
return res;
}
// Otherwise let's listen handle the payload
probot = probot || loadProbot(appFn);
// Ends function immediately after callback
context.callbackWaitsForEmptyEventLoop = false;
// Determine incoming webhook event type
const headers = lowerCaseKeys(event.headers);
const e = headers["x-github-event"];
if (!e) {
return {
statusCode: 400,
body: "X-Github-Event header is missing",
};
}
// If body is expected to be base64 encoded, decode it and continue
if (event.isBase64Encoded) {
event.body = Buffer.from(event.body, "base64").toString("utf8");
}
// Convert the payload to an Object if API Gateway stringifies it
event.body =
typeof event.body === "string" ? JSON.parse(event.body) : event.body;
// Bail for null body
if (!event.body) {
return {
statusCode: 400,
body: "Event body is null.",
};
}
// Do the thing
console.log(
`Received event ${e}${event.body.action ? "." + event.body.action : ""}`
);
if (event) {
try {
await probot.receive({
name: e,
payload: event.body,
});
return {
statusCode: 200,
body: JSON.stringify({
message: `Received ${e}.${event.body.action}`,
}),
};
} catch (err) {
console.error(err);
return {
statusCode: 500,
body: JSON.stringify(err),
};
}
} else {
console.error({ event, context });
throw new Error("unknown error");
}
};
};