Commit | Line | Data |
---|---|---|
02999424 JB |
1 | import { ClusterWorker } from 'poolifier' |
2 | import { type RawData, WebSocketServer } from 'ws' | |
3 | import { | |
4 | type ClusterWorkerData, | |
5 | type ClusterWorkerResponse, | |
6 | type DataPayload, | |
7 | type MessagePayload, | |
8 | MessageType | |
9 | } from './types.js' | |
10 | import { requestHandlerPool } from './request-handler-pool.js' | |
11 | ||
12 | const emptyFunction = (): void => { | |
13 | /** Intentional */ | |
14 | } | |
15 | ||
16 | const startWebSocketServer = ( | |
17 | workerData?: ClusterWorkerData | |
18 | ): ClusterWorkerResponse => { | |
19 | const { port } = workerData as ClusterWorkerData | |
20 | const wss = new WebSocketServer({ port }, () => { | |
21 | console.info( | |
22 | `⚡️[ws server]: WebSocket server is started on cluster worker at ws://localhost:${port}/` | |
23 | ) | |
24 | }) | |
25 | ||
26 | wss.on('connection', ws => { | |
27 | ws.on('error', console.error) | |
28 | ws.on('message', (message: RawData) => { | |
29 | const { type, data } = JSON.parse( | |
30 | // eslint-disable-next-line @typescript-eslint/no-base-to-string | |
31 | message.toString() | |
32 | ) as MessagePayload<DataPayload> | |
33 | switch (type) { | |
34 | case MessageType.echo: | |
35 | requestHandlerPool | |
36 | .execute({ data }, 'echo') | |
37 | .then(response => { | |
38 | ws.send( | |
39 | JSON.stringify({ | |
40 | type: MessageType.echo, | |
41 | data: response.data | |
42 | }) | |
43 | ) | |
44 | return null | |
45 | }) | |
46 | .catch(emptyFunction) | |
47 | break | |
48 | case MessageType.factorial: | |
49 | requestHandlerPool | |
50 | .execute({ data }, 'factorial') | |
51 | .then(response => { | |
52 | ws.send( | |
53 | JSON.stringify({ | |
54 | type: MessageType.factorial, | |
55 | data: response.data | |
56 | }) | |
57 | ) | |
58 | return null | |
59 | }) | |
60 | .catch(emptyFunction) | |
61 | break | |
62 | } | |
63 | }) | |
64 | }) | |
65 | return { | |
66 | status: true, | |
67 | port: wss.options.port | |
68 | } | |
69 | } | |
70 | ||
71 | class WebSocketServerWorker extends ClusterWorker< | |
72 | ClusterWorkerData, | |
73 | ClusterWorkerResponse | |
74 | > { | |
75 | public constructor () { | |
76 | super(startWebSocketServer) | |
77 | } | |
78 | } | |
79 | ||
80 | export const webSocketServerWorker = new WebSocketServerWorker() |