forked from denoland/docs
-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.ts
157 lines (140 loc) · 3.79 KB
/
server.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
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
import Server from "lume/core/server.ts";
import REDIRECTS from "./_redirects.json" with { type: "json" };
import GO_LINKS from "./go.json" with { type: "json" };
import REDIRECT_LINKS from "./oldurls.json" with { type: "json" };
import {
type Event,
formatStatus,
GA4Report,
isDocument,
isRedirect,
isServerError,
} from "ga4";
import { apiDocumentContentTypeMiddleware } from "./middleware.ts";
const server = new Server({
port: 8000,
root: ".",
});
REDIRECTS["/api/"] = "/api/deno/";
for (const [name, url] of Object.entries(GO_LINKS)) {
REDIRECTS[`/go/${name}/`] = url;
}
for (const [name, url] of Object.entries(REDIRECT_LINKS)) {
REDIRECTS[name] = url;
}
const GA4_MEASUREMENT_ID = Deno.env.get("GA4_MEASUREMENT_ID");
function ga4(
request: Request,
remoteAddr: Deno.Addr,
response: Response,
error?: unknown,
) {
Promise.resolve().then(async () => {
if (request.method !== "GET") {
return;
}
if (!isDocument(request, response) && error == null) {
return;
}
let event: Event | null = null;
if (isRedirect(response)) {
const redirectLocation = response.headers.get("location");
event = { name: "redirect", params: { redirectLocation } };
} else {
const fetchDest = request.headers.get("sec-fetch-dest");
if (fetchDest) {
if (/^(document|i?frame|video)$/.test(fetchDest)) {
event = { name: "page_view", params: {} };
} else {
event = null; // Don't report asset downloads.
}
} else {
const contentType = response.headers.get("content-type");
if (contentType != null && /text\/html/.test(contentType)) {
event = { name: "page_view", params: {} }; // Probably an old browser.
} else {
event = { name: "file_download", params: {} };
}
}
}
if (event == null && error == null) {
return;
}
if (event != null) {
// And add some extra HTTP metadata to the event.
event.params.httpRequestMethod = request.method;
event.params.httpResponseStatus = formatStatus(response);
event.params.clientType = "browser";
}
// If an exception was thrown, build a separate event to report it.
let exceptionEvent;
if (error != null) {
exceptionEvent = {
name: "exception",
params: {
description: String(error),
fatal: isServerError(response),
},
};
} else {
exceptionEvent = undefined;
}
// Create basic report.
const report = new GA4Report({
measurementId: GA4_MEASUREMENT_ID,
request,
response,
conn: {
remoteAddr,
localAddr: server.addr!,
},
});
// Override the default (page_view) event.
report.event = event;
// Add the exception event, if any.
if (exceptionEvent != null) {
report.events.push(exceptionEvent);
}
await report.send();
}).catch((err) => {
console.error(`Internal error: ${err}`);
});
}
server.use(async (req, next, info) => {
let err;
let res: Response;
try {
const url = new URL(req.url, "http://localhost:8000");
const redirect = REDIRECTS[url.pathname] ||
(url.pathname.endsWith("/")
? REDIRECTS[url.pathname.slice(0, -1)]
: REDIRECTS[url.pathname + "/"]);
if (redirect) {
res = new Response(null, {
status: 301,
headers: {
"Location": redirect,
},
});
} else {
res = await next(req);
}
return res;
} catch (e) {
res = new Response("Internal Server Error", {
status: 500,
});
err = e;
throw e;
} finally {
ga4(
req,
info.remoteAddr,
res!,
err,
);
}
});
server.use(apiDocumentContentTypeMiddleware);
server.start();
console.log("Listening on http://localhost:8000");