summary refs log tree commit diff
path: root/src/webrtc/util/Send.ts
blob: 7f8ab4ddafe2eb2cb820c23951b4b991f8f16c63 (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
27
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);
		});
	});
}