'Use custom WebSocket class in TypeScript for clients passed to WebSocket server events in "ws" package

Using the ws package and TypeScript, how might one make a WebSocket server pass instances of a custom WebSocket client class, instead of its own plain WebSocket, to any event handlers?

For example:

import { WebSocket, WebSocketServer } from 'ws';

class CustomWebSocket extends WebSocket {
    doSomething() {
        return true;
    }
}

class CustomWebSocketServer extends WebSocketServer {
    clients: Set<CustomWebSocket> = new Set();
}

const wss = new CustomWebSocketServer({ port: 1234 });

wss.on('connection', (clientSocket: CustomWebSocket) => {
    // Runtime error when connection event fires when client connects.
    // TypeError: clientSocket.doSomething is not a function
    clientSocket.doSomething();
});


Solution 1:[1]

If you use an adapter on the client-side, you might be able to do something close, check this out... This implementation uses WS, MONGODB adapter and PM2.

const ip = require("ip");
const { createAdapter } = require("@socket.io/mongo-adapter");

const ioClient = require("socket.io-client");
const mongoose = require("mongoose");

const COLLECTION = "ws-io-adapter-events";

const socketClient = ioClient(
  `http://${ip.address()}:${process.env.PORT}/endpoint`
    );

const listenSockets = async io => {
  try {
    await mongoose.connection.createCollection(COLLECTION, {
      capped: true,
      size: 1e6,
    });
  } catch (e) {
    // collection already exists
  }
  const mongoCollection = mongoose.connection.collection(COLLECTION);

  io.adapter(createAdapter(mongoCollection));

  const mainSocket = io.of("/endpoint");

  mainSocket.on("connection", socket => { //you can also pass your custom WS here
    socket.on("food:ready", (**custom_activity_goes_here_event_orfunc**) => {
      mainSocket.emit("food:ready", { data: **custom_activity_goes_here_event_orfunc** });
    });
  });
};

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Yusuf Ganiyu