72 lines
1.7 KiB
TypeScript
72 lines
1.7 KiB
TypeScript
import { serve, type ServerWebSocket, type WebSocketHandler } from "bun";
|
|
import front from "./front/index.html";
|
|
|
|
const subscribers = [] as ServerWebSocket<{ uuid?: string; role: "broadcast" | "subscribe" }>[];
|
|
|
|
const server = serve({
|
|
routes: {
|
|
"/": front,
|
|
"/ws/broadcast": (req, server) => {
|
|
const uuid = crypto.randomUUID();
|
|
if (
|
|
server.upgrade(req, {
|
|
data: { uuid, role: "broadcast" },
|
|
})
|
|
) {
|
|
return;
|
|
}
|
|
|
|
return new Response("Upgrade required", { status: 426 });
|
|
},
|
|
"/ws/subscribe": (req, server) => {
|
|
const uuid = crypto.randomUUID();
|
|
if (
|
|
server.upgrade(req, {
|
|
data: { uuid, role: "subscribe" },
|
|
})
|
|
) {
|
|
return;
|
|
}
|
|
|
|
return new Response("Upgrade required", { status: 426 });
|
|
},
|
|
},
|
|
development: {
|
|
console: true,
|
|
},
|
|
websocket: {
|
|
open(ws) {
|
|
if (ws.data.role === "subscribe") {
|
|
subscribers.push(ws);
|
|
} else if (ws.data.role === "broadcast") {
|
|
ws.send("Connected to broadcast");
|
|
}
|
|
},
|
|
message(ws, message) {
|
|
console.log("Received message", message.toString());
|
|
if (ws.data.role === "broadcast") {
|
|
const uuid = ws.data.uuid;
|
|
const coords = JSON.parse(message.toString());
|
|
const messageToSend = JSON.stringify({
|
|
geometry: {
|
|
...coords,
|
|
spatialReference: {
|
|
wkid: 4326,
|
|
},
|
|
},
|
|
attributes: {
|
|
uuid,
|
|
},
|
|
});
|
|
subscribers.forEach((subscriber) => {
|
|
subscriber.send(messageToSend);
|
|
});
|
|
} else if (ws.data.role === "subscribe") {
|
|
ws.send(`Received message: ${message}`);
|
|
}
|
|
},
|
|
close(ws) {},
|
|
} as WebSocketHandler<{ uuid?: string; role: "broadcast" | "subscribe" }>,
|
|
});
|
|
|
|
console.log(`Server running at ${server.url}`);
|