-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.ts
67 lines (56 loc) · 1.87 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
import { SessionRequest, setSession } from './session'
export const server = Bun.serve({
fetch: async (Request) => {
const path = new URL(Request.url).pathname
if (Request.method == 'GET' && path.startsWith('/static')) {
const file = Bun.file('.' + path)
if (!(await file.exists())) {
return new Response('Not Found', { status: 404 })
}
return new Response(file)
}
const router = new Bun.FileSystemRouter({
dir: './pages',
style: 'nextjs'
})
const route = router.match(Request)
if (!route) {
return new Response('Not Found', { status: 404 })
}
let data: FormData | undefined
if (Request.method == 'POST') {
if (
Request.headers.get('Content-Type') ==
'application/x-www-form-urlencoded' ||
Request.headers.get('Content-Type')?.includes('multipart/form-data')
) {
data = await Request.formData()
} else if (Request.headers.get('Content-Type') == 'application/json') {
const text = await Request.text()
data = JSON.parse(text)
}
}
const sessReq = new SessionRequest(Request, data, route.params)
const page = await import(route.filePath)
let res: Response | undefined
if (sessReq.sessionValid == false) {
if (sessReq.parsedUrl.pathname != '/login') {
return setSession(Response.redirect('/login?redirect=' + encodeURIComponent(Request.url)), undefined)
}
}
if (Request.method == 'POST') {
res = page.post?.(sessReq, data)
} else if (Request.method == 'GET') {
res = page.get?.(sessReq)
}
return res ?? new Response('Method Not Allowed', { status: 405 })
},
port: 3000,
websocket: {
message: function () // ws: ServerWebSocket<unknown>,
// message: string | Buffer
: void | Promise<void> {
throw new Error('Function not implemented.')
}
}
})