Skip to content

Instantly share code, notes, and snippets.

@SamukaDEV
Created January 22, 2025 05:33
PeerJS Wrapper Class "Helper"
class HelpApp {
connection = null;
peer = null;
options = null;
constructor(options) {
this.options = options;
// check dependencies
if (globalThis.Peer === undefined) {
const tag = document.createElement("script");
tag.setAttribute('src', "https://unpkg.com/peerjs/dist/peerjs.min.js");
tag.onload = () => {
this.init()
}
tag.onerror = () => {
throw new Error("Failed to load PeerJS dependency")
}
document.head.appendChild(tag);
return;
}
this.init()
}
init() {
const s_opts = this.options?.server;
if (!s_opts) throw new Error('[HelpApp/Error] Server options missing!')
this.peer = new Peer({ ...s_opts });
this.peer.on("connection", (cn) => {
this.connection = cn;
this.connection.on("data", this.on_data_received);
console.log("sameone connected on me");
});
this.peer.on("open", (id) => {
console.log("Peer connected as", id);
});
this.peer.on("error", (err) => {
console.warn(`[HelpApp/Error]`, err);
});
}
connect(friend_id) {
this.connection = this.peer.connect(friend_id);
this.connection.on("data", this.on_data_received);
}
send(content) {
if (!this.connection.open) return;
if (content === null || content === undefined) return;
this.connection.send(content);
}
on_data_received(data) {
console.log("Received:", typeof data, "isArray:", Array.isArray(data), "constructor:", data.constructor?.name, data);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment