#Socket IO code review

4 messages · Page 1 of 1 (latest)

placid lily
#

What do you think about this code ? The aim is to define my socket and be able to import it where I need, so I can start, stop it, and also get it to define new listeners / emit events from anywhere in my app ?

import { Server as IOServer, Socket } from "socket.io";
import { Server } from "http";

let io: IOServer;

export const startIOServer = (server: Server) => {
  io = new IOServer(server);

  io.on("connection", (socket: Socket) => {
    console.log("Socket.io connected:", socket.id);

    // Add your default socket.io event handling logic here
  });

  return io;
};

export const getIOServer = () => {
  if (!io) {
    throw new Error("Socket.io has not been initialized");
  }
  return io;
};

export const closeIOServer = () => {
  if (io) {
    io.close();
    console.log("Socket.io closed.");
  }
};

export const socket = {
  get: getIOServer,
  start: startIOServer,
  close: closeIOServer,
};

spring coral
#

Seems ok to start with. Is there something you don't like about it?

#

If you're trying to isolate it, maybe you want some way for consumers to add a callback for each connection or an event or something

#

and cleanup callback maybe for a socket that is closed/timesout