blob: f75260a21b08dfaaf707ef8eca7826684d007748 [file] [log] [blame]
Issam E. Maghni0ef4a362022-10-05 23:20:16 +00001/*
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 */
18import { IncomingMessage } from 'node:http';
19import { Duplex } from 'node:stream';
20
21import { Service } from 'typedi';
22import { WebSocket, WebSocketServer } from 'ws';
23
24@Service()
25class 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
49export { Ws };