Files
chad/server/plugins/socket.ts

45 lines
1.3 KiB
TypeScript

import type { FastifyInstance } from 'fastify'
import type { ServerOptions } from 'socket.io'
import type { MessageSelect } from '../prisma/generated-client/models/Message.ts'
import fp from 'fastify-plugin'
import { Server } from 'socket.io'
import registerChatSocket from '../socket/chat.ts'
import registerWebrtcSocket from '../socket/webrtc.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()
})
await registerWebrtcSocket(fastify.io, fastify.mediasoupRouter, fastify.prisma)
await registerChatSocket(fastify.io)
fastify.bus.on('chat:new-message', async (message: MessageSelect) => {
fastify.io.emit('chat:new-message', message)
})
},
{ name: 'socket-io', dependencies: ['mediasoup-worker', 'mediasoup-router'] },
)
export const autoConfig: Partial<ServerOptions> = {
path: '/chad/ws',
cors: {
origin: process.env.CORS_ORIGIN || '*',
methods: ['GET', 'POST'],
credentials: true,
},
}