-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
72 lines (50 loc) · 1.73 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
"use strict";
// P A C K A G E S
const color = require("colorette");
const got = require("got");
// U T I L
const apiUrl = "https://api.chew.sh";
// P R O G R A M
module.exports = exports = (siteId, visitDetails) => {
if (!siteId)
return displayError("Your site cannot be tracked without an ID!");
if (!visitDetails)
return; // Gracefully decline to continue
return new Promise(async(resolve) => { // eslint-disable-line no-async-promise-executor
const visitedUrl = `${visitDetails.protocol}://${visitDetails.host}${visitDetails.url}`;
const { protocol } = new URL(visitedUrl);
switch(true) {
case protocol.includes("localhost"):
case protocol.includes(".local"):
resolve(siteId); // Ignore local development
return;
default:
try {
const [visitEmitResponse] = await Promise.all([got.post(apiUrl, {
body: visitDetails,
json: true
})]);
if (!visitEmitResponse.body)
resolve();
else
resolve(visitEmitResponse.body);
} catch(visitEmitError) {
resolve(displayError(visitEmitError));
}
}
});
};
// H E L P E R
const displayError = text => {
if (text.toString().includes("40"))
text = text.toString().split("-")[1].trim().replace(/"/g, "");
if (text.toString().includes("50"))
text = "Internal server error, please try once more in a few minutes.";
if (text.toString().includes("socket hang up"))
return;
return process.stdout.write(
color.red("\n▸▸ Chew Error\n") +
color.magenta(`▸▸▸ ${text.toString().split(":")}\n\n`) +
color.cyan(`Check ${color.underline("https://chew.sh/docs")} for integration tips\n`)
);
};