Issam E. Maghni | 0ef4a36 | 2022-10-05 23:20:16 +0000 | [diff] [blame^] | 1 | /* |
| 2 | * Copyright (C) 2022 Savoir-faire Linux Inc. |
| 3 | * |
| 4 | * This program is free software; you can redistribute it and/or modify |
| 5 | * it under the terms of the GNU Affero General Public License as |
| 6 | * published by the Free Software Foundation; either version 3 of the |
| 7 | * License, or (at your option) any later version. |
| 8 | * |
| 9 | * This program is distributed in the hope that it will be useful, |
| 10 | * but WITHOUT ANY WARRANTY; without even the implied warranty of |
| 11 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the |
| 12 | * GNU Affero General Public License for more details. |
| 13 | * |
| 14 | * You should have received a copy of the GNU Affero General Public |
| 15 | * License along with this program. If not, see |
| 16 | * <https://www.gnu.org/licenses/>. |
| 17 | */ |
| 18 | import { IncomingMessage } from 'node:http'; |
| 19 | import { Duplex } from 'node:stream'; |
| 20 | |
| 21 | import { Service } from 'typedi'; |
| 22 | import { WebSocket, WebSocketServer } from 'ws'; |
| 23 | |
| 24 | @Service() |
| 25 | class Ws { |
| 26 | async build() { |
| 27 | await Promise.resolve(42); |
| 28 | |
| 29 | const wss = new WebSocketServer({ |
| 30 | noServer: true, |
| 31 | }); |
| 32 | wss.on('connection', (ws: WebSocket, _req: IncomingMessage, id: string) => { |
| 33 | ws.on('message', (data) => { |
| 34 | ws.send( |
| 35 | JSON.stringify({ |
| 36 | id, |
| 37 | data, |
| 38 | }) |
| 39 | ); |
| 40 | }); |
| 41 | }); |
| 42 | |
| 43 | return (request: IncomingMessage, socket: Duplex, head: Buffer) => { |
| 44 | wss.handleUpgrade(request, socket, head, (ws) => wss.emit('connection', ws, request, '42')); |
| 45 | }; |
| 46 | } |
| 47 | } |
| 48 | |
| 49 | export { Ws }; |