All checks were successful
ci/woodpecker/push/ci Pipeline was successful
Co-authored-by: Jason Woltje <jason@diversecanvas.com> Co-committed-by: Jason Woltje <jason@diversecanvas.com>
33 lines
831 B
TypeScript
33 lines
831 B
TypeScript
import { io, type Socket } from 'socket.io-client';
|
|
|
|
const GATEWAY_URL = process.env['NEXT_PUBLIC_GATEWAY_URL'] ?? 'http://localhost:4000';
|
|
|
|
let socket: Socket | null = null;
|
|
|
|
export function getSocket(): Socket {
|
|
if (!socket) {
|
|
socket = io(`${GATEWAY_URL}/chat`, {
|
|
withCredentials: true,
|
|
autoConnect: false,
|
|
transports: ['websocket', 'polling'],
|
|
});
|
|
|
|
// Reset singleton reference when socket is fully closed so the next
|
|
// getSocket() call creates a fresh instance instead of returning a
|
|
// closed/dead socket.
|
|
socket.on('disconnect', () => {
|
|
socket = null;
|
|
});
|
|
}
|
|
return socket;
|
|
}
|
|
|
|
/** Tear down the singleton socket and reset the reference. */
|
|
export function destroySocket(): void {
|
|
if (socket) {
|
|
socket.offAny();
|
|
socket.disconnect();
|
|
socket = null;
|
|
}
|
|
}
|