-
Notifications
You must be signed in to change notification settings - Fork 0
/
middleware.ts
77 lines (68 loc) · 2.19 KB
/
middleware.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
export default function middleware(
request: Request,
context: { waitUntil(promise: Promise<unknown>): void }
) {
const { pathname } = new URL(request.url);
const match = pathname.match(/^\/(?<summer>s?)(?<year>(\d{2})?)$/);
if (match) {
const baseUrl = "https://reg.uci.edu/calendars/quarterly";
const groups = match.groups;
const summer = !!groups.summer;
const year = parseInt(groups.year);
// Current/Next Summer Calendar (ucicalendar.com/s)
if (summer && !year) {
incrCounter(context);
return Response.redirect("https://summer.uci.edu/calendar/", 307);
}
// Current/Next Yearly Calendar (ucicalendar.com/)
if (!year) {
incrCounter(context);
return Response.redirect(
"https://reg.uci.edu/calendars/quarterly/2024-2025/quarterly24-25.html",
307
);
}
// Summer Calendar (ucicalendar.com/s<year>)
if (summer && year && 15 <= year && year <= 24) {
const firstYear = String(year - 1).padStart(2, "0");
const secondYear = String(year).padStart(2, "0");
const fullYearRange = `20${firstYear}-20${secondYear}`;
incrCounter(context);
return Response.redirect(
`${baseUrl}/${fullYearRange}/summer${secondYear}.html`
);
}
// Yearly Calendar (ucicalendar.com/<year>)
if (year && 8 <= year && year <= 25) {
const firstYear = String(year).padStart(2, "0");
const secondYear = String(year + 1).padStart(2, "0");
const yearRange = `${firstYear}-${secondYear}`;
const fullYearRange = `20${firstYear}-20${secondYear}`;
incrCounter(context);
return Response.redirect(
`${baseUrl}/${fullYearRange}/quarterly${yearRange}.html`
);
}
return Response.redirect(new URL("/format", request.url).toString(), 307);
} else {
return new Response(null, {
headers: {
"x-middleware-next": "1",
},
});
}
}
const incrCounter = (
context: {
waitUntil(promise: Promise<unknown>): void;
},
key = "count"
) => {
context.waitUntil(
fetch(`${process.env.UPSTASH_REDIS_REST_URL}/incr/${key}`, {
headers: {
Authorization: `Bearer ${process.env.UPSTASH_REDIS_REST_TOKEN}`,
},
})
);
};