Skip to content
Permalink
Newer
Older
100644 89 lines (80 sloc) 2.23 KB
October 19, 2023 16:49
1
export async function onRequestPost(context: RequestContext) {
2
if (!context.data.departments)
3
return new Response('{"error":"Not in any departments"}', {
4
headers: {
5
"content-type": "application/json",
6
},
7
status: 403,
8
});
9
10
const { departments, end, reason, start } = context.data.body;
11
12
if (
13
!Array.isArray(departments) ||
14
!departments.length ||
15
typeof end !== "string" ||
16
typeof reason !== "string" ||
17
typeof start !== "string"
18
)
19
return new Response('{"error":"Invalid notice"}', {
20
headers: {
21
"content-type": "application/json",
22
},
23
status: 400,
24
});
25
26
const endDate = new Date(end);
27
const startDate = new Date(start);
28
const now = new Date();
29
30
if (
31
isNaN(endDate.getFullYear()) ||
32
isNaN(startDate.getFullYear()) ||
33
endDate.getFullYear() < now.getFullYear() ||
34
endDate.getFullYear() > now.getFullYear() + 1 ||
35
startDate.getFullYear() < now.getFullYear() ||
36
startDate.getFullYear() > now.getFullYear() + 1 ||
37
endDate.valueOf() < startDate.valueOf()
38
)
39
return new Response('{"error":"Dates are invalid"}', {
40
headers: {
41
"content-type": "application/json",
42
},
43
status: 400,
44
});
45
October 19, 2023 16:50
46
if (!departments.every((d) => context.data.departments.includes(d)))
47
return new Response(
48
'{"error":"Cannot file a notice in a department you are not part of"}',
49
{
50
headers: {
51
"content-type": "application/json",
52
},
53
status: 400,
54
}
55
);
October 19, 2023 16:49
56
57
const inactivityId =
58
context.data.current_user.id +
59
(context.request.headers.get("cf-ray") as string).split("-")[0] +
60
Date.now().toString();
61
October 19, 2023 16:50
62
await context.env.DATA.put(
63
`inactivity_${inactivityId}`,
64
JSON.stringify({
65
created_at: Date.now(),
66
departments,
67
end,
68
reason,
69
start,
70
user: {
71
id: context.data.current_user.id,
72
username: context.data.current_user.username,
73
},
74
}),
75
{
76
expirationTtl: 63072000,
77
}
78
);
79
80
await context.env.D1.prepare(
81
"INSERT INTO inactivity_notices (created_at, id, user) VALUES (?, ?, ?);"
82
)
83
.bind(Date.now(), inactivityId, context.data.current_user.id)
84
.run();
October 19, 2023 16:49
85
86
return new Response(null, {
87
status: 204,
88
});
89
}