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( | |
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 | 43 | ws.send( |
66f0c14c JB |
44 | JSON.stringify( |
45 | { | |
46 | type: MessageType.factorial, | |
47 | data: response.data | |
48 | }, | |
49 | (_, v) => (typeof v === 'bigint' ? v.toString() : v) | |
50 | ) | |
219d4044 | 51 | ) |
fefd3cef | 52 | return undefined |
219d4044 JB |
53 | }) |
54 | .catch(emptyFunction) | |
55 | break | |
56 | } | |
57 | }) | |
58 | }) |