-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathworker.js
More file actions
88 lines (72 loc) · 2.32 KB
/
worker.js
File metadata and controls
88 lines (72 loc) · 2.32 KB
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
import { enforceRateLimit } from "./middleware/rateLimit";
import { serveDefaultPage } from "./pages/defaultPage";
import { handleProfileRoute } from "./routes/profileRoute";
import { handleUuidRoute } from "./routes/uuidRoute";
import { internalError, notFound } from "./utils/responses";
const ROBOTS_POLICY = "noindex, nofollow, noarchive, nosnippet, noimageindex, notranslate";
const ROUTE_HANDLERS = {
uuid: handleUuidRoute,
profile: handleProfileRoute
};
function withRobotsBlocked(response) {
const headers = new Headers(response.headers);
headers.set("X-Robots-Tag", ROBOTS_POLICY);
return new Response(response.body, {
status: response.status,
statusText: response.statusText,
headers
});
}
function robotsTxtResponse() {
return new Response("User-agent: *\nDisallow: /\n", {
headers: {
"content-type": "text/plain; charset=utf-8",
"cache-control": "public, max-age=3600"
}
});
}
function resolveRoute(pathname) {
if (!pathname || pathname === "/") {
return null;
}
const normalizedPath = pathname.startsWith("/") ? pathname.slice(1) : pathname;
const separatorIndex = normalizedPath.indexOf("/");
if (separatorIndex <= 0) {
return null;
}
const resource = normalizedPath.slice(0, separatorIndex);
const identifier = normalizedPath.slice(separatorIndex + 1);
if (!identifier || identifier.includes("/")) {
return null;
}
const handler = ROUTE_HANDLERS[resource];
if (!handler) {
return null;
}
return { handler, identifier };
}
export default {
async fetch(request, env) {
try {
const pathname = new URL(request.url).pathname;
if (pathname === "/robots.txt") {
return withRobotsBlocked(robotsTxtResponse());
}
if (pathname === "/") {
return withRobotsBlocked(serveDefaultPage(request));
}
const route = resolveRoute(pathname);
if (!route) {
return withRobotsBlocked(notFound("Route not found"));
}
const rateLimitedResponse = await enforceRateLimit(request, env);
if (rateLimitedResponse) {
return withRobotsBlocked(rateLimitedResponse);
}
return withRobotsBlocked(await route.handler(route.identifier, env));
} catch (error) {
console.error("Unhandled worker error", error);
return withRobotsBlocked(internalError());
}
}
};