diff --git a/src/chat/src/app.ts b/src/chat/src/app.ts index e338226..e8f198b 100644 --- a/src/chat/src/app.ts +++ b/src/chat/src/app.ts @@ -5,8 +5,10 @@ import * as db from '@shared/database'; import * as auth from '@shared/auth'; import * as swagger from '@shared/swagger'; import * as utils from '@shared/utils'; -import useSocketIo from 'fastify-socket.io'; +// import useSocketIo from 'fastify-socket.io'; import { setupSocketIo } from './socket'; +import.meta.glob('/plugins/**.ts') + declare const __SERVICE_NAME: string; @@ -22,9 +24,9 @@ const app: FastifyPluginAsync = async (fastify, opts): Promise => { await fastify.register(db.useDatabase as FastifyPluginAsync, {}); await fastify.register(auth.jwtPlugin as FastifyPluginAsync, {}); await fastify.register(auth.authPlugin as FastifyPluginAsync, {}); - await fastify.register(useSocketIo, { - path: '/api/chat/socket.io', - }); + // await fastify.register(useSocketIo, { + // path: '/api/chat/socket.io', + // }); // Place here your custom code! for (const plugin of Object.values(plugins)) { @@ -42,7 +44,7 @@ const app: FastifyPluginAsync = async (fastify, opts): Promise => { // Setup Socket.io - setupSocketIo(fastify); + setupSocketIo(); }; export default app; export { app }; diff --git a/src/chat/src/plugins/socket.ts b/src/chat/src/plugins/socket.ts new file mode 100644 index 0000000..59905d2 --- /dev/null +++ b/src/chat/src/plugins/socket.ts @@ -0,0 +1,36 @@ +import type { + FastifyInstance, + FastifyPluginAsync, + HookHandlerDoneFunction, +} from 'fastify'; +import fp from 'fastify-plugin'; +import { Server, type ServerOptions } from 'socket.io'; + +export type FastifySocketioOptions = Partial & { + preClose?: (done: HookHandlerDoneFunction) => void; +}; + +const F: (f: FastifyInstance) => (Omit & { io: Server }) = f => (f as Omit & { io: Server }); + +const fastifySocketIO: FastifyPluginAsync = fp( + async (fastify, opts: FastifySocketioOptions) => { + function defaultPreClose(done: HookHandlerDoneFunction) { + F(fastify).io.local.disconnectSockets(true); + done(); + } + fastify.decorate('io', new Server(fastify.server, opts)); + fastify.addHook('preClose', (done) => { + if (opts.preClose) { + return opts.preClose(done); + } + return defaultPreClose(done); + }); + fastify.addHook('onClose', (instance: FastifyInstance, done) => { + F(instance).io.close(); + done(); + }); + }, +); + + +export default fastifySocketIO; \ No newline at end of file diff --git a/src/chat/src/routes/nginx-chat.ts b/src/chat/src/routes/nginx-chat.ts index 541cc7d..c40c1c0 100644 --- a/src/chat/src/routes/nginx-chat.ts +++ b/src/chat/src/routes/nginx-chat.ts @@ -1,7 +1,10 @@ import { FastifyPluginAsync } from 'fastify'; import { MakeStaticResponse, typeResponse } from '@shared/utils'; import { Type } from '@sinclair/typebox'; -import * as fsocketio from 'socket.io'; +// import * as fsocketio from 'socket.io'; + + + export const ChatRes = { 200: typeResponse('success', 'chat.success', {