This commit is contained in:
73
src/TRPC/TRPCWebSocketServer.ts
Normal file
73
src/TRPC/TRPCWebSocketServer.ts
Normal file
@@ -0,0 +1,73 @@
|
||||
import type { AnyRouter } from "@trpc/server"
|
||||
import type { applyWSSHandler } from "@trpc/server/adapters/ws"
|
||||
import { Config, Context, Effect, Layer } from "effect"
|
||||
import type ws from "ws"
|
||||
import { ExpressNodeHTTPServer } from "../Express"
|
||||
import { ImportError } from "../ImportError"
|
||||
import { TRPCUnknownContextCreator } from "./TRPCContextCreator"
|
||||
|
||||
|
||||
const importWS = Effect.tryPromise({
|
||||
try: () => import("ws"),
|
||||
catch: cause => new ImportError({ path: "ws", cause }),
|
||||
})
|
||||
|
||||
const importTRPCServerWSAdapter = Effect.tryPromise({
|
||||
try: () => import("@trpc/server/adapters/ws"),
|
||||
catch: cause => new ImportError({ path: "@trpc/server/adapters/ws", cause }),
|
||||
})
|
||||
|
||||
|
||||
export const make = <
|
||||
Tag,
|
||||
TagShape extends AnyRouter,
|
||||
>(
|
||||
routerTag: Context.TagClass<Tag, "@thilalib/TRCP/TRPCRouter", TagShape>
|
||||
) => {
|
||||
class TRPCWebSocketServer extends Context.Tag("@thilalib/TRPC/TRPCWebSocketServer")<TRPCWebSocketServer, {
|
||||
wss: ws.Server
|
||||
handler: ReturnType<typeof applyWSSHandler<TagShape>>
|
||||
}>() {}
|
||||
|
||||
const TRPCWebSocketServerLive = (
|
||||
config: {
|
||||
readonly host: Config.Config<string>
|
||||
}
|
||||
) => Layer.effect(TRPCWebSocketServer, Effect.gen(function*() {
|
||||
const { WebSocketServer } = yield* importWS
|
||||
const { applyWSSHandler } = yield* importTRPCServerWSAdapter
|
||||
|
||||
const host = yield* config.host
|
||||
|
||||
return yield* Effect.acquireRelease(
|
||||
Effect.gen(function*() {
|
||||
yield* Effect.logInfo(`WebSocket server started on ${ host }`)
|
||||
|
||||
const wss = new WebSocketServer({
|
||||
server: yield* ExpressNodeHTTPServer.ExpressNodeHTTPServer,
|
||||
host,
|
||||
})
|
||||
|
||||
return {
|
||||
wss,
|
||||
handler: applyWSSHandler({
|
||||
wss,
|
||||
router: yield* routerTag,
|
||||
createContext: (yield* TRPCUnknownContextCreator).createWebSocketContext,
|
||||
}),
|
||||
}
|
||||
}),
|
||||
|
||||
({ wss, handler }) => Effect.gen(function*() {
|
||||
yield* Effect.logInfo(`WebSocket server on ${ host } is stopping. Waiting for existing connections to end...`)
|
||||
|
||||
handler.broadcastReconnectNotification()
|
||||
yield* Effect.async(resume => {
|
||||
wss.close(() => resume(Effect.logInfo("WebSocket server closed")))
|
||||
})
|
||||
}),
|
||||
)
|
||||
}))
|
||||
|
||||
return { TRPCWebSocketServer, TRPCWebSocketServerLive }
|
||||
}
|
||||
Reference in New Issue
Block a user