WebSocketServer

This commit is contained in:
Julien Valverdé
2024-07-11 19:24:18 +02:00
parent 9ea6188f8b
commit 320ccb5bc5

View File

@@ -0,0 +1,40 @@
import { applyWSSHandler } from "@trpc/server/adapters/ws"
import { Context, Effect, Layer, Runtime } from "effect"
import ws from "ws"
import { ExpressHTTPServer } from "../http/ExpressHTTPServer"
import { TRPCContextCreator } from "../trpc/TRPCContextCreator"
export class WebSocketServer extends Context.Tag("RPCWebSocketServer")<WebSocketServer, {
wss: ws.Server
handler: ReturnType<typeof applyWSSHandler>
}>() {}
export module WebSocketServer {
export const Live = Layer.effect(WebSocketServer, Effect.acquireRelease(
Effect.gen(function*() {
const runSync = yield* Effect.runtime().pipe(
Effect.map(Runtime.runSync)
)
const wss = new ws.WebSocketServer({ server: yield* ExpressHTTPServer }, () =>
runSync(Effect.logInfo(`WebSocket RPC server started`))
)
const handler = applyWSSHandler({
wss,
router: yield* RPCRouter,
createContext: yield* TRPCContextCreator,
})
return { wss, handler }
}),
({ wss, handler }) => Effect.gen(function*() {
yield* Effect.logInfo(`WebSocket server is closing. Waiting for existing connections to end...`)
yield* Effect.async(resume => {
wss.close(() => resume(Effect.logInfo(`WebSocket server closed`)))
})
}),
))
}