import { useState } from "react"; const API_BASE = "http://localhost:8080/api/v1"; async function apiFetch(path, { method = "GET", userId, body } = {}) { const headers = { "Content-Type": "application/json" }; if (userId) headers["X-User-Id"] = userId; const res = await fetch(`${API_BASE}${path}`, { method, headers, body: body ? JSON.stringify(body) : undefined, }); const requestId = res.headers.get("X-Request-Id"); const data = await res.json().catch(() => null); if (!res.ok) { const message = data?.error?.message || `HTTP ${res.status}`; throw new Error(`${message} (request_id: ${requestId})`); } return data; } export default function App() { const [username, setUsername] = useState(""); const [displayName, setDisplayName] = useState(""); const [me, setMe] = useState(null); const [chat, setChat] = useState(null); const [memberIdsInput, setMemberIdsInput] = useState(""); const [chatTitle, setChatTitle] = useState(""); const [text, setText] = useState(""); const [messages, setMessages] = useState([]); const [error, setError] = useState(""); async function handleRegister() { setError(""); try { const user = await apiFetch("/users", { method: "POST", body: { username, display_name: displayName }, }); setMe(user); } catch (e) { setError(e.message); } } async function handleCreateChat() { setError(""); try { const memberIds = memberIdsInput .split(",") .map((s) => s.trim()) .filter(Boolean); const created = await apiFetch("/chats", { method: "POST", userId: me.id, body: { title: chatTitle, member_ids: [me.id, ...memberIds] }, }); setChat(created); setMessages([]); } catch (e) { setError(e.message); } } async function handleSendMessage() { setError(""); try { const msg = await apiFetch(`/chats/${chat.id}/messages`, { method: "POST", userId: me.id, body: { text }, }); setMessages((prev) => [...prev, msg]); setText(""); } catch (e) { setError(e.message); } } async function handleLoadHistory() { setError(""); try { const page = await apiFetch(`/chats/${chat.id}/messages`, { method: "GET", userId: me.id, }); setMessages(page.items); } catch (e) { setError(e.message); } } return (
{error}
} {!me && (Вошли как {me.username} (id: {me.id})