-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.ts
executable file
·72 lines (60 loc) · 1.86 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
#!/usr/bin/env bun
import { serve } from 'bun'
import { StateManager } from './state'
import type { Channel } from './types'
import { z } from 'zod'
import { generateId } from './utils'
const eventSchema = z.object({
key: z.string(),
value: z.any()
})
const stateManager = new StateManager()
const server = serve({
port: 3001,
routes: {
'/': req => {
const cookies = req.cookies
const { searchParams } = new URL(req.url)
const channelId = searchParams.get('channelId') || generateId()
const state = stateManager.get(channelId)
cookies.set('channelId', channelId, {
httpOnly: false,
secure: true,
sameSite: 'none' as const,
path: '/',
maxAge: 60 * 60 * 24 * 30 // 30 days
})
const headers = new Headers({
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Credentials': 'true',
'Set-Cookie': cookies.toSetCookieHeaders().join('; ')
})
if (server.upgrade(req, { data: { channelId }, headers }))
return new Response('ok', { status: 101, headers })
return Response.json(state?.getAll(), { headers })
},
'/**': () => new Response('try /', { status: 404 })
},
websocket: {
publishToSelf: false,
message: async (ws, message) => {
const payload = JSON.parse(message.toString())
const [key, value] = Object.entries(payload)[0] as [string, string]
const { channelId } = ws.data as unknown as Channel
const parsed = eventSchema.parse({ key, value })
const state = stateManager.get(channelId)
if (!state) return
const newVal = await state.set(parsed.key, parsed.value)
ws.publish(channelId, JSON.stringify({ [key]: newVal }))
},
open(ws) {
const { channelId } = ws.data as unknown as Channel
ws.subscribe(channelId)
},
close(ws) {
const { channelId } = ws.data as unknown as Channel
ws.unsubscribe(channelId)
}
}
})
console.log(`Server running on port ${server.port}`)