-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.ts
75 lines (62 loc) · 2.12 KB
/
main.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
import { Context, Hono, Next, } from 'hono'
import { serveStatic } from 'hono/deno'
import config from "./lib/config.ts";
import { getInterwikiData } from "./lib/kv.ts";
const app = new Hono()
const NotFoundHandler = serveStatic({
path: "./public/404/index.html",
onFound(_path, c) {
c.status(404)
},
})
const staticFilesHandler = serveStatic({ root: "./public" })
const defaultRedirects = {
homepage: "https://landing.lorebooks.wiki",
urlPrefix: "https://landing.lorebooks.wiki/"
}
app.get("/", (c: Context, next: Next) => staticFilesHandler(c, next))
app.get("/abuse", (c: Context, next: Next) => serveStatic({ path: "./public/abuse/index.html" })(c, next))
app.get("/favicon.ico", (c: Context) => {
return c.redirect("https://raw.githubusercontent.com/lorebooks-wiki/mkdocs-material-template/main/docs/assets/branding/default-favicon_512.png")
})
app.get("/css/*", (c: Context, next: Next) => staticFilesHandler(c, next))
app.get("/test-broken", (c: Context) => {
throw Error("why")
})
app.get("/:wiki", async(c: Context, next: Next) => {
const { wiki } = c.req.param()
const {data: dbResult, error } = await getInterwikiData(wiki)
console.log(`[debug] dbResult: ${JSON.stringify(dbResult)}`)
if (dbResult?.value !== null) {
const interwikiData = dbResult?.value || defaultRedirects
return c.redirect(interwikiData.homepage)
} else {
return NotFoundHandler(c, next)
}
})
app.get("/:wiki/*", async (c: Context) => {
const {wiki} = c.req.param()
const { data: dbResult, error } = await getInterwikiData(wiki)
const path = c.req.path.slice(`/${wiki}/`.length)
if (dbResult === null) {
return NotFoundHandler(c)
}
const targetUrl = `${dbResult.value.homepage}/${path}`
console.log(`[debug]: redirecting to ${targetUrl}`)
return c.redirect(targetUrl)
})
app.notFound((c: Context, next: Next) => {
const data = NotFoundHandler(c, next)
return data
})
app.onError((err, c: Context) => {
const data = serveStatic({
path: "./public/500/index.html",
onFound(_path, c) {
c.status(500)
},
})(c)
console.error(err)
return data
})
Deno.serve({ port: config.port},app.fetch)