| 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( |
| 8 | `⚡️[ws server]: WebSocket server is started at ws://localhost:${port}/` |
| 9 | ) |
| 10 | }) |
| 11 | |
| 12 | const emptyFunction = (): void => { |
| 13 | /* Intentional */ |
| 14 | } |
| 15 | |
| 16 | wss.on('connection', ws => { |
| 17 | ws.on('error', console.error) |
| 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') |
| 27 | .then(response => { |
| 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') |
| 41 | .then(response => { |
| 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 | }) |