-
-
Notifications
You must be signed in to change notification settings - Fork 11
Expand file tree
/
Copy pathworker.ts
More file actions
83 lines (71 loc) · 2.13 KB
/
worker.ts
File metadata and controls
83 lines (71 loc) · 2.13 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
import { WorkerEntrypoint } from "cloudflare:workers";
import type { ApiResponse } from "./src/types.js";
export default class extends WorkerEntrypoint<Env> {
async fetch(request: Request) {
const url = new URL(request.url);
if (url.pathname === '/') {
return this.handleSSR(request);
}
else if (url.pathname === '/not_an_api.json') {
const value = await this.env.KV_STATUS.get<ApiResponse>('steamstatus', { type: 'json' });
return Response.json(value, {
headers: {
'Cache-Control': 'no-store'
}
});
}
return new Response(null, { status: 404 });
}
async handleSSR(request: Request): Promise<Response> {
const statusData = await this.env.KV_STATUS.get<ApiResponse>('steamstatus', { type: 'json' });
const htmlResponse = await this.env.ASSETS.fetch(request);
if (!statusData) {
return htmlResponse;
}
const statuses = ['good', 'minor', 'major'];
const servicesMap = new Map(statusData.services.map(([id, status, title]) => [id, { status, title }]));
return new HTMLRewriter()
.on('.status[id]', {
element(element) {
const serviceId = element.getAttribute('id');
if (!serviceId) {
return;
}
const service = servicesMap.get(serviceId);
if (service) {
element.setAttribute('class', `status ${statuses[service.status]}`);
element.setInnerContent(service.title);
}
}
})
.on('#psa', {
element(element) {
if (statusData.psa) {
element.removeAttribute('hidden');
element.setInnerContent(statusData.psa, { html: true });
}
}
})
.on('#loader', {
element(element) {
const ssrData = structuredClone(statusData);
// @ts-ignore
delete ssrData.notice;
// @ts-ignore
delete ssrData.services;
element.setAttribute('hidden', '');
element.setAttribute('data-ssr', JSON.stringify(ssrData));
}
})
.on('#js-sale-name', {
element(element) {
if (statusData.sale) {
element.setAttribute('class', 'has-sale');
element.setAttribute('href', 'https://steamdb.info/sales/');
element.setInnerContent(statusData.sale);
}
}
})
.transform(htmlResponse);
}
}