Commit | Line | Data |
---|---|---|
219d4044 | 1 | import { type RawData, WebSocketServer } from 'ws' |
ded253e2 | 2 | |
219d4044 | 3 | import { requestHandlerPool } from './pool.js' |
ded253e2 | 4 | import { type DataPayload, type MessagePayload, MessageType } from './types.js' |
219d4044 JB |
5 | |
6 | const port = 8080 | |
7 | const wss = new WebSocketServer({ port }, () => { | |
8 | console.info( | |
72855e92 | 9 | `⚡️[ws server]: WebSocket server is started at ws://localhost:${port}/` |
219d4044 JB |
10 | ) |
11 | }) | |
12 | ||
13 | const emptyFunction = (): void => { | |
8ea47589 | 14 | /* Intentional */ |
219d4044 JB |
15 | } |
16 | ||
041dc05b | 17 | wss.on('connection', ws => { |
219d4044 | 18 | ws.on('error', console.error) |
219d4044 JB |
19 | ws.on('message', (message: RawData) => { |
20 | const { type, data } = JSON.parse( | |
219d4044 JB |
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, | |
3a502712 | 31 | data: response.data, |
219d4044 JB |
32 | }) |
33 | ) | |
fefd3cef | 34 | return undefined |
219d4044 JB |
35 | }) |
36 | .catch(emptyFunction) | |
37 | break | |
38 | case MessageType.factorial: | |
39 | requestHandlerPool | |
40 | .execute({ data }, 'factorial') | |
041dc05b | 41 | .then(response => { |
219d4044 | 42 | ws.send( |
66f0c14c JB |
43 | JSON.stringify( |
44 | { | |
45 | type: MessageType.factorial, | |
3a502712 | 46 | data: response.data, |
66f0c14c JB |
47 | }, |
48 | (_, v) => (typeof v === 'bigint' ? v.toString() : v) | |
49 | ) | |
219d4044 | 50 | ) |
fefd3cef | 51 | return undefined |
219d4044 JB |
52 | }) |
53 | .catch(emptyFunction) | |
54 | break | |
55 | } | |
56 | }) | |
57 | }) |