perf: switch benchmarks to factorial(50000)
[poolifier.git] / examples / typescript / websocket-server-pool / ws-worker_threads / src / main.ts
1 import { type RawData, WebSocketServer } from 'ws'
2
3 import { requestHandlerPool } from './pool.js'
4 import { type DataPayload, type MessagePayload, MessageType } from './types.js'
5
6 const port = 8080
7 const wss = new WebSocketServer({ port }, () => {
8 console.info(
9 `⚡️[ws server]: WebSocket server is started at ws://localhost:${port}/`
10 )
11 })
12
13 const emptyFunction = (): void => {
14 /* Intentional */
15 }
16
17 wss.on('connection', ws => {
18 ws.on('error', console.error)
19 ws.on('message', (message: RawData) => {
20 const { type, data } = JSON.parse(
21 // eslint-disable-next-line @typescript-eslint/no-base-to-string
22 message.toString()
23 ) as MessagePayload<DataPayload>
24 switch (type) {
25 case MessageType.echo:
26 requestHandlerPool
27 .execute({ data }, 'echo')
28 .then(response => {
29 ws.send(
30 JSON.stringify({
31 type: MessageType.echo,
32 data: response.data
33 })
34 )
35 return undefined
36 })
37 .catch(emptyFunction)
38 break
39 case MessageType.factorial:
40 requestHandlerPool
41 .execute({ data }, 'factorial')
42 .then(response => {
43 ws.send(
44 JSON.stringify(
45 {
46 type: MessageType.factorial,
47 data: response.data
48 },
49 (_, v) => (typeof v === 'bigint' ? v.toString() : v)
50 )
51 )
52 return undefined
53 })
54 .catch(emptyFunction)
55 break
56 }
57 })
58 })