2954cbdec897d26f495e705b65118388f069e1da
[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 message.toString()
22 ) as MessagePayload<DataPayload>
23 switch (type) {
24 case MessageType.echo:
25 requestHandlerPool
26 .execute({ data }, 'echo')
27 .then(response => {
28 ws.send(
29 JSON.stringify({
30 type: MessageType.echo,
31 data: response.data,
32 })
33 )
34 return undefined
35 })
36 .catch(emptyFunction)
37 break
38 case MessageType.factorial:
39 requestHandlerPool
40 .execute({ data }, 'factorial')
41 .then(response => {
42 ws.send(
43 JSON.stringify(
44 {
45 type: MessageType.factorial,
46 data: response.data,
47 },
48 (_, v) => (typeof v === 'bigint' ? v.toString() : v)
49 )
50 )
51 return undefined
52 })
53 .catch(emptyFunction)
54 break
55 }
56 })
57 })