-
Notifications
You must be signed in to change notification settings - Fork 0
/
handler.js
93 lines (84 loc) · 2.28 KB
/
handler.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
"use strict";
const fetch = require("node-fetch");
const { trelloList, trelloCustomFields, zapier } = require(`./config.json`);
const trelloApiKey = process.env.TRELLO_API_KEY;
const trelloApiToken = process.env.TRELLO_API_TOKEN;
const Trello = require("trello");
const trello = new Trello(trelloApiKey, trelloApiToken);
const getCustomFieldsOnCard = async function(cardId) {
try {
const response = await trello.makeRequest(
"get",
`/1/cards/${cardId}/customFieldItems`,
{ webhooks: false }
);
return response;
} catch (err) {
console.error("Failed request to Trello");
}
};
const getScope = function(customFields) {
const scopeField = customFields.find(
el => el.idCustomField === trelloCustomFields.scope.idCustomField
);
if (typeof scopeField !== "undefined") {
return scopeField.value.number;
}
return 0;
};
const zapierPostRequest = async function(url, payload) {
const options = {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify(payload),
};
try {
const response = await fetch(url, options);
console.log(`Successful request to Zapier with URL ${url}`);
return response;
} catch (err) {
console.error(`Failed request to Zapier with URL ${url}`);
}
return null;
};
async function addRowToSheet(body) {
const cardCustomFields = await getCustomFieldsOnCard(
body.action.data.card.id
);
const scope = getScope(cardCustomFields);
if (typeof scope !== "undefined") {
return await zapierPostRequest(zapier.addRowToSheet.url, { ...body, scope });
}
}
const isCardMovedToList = function(listModelId, action) {
const { listAfter, listBefore } = action.data;
return (
action.type === "updateCard" &&
typeof listAfter !== "undefined" &&
typeof listBefore !== "undefined" &&
listAfter.id === listModelId
);
};
async function movedToDone(body) {
if (isCardMovedToList(trelloList.done.modelId, body.action)) {
return await addRowToSheet(body);
}
}
module.exports.webhook = async event => {
try {
if (event.body) {
const body = JSON.parse(event.body);
if (body.action) {
await movedToDone(body);
}
}
} catch (err) {
console.error(err);
} finally {
return {
statusCode: 200,
};
}
};