159 lines
3.8 KiB
JavaScript
159 lines
3.8 KiB
JavaScript
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 (
|
|
<div style={{ maxWidth: 480, margin: "2rem auto", fontFamily: "sans-serif" }}>
|
|
<h1>Lab1 Messenger — демо-клиент</h1>
|
|
{error && <p style={{ color: "red" }}>{error}</p>}
|
|
|
|
{!me && (
|
|
<section>
|
|
<h2>Регистрация</h2>
|
|
<input
|
|
placeholder="username (a-z0-9_)"
|
|
value={username}
|
|
onChange={(e) => setUsername(e.target.value)}
|
|
/>
|
|
<input
|
|
placeholder="display name"
|
|
value={displayName}
|
|
onChange={(e) => setDisplayName(e.target.value)}
|
|
/>
|
|
<button onClick={handleRegister}>Зарегистрироваться</button>
|
|
</section>
|
|
)}
|
|
|
|
{me && !chat && (
|
|
<section>
|
|
<p>
|
|
Вошли как <b>{me.username}</b> (id: {me.id})
|
|
</p>
|
|
<h2>Создать чат</h2>
|
|
<input
|
|
placeholder="название чата"
|
|
value={chatTitle}
|
|
onChange={(e) => setChatTitle(e.target.value)}
|
|
/>
|
|
<input
|
|
placeholder="ID других участников через запятую"
|
|
value={memberIdsInput}
|
|
onChange={(e) => setMemberIdsInput(e.target.value)}
|
|
/>
|
|
<button onClick={handleCreateChat}>Создать</button>
|
|
</section>
|
|
)}
|
|
|
|
{me && chat && (
|
|
<section>
|
|
<h2>Чат: {chat.title}</h2>
|
|
<button onClick={handleLoadHistory}>Обновить историю</button>
|
|
<ul>
|
|
{messages.map((m) => (
|
|
<li key={m.id}>
|
|
<b>{m.sender_id === me.id ? "Я" : m.sender_id}:</b> {m.text}
|
|
</li>
|
|
))}
|
|
</ul>
|
|
<input
|
|
placeholder="текст сообщения"
|
|
value={text}
|
|
onChange={(e) => setText(e.target.value)}
|
|
/>
|
|
<button onClick={handleSendMessage}>Отправить</button>
|
|
</section>
|
|
)}
|
|
</div>
|
|
);
|
|
} |