Commit | Line | Data |
---|---|---|
219d4044 JB |
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( | |
72855e92 | 8 | `⚡️[ws server]: WebSocket server is started at ws://localhost:${port}/` |
219d4044 JB |
9 | ) |
10 | }) | |
11 | ||
12 | const emptyFunction = (): void => { | |
8ea47589 | 13 | /* Intentional */ |
219d4044 JB |
14 | } |
15 | ||
041dc05b | 16 | wss.on('connection', ws => { |
219d4044 | 17 | ws.on('error', console.error) |
219d4044 JB |
18 | ws.on('message', (message: RawData) => { |
19 | const { type, data } = JSON.parse( | |
20 | // eslint-disable-next-line @typescript-eslint/no-base-to-string | |
21 | message.toString() | |
22 | ) as MessagePayload<DataPayload> | |
23 | switch (type) { | |
24 | case MessageType.echo: | |
25 | requestHandlerPool | |
26 | .execute({ data }, 'echo') | |
041dc05b | 27 | .then(response => { |
219d4044 JB |
28 | ws.send( |
29 | JSON.stringify({ | |
30 | type: MessageType.echo, | |
31 | data: response.data | |
32 | }) | |
33 | ) | |
34 | return null | |
35 | }) | |
36 | .catch(emptyFunction) | |
37 | break | |
38 | case MessageType.factorial: | |
39 | requestHandlerPool | |
40 | .execute({ data }, 'factorial') | |
041dc05b | 41 | .then(response => { |
219d4044 JB |
42 | ws.send( |
43 | JSON.stringify({ | |
44 | type: MessageType.factorial, | |
45 | data: response.data | |
46 | }) | |
47 | ) | |
48 | return null | |
49 | }) | |
50 | .catch(emptyFunction) | |
51 | break | |
52 | } | |
53 | }) | |
54 | }) |