EvalueTonSavoir/nginx/njs/main.js

66 lines
1.9 KiB
JavaScript
Raw Normal View History

2024-11-15 17:46:01 -05:00
const roomCache = new Map();
2024-11-10 20:42:02 -05:00
async function fetchRoomInfo(r) {
try {
2024-11-15 17:46:01 -05:00
let res = await r.subrequest(`/api/room/${r.variables.room_id}`, { method: 'GET' });
2024-11-12 11:44:15 -05:00
2024-11-10 20:42:02 -05:00
if (res.status !== 200) {
r.error(`Failed to fetch room info: ${res.status}`);
return null;
}
2024-11-12 11:44:15 -05:00
2024-11-10 22:52:04 -05:00
let room = JSON.parse(res.responseText);
2024-11-15 17:46:01 -05:00
r.error(`Debug: Room info fetched: ${JSON.stringify(room)}`);
2024-11-10 22:52:04 -05:00
return room;
2024-11-10 20:42:02 -05:00
} catch (error) {
r.error(`Error fetching room info: ${error}`);
return null;
}
}
2024-11-15 17:46:01 -05:00
function checkCache(r) {
let room = roomCache.get(r.variables.room_id);
if (room) {
r.error(`Cache hit for room_id: ${r.variables.room_id}`);
r.return(200, JSON.stringify(room));
} else {
r.error(`Cache miss for room_id: ${r.variables.room_id}`);
r.return(404);
}
}
function setCache(r) {
let room = JSON.parse(r.responseBody);
roomCache.set(r.variables.room_id, room);
r.error(`Cached room info: ${JSON.stringify(room)}`);
}
2024-11-10 20:42:02 -05:00
async function routeWebSocket(r) {
2024-11-15 17:46:01 -05:00
let room = roomCache.get(r.variables.room_id);
2024-11-12 11:44:15 -05:00
2024-11-15 17:46:01 -05:00
if (!room) {
r.error(`Cache miss. Fetching room info for: ${r.variables.room_id}`);
room = await fetchRoomInfo(r);
if (!room || !room.host) {
r.error(`Invalid room info for room_id: ${r.variables.room_id}`);
2024-11-10 20:42:02 -05:00
r.return(404, 'Room not found or invalid');
return;
}
2024-11-15 17:46:01 -05:00
roomCache.set(r.variables.room_id, room); // Cache the result
} else {
r.error(`Cache hit for room_id: ${r.variables.room_id}`);
}
2024-11-12 11:44:15 -05:00
2024-11-15 17:46:01 -05:00
let proxyUrl = room.host.startsWith('http://') || room.host.startsWith('https://')
? room.host
: `http://${room.host}`;
2024-11-12 11:44:15 -05:00
2024-11-15 17:46:01 -05:00
r.error(`Routing WebSocket to: ${proxyUrl}`);
r.variables.proxy_target = proxyUrl;
r.internalRedirect('@websocket_proxy');
2024-11-10 20:42:02 -05:00
}
2024-11-15 17:46:01 -05:00
export default { routeWebSocket, checkCache, setCache };