async fetch(request) {
const upgradeHeader = request.headers.get("Upgrade");
if (upgradeHeader === "websocket") {
const [client, server] = Object.values(new WebSocketPair());
this.state.acceptWebSocket(server);
const isFirst = this.sessions.size === 0;
server.serializeAttachment({ isFirst });
this.sessions.set(server, { isFirst });
if (!isFirst) {
console.log("sessions.size: ", this.sessions.size);
// Debug
for (let [ws, data] of this.sessions.entries()) {
console.log("WS:", ws, "DATA:", data);
}
// find the connection with session.isFirst === true
const [firstWs, firstSession] = [...this.sessions.entries()].find(([_, session]) => session.isFirst) || [];
console.log("Found firstWs:", firstWs, "firstSession:", firstSession);
if (firstWs) {
console.log("Sending sync.")
firstWs.send(JSON.stringify({ Evento: "sincronizar_fila", Comando: "" }));
}
}
// When connect, send the stored musics
const storedMusics = await this.state.storage.get("musicas");
if (storedMusics) {
server.send(JSON.stringify({ Evento: "musicas", Comando: storedMusics }));
}
return new Response(null, { status: 101, webSocket: client });
}
return new Response("The request is not a websocket.", { status: 400 });
}