-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathentry.ts
129 lines (119 loc) · 2.78 KB
/
entry.ts
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
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
import { label } from "./svg.ts";
import { format } from "https://deno.land/[email protected]/datetime/mod.ts";
function responseSvg(body: string) {
return new Response(body, {
status: 200,
headers: {
"content-type": "image/svg+xml",
},
});
}
const ONE_DAY = 1000 * 60 * 60 * 24;
function createDdayLabel(
from: number | null,
to: number | null,
now: number,
offset: number,
): string {
if (from && to) {
if (from > to) {
[from, to] = [to, from]; // swap
}
const text = `${format(new Date(from + offset), "yyyy-MM-dd")} ~ ${
format(new Date(to + offset), "yyyy-MM-dd")
}`;
if (now < from) {
const dday = Math.ceil((from - now) / ONE_DAY);
return label([
{
text: text,
},
{
text: `D-${dday}`,
bgColor: "#2A8C82",
},
]);
}
if (now < to + ONE_DAY) {
const dday = Math.max(1, Math.ceil((now - from) / ONE_DAY));
return label([
{
text: text,
},
{
text: `Day ${dday}`,
bgColor: "#05F2AF",
},
]);
}
return label([
{
text: text,
bgColor: "#cccccc",
},
]);
}
if (from) {
const text = `${format(new Date(from + offset), "yyyy-MM-dd")}`;
if (now < from) {
const dday = Math.ceil((from - now) / ONE_DAY);
return label([
{
text: text,
},
{
text: `D-${dday}`,
bgColor: "#2A8C82",
},
]);
}
if (now < from + ONE_DAY) {
return label([
{
text: text,
},
{
text: `D-Day`,
bgColor: "#05F2AF",
},
]);
}
return label([
{
text: text,
bgColor: "#cccccc",
},
]);
}
return label([{ text: "D-Day", bgColor: "#05F2AF" }]);
}
addEventListener("fetch", (event) => {
try {
const url = new URL(event.request.url);
const path = url.pathname.replace(/^\/|\/$/g, "");
const args = path.split("/");
switch (args[0]) {
case "dday": {
const offset = +(url.searchParams.get("offset") ?? 0);
const from = args[1] ? new Date(args[1]).getTime() - offset : null;
const to = args[2] ? new Date(args[2]).getTime() - offset : null;
const now = +(url.searchParams.get("now") ?? Date.now());
event.respondWith(
responseSvg(createDdayLabel(from, to, now, offset)),
);
return;
}
case "error": {
throw new Error("error");
}
}
event.respondWith(
responseSvg(label([{ text: "badge.dist.be", bgColor: "#4D86DB" }])),
);
} catch (e) {
console.warn("[error]", e);
event.respondWith(
responseSvg(label([{ text: "#Error", bgColor: "#D95436" }])),
);
}
});