f3aea4e5b60a2cdc15fa2f3a124ed93673b39b53
[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 type: MessageType.factorial,
46 data: response.data
47 })
48 )
49 return undefined
50 })
51 .catch(emptyFunction)
52 break
53 }
54 })
55 })