Files
chad/server/plugins/socket.ts

58 lines
1.5 KiB
TypeScript

import type { FastifyInstance } from 'fastify'
import type { ServerOptions } from 'socket.io'
import fp from 'fastify-plugin'
import { Server } from 'socket.io'
import registerChatSocket from './socket/chat/index.ts'
import registerWebrtcSocket from './socket/webrtc/index.ts'
declare module 'fastify' {
interface FastifyInstance {
io: Server
}
}
export default fp<Partial<ServerOptions>>(
async (fastify, opts) => {
fastify.decorate('io', new Server(fastify.server, opts))
fastify.addHook('preClose', () => {
fastify.io.disconnectSockets(true)
})
fastify.addHook('onClose', async (fastify: FastifyInstance) => {
await fastify.io.close()
})
fastify.io.use(async (socket, next) => {
const sessionId = fastify.lucia.readSessionCookie(socket.handshake.headers.cookie ?? '')
if (!sessionId) {
return next(fastify.httpErrors.unauthorized())
}
const { user } = await fastify.lucia.validateSession(sessionId)
if (!user) {
return next(fastify.httpErrors.unauthorized())
}
socket.data.user = user
next()
})
await registerWebrtcSocket(fastify)
await registerChatSocket(fastify)
},
{ name: 'socket-io', dependencies: ['mediasoup-worker', 'mediasoup-router', 'prisma', 'event-bus'] },
)
export const autoConfig: Partial<ServerOptions> = {
path: '/chad/ws',
cors: {
origin: process.env.CORS_ORIGIN || '*',
methods: ['GET', 'POST'],
credentials: true,
},
}