Lab2
This commit is contained in:
+379
-141
@@ -2,158 +2,396 @@ 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;
|
||||
function basicAuthorization(username, password) {
|
||||
const encoded = btoa(
|
||||
new TextEncoder()
|
||||
.encode(`${username}:${password}`)
|
||||
.reduce((value, byte) => value + String.fromCharCode(byte), "")
|
||||
);
|
||||
|
||||
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 `Basic ${encoded}`;
|
||||
}
|
||||
return data;
|
||||
|
||||
async function apiFetch(
|
||||
path,
|
||||
{
|
||||
method = "GET",
|
||||
token,
|
||||
basicCredentials,
|
||||
body,
|
||||
} = {}
|
||||
) {
|
||||
const headers = {
|
||||
Accept: "application/json",
|
||||
};
|
||||
|
||||
if (body !== undefined) {
|
||||
headers["Content-Type"] = "application/json";
|
||||
}
|
||||
|
||||
if (token) {
|
||||
headers.Authorization = `Bearer ${token}`;
|
||||
}
|
||||
|
||||
if (basicCredentials) {
|
||||
headers.Authorization = basicAuthorization(
|
||||
basicCredentials.username,
|
||||
basicCredentials.password
|
||||
);
|
||||
}
|
||||
|
||||
const response = await fetch(`${API_BASE}${path}`, {
|
||||
method,
|
||||
headers,
|
||||
body: body !== undefined ? JSON.stringify(body) : undefined,
|
||||
});
|
||||
|
||||
const requestId = response.headers.get("X-Request-Id");
|
||||
|
||||
const raw = await response.text();
|
||||
const data = raw ? JSON.parse(raw) : null;
|
||||
|
||||
if (!response.ok) {
|
||||
const message = data?.error?.message || `HTTP ${response.status}`;
|
||||
throw new Error(`${message} (request_id: ${requestId || "unknown"})`);
|
||||
}
|
||||
|
||||
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("");
|
||||
const [username, setUsername] = useState("");
|
||||
const [displayName, setDisplayName] = useState("");
|
||||
const [password, setPassword] = 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);
|
||||
}
|
||||
}
|
||||
const [session, setSession] = useState(null);
|
||||
const [chat, setChat] = useState(null);
|
||||
|
||||
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);
|
||||
}
|
||||
}
|
||||
const [memberIdsInput, setMemberIdsInput] = useState("");
|
||||
const [chatTitle, setChatTitle] = useState("");
|
||||
|
||||
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);
|
||||
}
|
||||
}
|
||||
const [text, setText] = useState("");
|
||||
const [messages, setMessages] = useState([]);
|
||||
|
||||
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);
|
||||
}
|
||||
}
|
||||
const [error, setError] = useState("");
|
||||
const [loading, setLoading] = useState(false);
|
||||
|
||||
return (
|
||||
<div style={{ maxWidth: 480, margin: "2rem auto", fontFamily: "sans-serif" }}>
|
||||
<h1>Lab1 Messenger — демо-клиент</h1>
|
||||
{error && <p style={{ color: "red" }}>{error}</p>}
|
||||
const me = session?.user ?? null;
|
||||
const token = session?.token ?? null;
|
||||
|
||||
{!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>
|
||||
)}
|
||||
async function handleRegister() {
|
||||
setError("");
|
||||
setLoading(true);
|
||||
|
||||
{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>
|
||||
)}
|
||||
try {
|
||||
await apiFetch("/users", {
|
||||
method: "POST",
|
||||
body: {
|
||||
username,
|
||||
display_name: displayName,
|
||||
password,
|
||||
},
|
||||
});
|
||||
|
||||
{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>
|
||||
);
|
||||
const createdSession = await apiFetch("/auth/sessions", {
|
||||
method: "POST",
|
||||
basicCredentials: {
|
||||
username,
|
||||
password,
|
||||
},
|
||||
});
|
||||
|
||||
setSession(createdSession);
|
||||
setPassword("");
|
||||
} catch (requestError) {
|
||||
setError(requestError.message);
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
}
|
||||
|
||||
async function handleCreateChat() {
|
||||
if (!me || !token) {
|
||||
return;
|
||||
}
|
||||
|
||||
setError("");
|
||||
setLoading(true);
|
||||
|
||||
try {
|
||||
const enteredMemberIds = memberIdsInput
|
||||
.split(",")
|
||||
.map((value) => value.trim())
|
||||
.filter(Boolean);
|
||||
|
||||
const uniqueMemberIds = [...new Set([me.id, ...enteredMemberIds])];
|
||||
|
||||
const created = await apiFetch("/chats", {
|
||||
method: "POST",
|
||||
token,
|
||||
body: {
|
||||
title: chatTitle,
|
||||
member_ids: uniqueMemberIds,
|
||||
},
|
||||
});
|
||||
|
||||
setChat(created);
|
||||
setMessages([]);
|
||||
setText("");
|
||||
} catch (requestError) {
|
||||
setError(requestError.message);
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
}
|
||||
|
||||
async function handleSendMessage() {
|
||||
if (!chat || !token) {
|
||||
return;
|
||||
}
|
||||
|
||||
setError("");
|
||||
setLoading(true);
|
||||
|
||||
try {
|
||||
const message = await apiFetch(`/chats/${chat.id}/messages`, {
|
||||
method: "POST",
|
||||
token,
|
||||
body: { text },
|
||||
});
|
||||
|
||||
setMessages((previous) => [...previous, message]);
|
||||
setText("");
|
||||
} catch (requestError) {
|
||||
setError(requestError.message);
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
}
|
||||
|
||||
async function handleLoadHistory() {
|
||||
if (!chat || !token) {
|
||||
return;
|
||||
}
|
||||
|
||||
setError("");
|
||||
setLoading(true);
|
||||
|
||||
try {
|
||||
const page = await apiFetch(`/chats/${chat.id}/messages?limit=100`, {
|
||||
token,
|
||||
});
|
||||
|
||||
setMessages(page.items);
|
||||
} catch (requestError) {
|
||||
setError(requestError.message);
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
}
|
||||
|
||||
async function handleLogout() {
|
||||
if (!token) {
|
||||
return;
|
||||
}
|
||||
|
||||
setError("");
|
||||
setLoading(true);
|
||||
|
||||
try {
|
||||
await apiFetch("/auth/sessions/current", {
|
||||
method: "DELETE",
|
||||
token,
|
||||
});
|
||||
|
||||
setSession(null);
|
||||
setChat(null);
|
||||
setMessages([]);
|
||||
setText("");
|
||||
setMemberIdsInput("");
|
||||
setChatTitle("");
|
||||
} catch (requestError) {
|
||||
setError(requestError.message);
|
||||
|
||||
// Если token уже истёк или был отозван, локальная сессия всё равно
|
||||
// недействительна, поэтому её следует очистить.
|
||||
if (
|
||||
requestError.message.includes("Authentication") ||
|
||||
requestError.message.includes("401")
|
||||
) {
|
||||
setSession(null);
|
||||
setChat(null);
|
||||
setMessages([]);
|
||||
}
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<div
|
||||
style={{
|
||||
maxWidth: 560,
|
||||
margin: "2rem auto",
|
||||
fontFamily: "sans-serif",
|
||||
}}
|
||||
>
|
||||
<h1>Lab2 Messenger — демо-клиент</h1>
|
||||
|
||||
{error && (
|
||||
<p
|
||||
role="alert"
|
||||
style={{
|
||||
color: "#b00020",
|
||||
background: "#ffe7eb",
|
||||
padding: "0.75rem",
|
||||
borderRadius: "0.25rem",
|
||||
}}
|
||||
>
|
||||
{error}
|
||||
</p>
|
||||
)}
|
||||
|
||||
{!me && (
|
||||
<section>
|
||||
<h2>Регистрация и вход</h2>
|
||||
|
||||
<p>
|
||||
После регистрации клиент автоматически создаст сессию через Basic
|
||||
authentication и начнёт использовать Bearer-token.
|
||||
</p>
|
||||
|
||||
<input
|
||||
placeholder="username: a-z, 0-9, _"
|
||||
value={username}
|
||||
onChange={(event) => setUsername(event.target.value)}
|
||||
autoComplete="username"
|
||||
/>
|
||||
|
||||
<input
|
||||
placeholder="display name"
|
||||
value={displayName}
|
||||
onChange={(event) => setDisplayName(event.target.value)}
|
||||
autoComplete="name"
|
||||
/>
|
||||
|
||||
<input
|
||||
type="password"
|
||||
placeholder="пароль: 12–128 символов"
|
||||
value={password}
|
||||
onChange={(event) => setPassword(event.target.value)}
|
||||
autoComplete="new-password"
|
||||
/>
|
||||
|
||||
<button
|
||||
type="button"
|
||||
onClick={handleRegister}
|
||||
disabled={loading}
|
||||
>
|
||||
{loading ? "Выполняется…" : "Зарегистрироваться и войти"}
|
||||
</button>
|
||||
</section>
|
||||
)}
|
||||
|
||||
{me && !chat && (
|
||||
<section>
|
||||
<p>
|
||||
Вошли как <b>{me.username}</b>
|
||||
</p>
|
||||
|
||||
<p style={{ overflowWrap: "anywhere" }}>
|
||||
ID пользователя: {me.id}
|
||||
</p>
|
||||
|
||||
<button
|
||||
type="button"
|
||||
onClick={handleLogout}
|
||||
disabled={loading}
|
||||
>
|
||||
Выйти
|
||||
</button>
|
||||
|
||||
<h2>Создать чат</h2>
|
||||
|
||||
<input
|
||||
placeholder="название чата"
|
||||
value={chatTitle}
|
||||
onChange={(event) => setChatTitle(event.target.value)}
|
||||
/>
|
||||
|
||||
<input
|
||||
placeholder="UUID других участников через запятую"
|
||||
value={memberIdsInput}
|
||||
onChange={(event) => setMemberIdsInput(event.target.value)}
|
||||
/>
|
||||
|
||||
<button
|
||||
type="button"
|
||||
onClick={handleCreateChat}
|
||||
disabled={loading}
|
||||
>
|
||||
{loading ? "Создаётся…" : "Создать чат"}
|
||||
</button>
|
||||
</section>
|
||||
)}
|
||||
|
||||
{me && chat && (
|
||||
<section>
|
||||
<p>
|
||||
Вошли как <b>{me.username}</b>
|
||||
</p>
|
||||
|
||||
<button
|
||||
type="button"
|
||||
onClick={handleLogout}
|
||||
disabled={loading}
|
||||
>
|
||||
Выйти
|
||||
</button>
|
||||
|
||||
<h2>Чат: {chat.title}</h2>
|
||||
|
||||
<p>
|
||||
Участники: {chat.member_ids.length}
|
||||
</p>
|
||||
|
||||
<button
|
||||
type="button"
|
||||
onClick={handleLoadHistory}
|
||||
disabled={loading}
|
||||
>
|
||||
{loading ? "Загружается…" : "Обновить историю"}
|
||||
</button>
|
||||
|
||||
<ul>
|
||||
{messages.map((message) => (
|
||||
<li key={message.id}>
|
||||
<b>
|
||||
{message.sender_id === me.id
|
||||
? "Я"
|
||||
: message.sender_id}
|
||||
:
|
||||
</b>{" "}
|
||||
{message.text}
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
|
||||
<input
|
||||
placeholder="текст сообщения"
|
||||
value={text}
|
||||
onChange={(event) => setText(event.target.value)}
|
||||
/>
|
||||
|
||||
<button
|
||||
type="button"
|
||||
onClick={handleSendMessage}
|
||||
disabled={loading}
|
||||
>
|
||||
{loading ? "Отправляется…" : "Отправить"}
|
||||
</button>
|
||||
</section>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
Reference in New Issue
Block a user