chore: migrate to eslint 9
[poolifier.git] / examples / typescript / websocket-server-pool / ws-cluster / src / worker.ts
CommitLineData
72855e92
JB
1import { ClusterWorker } from 'poolifier'
2import { type RawData, WebSocketServer } from 'ws'
ded253e2 3
72855e92
JB
4import {
5 type DataPayload,
6 type MessagePayload,
7 MessageType,
8 type WorkerData,
3a502712 9 type WorkerResponse,
72855e92
JB
10} from './types.js'
11
3d49c6d2
JB
12class WebSocketServerWorker extends ClusterWorker<WorkerData, WorkerResponse> {
13 private static wss: WebSocketServer
14
66f0c14c
JB
15 private static readonly factorial = (n: number | bigint): bigint => {
16 if (n === 0 || n === 1) {
17 return 1n
18 } else {
19 n = BigInt(n)
20 let factorial = 1n
21 for (let i = 1n; i <= n; i++) {
22 factorial *= i
23 }
24 return factorial
8538ea4c 25 }
8538ea4c
JB
26 }
27
3d49c6d2
JB
28 private static readonly startWebSocketServer = (
29 workerData?: WorkerData
30 ): WorkerResponse => {
3a502712 31 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
67f3f2d6 32 const { port } = workerData!
30369cc0 33
3d49c6d2
JB
34 WebSocketServerWorker.wss = new WebSocketServer({ port }, () => {
35 console.info(
36 `⚡️[ws server]: WebSocket server is started in cluster worker at ws://localhost:${port}/`
37 )
38 })
72855e92 39
041dc05b 40 WebSocketServerWorker.wss.on('connection', ws => {
3d49c6d2
JB
41 ws.on('error', console.error)
42 ws.on('message', (message: RawData) => {
43 const { type, data } = JSON.parse(
3d49c6d2
JB
44 message.toString()
45 ) as MessagePayload<DataPayload>
46 switch (type) {
47 case MessageType.echo:
48 ws.send(
49 JSON.stringify({
50 type: MessageType.echo,
3a502712 51 data,
3d49c6d2
JB
52 })
53 )
54 break
55 case MessageType.factorial:
56 ws.send(
66f0c14c
JB
57 JSON.stringify(
58 {
59 type: MessageType.factorial,
60 data: {
3a502712
JB
61 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
62 number: WebSocketServerWorker.factorial(data.number!),
63 },
66f0c14c
JB
64 },
65 (_, v) => (typeof v === 'bigint' ? v.toString() : v)
66 )
3d49c6d2
JB
67 )
68 break
69 }
70 })
72855e92 71 })
3d49c6d2
JB
72 return {
73 status: true,
3a502712 74 port: WebSocketServerWorker.wss.options.port,
3d49c6d2 75 }
72855e92 76 }
72855e92 77
72855e92 78 public constructor () {
e8f1b611
JB
79 super(WebSocketServerWorker.startWebSocketServer, {
80 killHandler: () => {
81 WebSocketServerWorker.wss.close()
3a502712 82 },
e8f1b611 83 })
72855e92
JB
84 }
85}
86
87export const webSocketServerWorker = new WebSocketServerWorker()