Skip to content

Commit

Permalink
asd
Browse files Browse the repository at this point in the history
  • Loading branch information
Bit-Barron committed Nov 2, 2024
1 parent 6d18265 commit 127ae5d
Showing 1 changed file with 32 additions and 4 deletions.
36 changes: 32 additions & 4 deletions src/lib/server/socket.ts
Original file line number Diff line number Diff line change
@@ -1,17 +1,22 @@
/* eslint-disable @typescript-eslint/no-explicit-any */
import { Server } from 'socket.io';
import type { Server as HTTPServer } from 'http';

let io: Server | null = null;

export const initSocketIO = (httpServer: HTTPServer) => {
if (!io) {
console.log('Initializing Socket.IO server...');
io = new Server(httpServer, {
path: '/socket.io',
cors: {
origin: 'https://youtubepedia.barron.agency',
origin: ['https://youtubepedia.barron.agency', 'http://localhost:3000'],
methods: ['GET', 'POST'],
credentials: true
}
}); //'https://youtubepedia.barron.agency'
},
transports: ['websocket', 'polling']
});

io.on('connection', (socket) => {
console.log('Client connected', socket.id);

Expand All @@ -25,13 +30,36 @@ export const initSocketIO = (httpServer: HTTPServer) => {
console.log('Client disconnected', socket.id);
});
});

console.log('Socket.IO server initialized successfully');
}
return io;
};

export const getIO = (): Server => {
if (!io) {
throw new Error('Socket.IO has not been initialized');
console.warn('Socket.IO accessed before initialization, waiting...');
return new Proxy({} as Server, {
get: (target, prop) => {
if (prop === 'to' || prop === 'emit') {
return (...args: any[]) => {
setTimeout(() => {
const realIO = getIO();
if (realIO && prop in realIO) {
(realIO[prop as keyof Server] as any)(...args);
}
}, 100);
};
}
return () => {
console.warn('Socket.IO method called before initialization');
};
}
});
}
return io;
};

export const isSocketInitialized = (): boolean => {
return io !== null;
};

0 comments on commit 127ae5d

Please sign in to comment.