-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathindex.ts
82 lines (68 loc) · 2.08 KB
/
index.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
import { serve } from './deps/server.ts'
// project imports
import getCommentsCached from './loadHnComments.ts'
import { createFileMap } from './staticLoader.ts'
import { DOMAIN, BASE_URL } from "./utils/constants.ts";
const PORT = Number(Deno.env.get('PORT') || '3000')
const REDIRECT = Deno.env.get('REDIRECT')
const fileMap = await createFileMap()
// start server
serve(async (req) => {
const url = new URL(req.url)
// redirect http -> https, brandonsmith.ninja -> brandons.me
if (REDIRECT) {
if (req.headers.get('x-forwarded-proto') !== 'https' || url.hostname !== DOMAIN) {
return Response.redirect(
BASE_URL + url.pathname,
301
)
}
}
// serve static files
{
const staticFile = fileMap.get(url.pathname)
if (staticFile) {
const { content, headers } = staticFile
return new Response(content, {
headers
})
}
}
// dynamic endpoints
const endpointPrefix = '/hn-comments/'
if (url.pathname.startsWith(endpointPrefix)) {
const post = url.pathname.substring(endpointPrefix.length)
try {
if (post) {
const data = await getCommentsCached(post)
if (data) {
return new Response(JSON.stringify(data), {
headers: {
'Content-Type': 'application/json'
}
})
}
}
return new Response(undefined, { status: 404 })
} catch (e) {
console.error(e)
return new Response(undefined, { status: 500 })
}
}
if (url.pathname === '/health_check') {
return new Response('OK')
}
// handle 404s
{
const { content, headers } = fileMap.get('/404') as { content: Uint8Array, headers: HeadersInit }
return new Response(
content,
{
status: 404,
headers
}
)
}
}, {
port: PORT
})