simple websocket impl

This commit is contained in:
2026-01-03 17:15:01 +01:00
parent 69ba0ccf7c
commit 5756e51b52
3 changed files with 84 additions and 48 deletions

View File

@@ -1,8 +1,13 @@
import { createContext, useContext, useState, useEffect } from "react";
import {createContext, useContext,
useState, useEffect,
useRef
} from "react";
import { API_BASE } from "../config";
const HotelContext = createContext(null);
export function useHotel() {
return useContext(HotelContext);
}
@@ -18,6 +23,8 @@ export function HotelProvider({ accessToken, children, resClientId}) {
const tokens = JSON.parse(accessToken);
const accessTokenSingle = tokens[0];
const wsRef = useRef(null);
// --- API FUNCTIONS ---
@@ -30,7 +37,7 @@ export function HotelProvider({ accessToken, children, resClientId}) {
return res.json();
}
async function updateRoomStatus(roomId, status) {
async function updateRoomStatus(roomId, status) {
await fetch(`${API_BASE}/rooms/clean_db_update/${roomId}`, {
method: "PUT",
headers: {
@@ -41,12 +48,10 @@ export function HotelProvider({ accessToken, children, resClientId}) {
});
// refresh cached rooms
const updated = await fetchRooms();
setRooms(updated);
//const updated = await fetchRooms();
//setRooms(updated);
}
// CHAT
@@ -152,7 +157,7 @@ export function HotelProvider({ accessToken, children, resClientId}) {
}
async function addUserToConv({ conv_id, users}) {
if (!conv_id || users) {
if (!conv_id || !users) {
console.log("error in convs or user to add")
};
@@ -174,7 +179,6 @@ export function HotelProvider({ accessToken, children, resClientId}) {
}
// INVENTORY
@@ -231,7 +235,35 @@ export function HotelProvider({ accessToken, children, resClientId}) {
return users;
}
// --- WS DISPATCH MESSAGE ----
function handleWsMessage(msg) {
console.log("websocket message is :" + msg.event_type, typeof msg.event_type);
switch (msg.event_type) {
case "room_update": {
setRooms(prev =>
prev.map(r =>
r.id === msg.room_id
? { ...r, status: msg.status }
: r
)
);
break;
}
default:
console.warn("Unhandled WS message bruuuuh:", msg);
}
}
// --- WS USE EFFECT ----
// --- INITIAL DATA LOADING ---
useEffect(() => {
@@ -253,7 +285,42 @@ export function HotelProvider({ accessToken, children, resClientId}) {
load();
//console.log("USERS 2 =",usersById)
}, [accessToken]);
}, []);
useEffect(() => {
//if (!accessTokenSingle || !clientId) return;
const ws = new WebSocket(
`http://localhost:7080/auth/ws/${accessTokenSingle}`
);
wsRef.current = ws;
ws.onopen = () => {
console.log("WS connected");
};
ws.onmessage = (event) => {
const msg = JSON.parse(event.data);
console.log("WS :", msg);
handleWsMessage(msg);
};
ws.onerror = (err) => {
console.error("WS error", err);
};
ws.onclose = () => {
console.log("WS disconnected");
};
return () => {
ws.close();
};
}, [accessTokenSingle]);
return (
<HotelContext.Provider
@@ -279,3 +346,4 @@ export function HotelProvider({ accessToken, children, resClientId}) {
</HotelContext.Provider>
);
}