summary refs log tree commit diff
path: root/src/webrtc/util/Send.ts
blob: 1d8aa61e4f127f829d3488ed5c498ae1204f44e8 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
import { JSONReplacer } from "@spacebar/util";
import { VoicePayload } from "./Constants";
import { WebRtcWebSocket } from "./WebRtcWebSocket";

export function Send(socket: WebRtcWebSocket, data: VoicePayload) {
    if (process.env.WRTC_WS_VERBOSE) console.log(`[WebRTC] Outgoing message: ${JSON.stringify(data)}`);

    let buffer: Buffer | string;

    // TODO: encode circular object
    if (socket.encoding === "json") buffer = JSON.stringify(data, JSONReplacer);
    else return;

    return new Promise((res, rej) => {
        if (socket.readyState !== 1) {
            // return rej("socket not open");
            socket.close();
            return;
        }

        socket.send(buffer, (err) => {
            if (err) return rej(err);
            return res(null);
        });
    });
}