feat: add express cluster pool example
[poolifier.git] / examples / typescript / websocket-server-pool / ws-hybrid / src / websocket-server-worker.ts
index 8b1bf2e83ca25dba3c590be6817c241e4e6f4ce4..12c2190e750d36b77a4a8aca912c62ae37711ffa 100644 (file)
@@ -22,11 +22,17 @@ class WebSocketServerWorker extends ClusterWorker<
 ClusterWorkerData,
 ClusterWorkerResponse
 > {
+  private static wss: WebSocketServer
+  private static requestHandlerPool: DynamicThreadPool<
+  ThreadWorkerData<DataPayload>,
+  ThreadWorkerResponse<DataPayload>
+  >
+
   private static readonly startWebSocketServer = (
     workerData?: ClusterWorkerData
   ): ClusterWorkerResponse => {
     const { port } = workerData as ClusterWorkerData
-    const wss = new WebSocketServer({ port }, () => {
+    WebSocketServerWorker.wss = new WebSocketServer({ port }, () => {
       console.info(
         `⚡️[ws server]: WebSocket server is started in cluster worker at ws://localhost:${port}/`
       )
@@ -41,7 +47,7 @@ ClusterWorkerResponse
       workerData?.workerFile as string
     )
 
-    wss.on('connection', ws => {
+    WebSocketServerWorker.wss.on('connection', (ws) => {
       ws.on('error', console.error)
       ws.on('message', (message: RawData) => {
         const { type, data } = JSON.parse(
@@ -52,7 +58,7 @@ ClusterWorkerResponse
           case MessageType.echo:
             WebSocketServerWorker.requestHandlerPool
               .execute({ data }, 'echo')
-              .then(response => {
+              .then((response) => {
                 ws.send(
                   JSON.stringify({
                     type: MessageType.echo,
@@ -66,7 +72,7 @@ ClusterWorkerResponse
           case MessageType.factorial:
             WebSocketServerWorker.requestHandlerPool
               .execute({ data }, 'factorial')
-              .then(response => {
+              .then((response) => {
                 ws.send(
                   JSON.stringify({
                     type: MessageType.factorial,
@@ -82,17 +88,17 @@ ClusterWorkerResponse
     })
     return {
       status: true,
-      port: wss.options.port
+      port: WebSocketServerWorker.wss.options.port
     }
   }
 
-  private static requestHandlerPool: DynamicThreadPool<
-  ThreadWorkerData<DataPayload>,
-  ThreadWorkerResponse<DataPayload>
-  >
-
   public constructor () {
-    super(WebSocketServerWorker.startWebSocketServer)
+    super(WebSocketServerWorker.startWebSocketServer, {
+      killHandler: async () => {
+        await WebSocketServerWorker.requestHandlerPool.destroy()
+        WebSocketServerWorker.wss.close()
+      }
+    })
   }
 }