feat: add ws server request pool handlers example
[poolifier.git] / examples / typescript / websocket-server-pool / ws / src / main.ts
1 import { type RawData, WebSocketServer } from 'ws'
2 import { type DataPayload, type MessagePayload, MessageType } from './types.js'
3 import { requestHandlerPool } from './pool.js'
4
5 const port = 8080
6 const wss = new WebSocketServer({ port }, () => {
7 console.info(
8 `⚡️[ws server]: WebSocket server is started at http://localhost:${port}/`
9 )
10 })
11
12 const emptyFunction = (): void => {
13 /** Intentional */
14 }
15
16 wss.on('connection', ws => {
17 ws.on('error', console.error)
18
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 null
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 null
50 })
51 .catch(emptyFunction)
52 break
53 }
54 })
55 })