refactor: cleanup eslint configuration
[poolifier.git] / examples / typescript / websocket-server-pool / ws-worker_threads / src / main.ts
CommitLineData
219d4044 1import { type RawData, WebSocketServer } from 'ws'
ded253e2 2
219d4044 3import { requestHandlerPool } from './pool.js'
ded253e2 4import { type DataPayload, type MessagePayload, MessageType } from './types.js'
219d4044
JB
5
6const port = 8080
7const wss = new WebSocketServer({ port }, () => {
8 console.info(
72855e92 9 `⚡️[ws server]: WebSocket server is started at ws://localhost:${port}/`
219d4044
JB
10 )
11})
12
13const emptyFunction = (): void => {
8ea47589 14 /* Intentional */
219d4044
JB
15}
16
041dc05b 17wss.on('connection', ws => {
219d4044 18 ws.on('error', console.error)
219d4044
JB
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')
041dc05b 28 .then(response => {
219d4044
JB
29 ws.send(
30 JSON.stringify({
31 type: MessageType.echo,
32 data: response.data
33 })
34 )
fefd3cef 35 return undefined
219d4044
JB
36 })
37 .catch(emptyFunction)
38 break
39 case MessageType.factorial:
40 requestHandlerPool
41 .execute({ data }, 'factorial')
041dc05b 42 .then(response => {
219d4044
JB
43 ws.send(
44 JSON.stringify({
45 type: MessageType.factorial,
46 data: response.data
47 })
48 )
fefd3cef 49 return undefined
219d4044
JB
50 })
51 .catch(emptyFunction)
52 break
53 }
54 })
55})