blob: 67306ba938dfd2056b54d7f82e996fdeaf92af18 (
plain)
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
|
import { Context } from './context.model'
import { bindOperations } from './operations'
import { DatabaseChange } from '../../lib/database-change.model'
import WebSocket from 'ws'
import { Database, Context as CoreContext } from 'naive-core'
type CleanupRoutine = () => Promise<void>
export const runServer = async (ctx: Context): Promise<CleanupRoutine> => {
const db = new Database()
await db.init()
const wss = new WebSocket.Server({ port: ctx.wsPort })
const socketCleanup = () =>
new Promise((resolve, reject) => {
wss.close(resolve)
})
const operationCleanup = await bindOperations(
ctx,
db,
async (dbChange: DatabaseChange) => {
for (let client of wss.clients) {
client.send(JSON.stringify(dbChange))
}
}
)
return async () => {
Promise.all([operationCleanup(), socketCleanup()])
}
}
|