Files
nahodka-front/src/hooks/useChats.js
SlimusMinus db37befb8d Support new backend contracts: single-flight refresh, ad impression tokens, error handling
- apiFetch: proactive refresh, cross-tab single-flight via Web Locks, no logout on transient errors
- AuthContext: save tokens returned on own login change, revoke refresh on logout, sync tabs
- Ads: X-Session-Id, impressionToken in impression/click, IAB viewability, safe http(s) targetUrl
- STOMP: refresh before CONNECT, stop reconnect loop on dead session, /user/queue/errors behind flag
- Auth form: password 8 chars / 72 bytes; 429/413 messages via describeApiError
- My posts with auth + moderation badges; post form step validation and field limits
- Map: escape user text in Yandex hint/template

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-20 02:03:42 +03:00

131 lines
6.1 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

import { useState, useCallback, useRef } from "react";
import { useTranslation } from 'react-i18next';
import { API_URL } from "../config/authConstants";
import { apiFetch } from "../api/apiClient";
import { readApiError } from "../api/apiErrors";
import { cachePostsFromChats, setPostForChat } from "../stores/chatPostStore";
import { useUnread } from "../context/UnreadContext";
export function useChats() {
const { t } = useTranslation();
const [chats, setChats] = useState([]);
// Стартуем в состоянии загрузки: иначе самый первый рендер успевает показать
// "Нет чатов" до того, как эффект выставит loading — список "моргает".
const [loading, setLoading] = useState(true);
const [error, setError] = useState("");
const { updateFromChats, clearChatUnread } = useUnread();
// fetchChats дёргается и при монтировании, и на каждое изменение totalUnread —
// без guard'а медленный предыдущий ответ воскрешал бы прочитанные счётчики.
const requestIdRef = useRef(0);
// silent=true — фоновое обновление списка (новое сообщение по WS, удаление
// чата и т.п.): не трогаем loading, иначе текущий список на миг подменяется
// экраном загрузки и страница "моргает".
const fetchChats = useCallback(async ({ silent = false } = {}) => {
const requestId = ++requestIdRef.current;
if (!silent) setLoading(true);
setError("");
try {
const res = await apiFetch(`${API_URL}/api/v1/chats`);
if (!res.ok) throw new Error(t('chats.fetchError'));
const data = await res.json();
if (requestId !== requestIdRef.current) return; // устаревший ответ
const list = Array.isArray(data) ? data : (data.items ?? data.content ?? []);
cachePostsFromChats(list);
setChats(list);
updateFromChats(list);
} catch (e) {
if (requestId !== requestIdRef.current) return;
setError(e.message || t('chats.fetchError'));
} finally {
if (requestId === requestIdRef.current && !silent) setLoading(false);
}
}, [updateFromChats, t]);
/**
* Существующий чат с пользователем по объявлению или null, если переписки ещё нет.
* Ничего не создаёт: чат появляется только вместе с первым сообщением (startChat).
*/
const findChat = useCallback(async (otherUserId, postId, postInfo) => {
const res = await apiFetch(chatWithUrl(otherUserId, postId));
if (res.status === 404) return null;
if (!res.ok) {
await logChatError("findChat", res);
throw new Error(t('chats.createError'));
}
const chat = await res.json();
cacheChatPost(chat, postInfo);
return chat;
}, [t]);
/** Отправляет первое сообщение: бэкенд создаёт (или находит) чат вместе с ним. */
const startChat = useCallback(async (otherUserId, postId, content, postInfo) => {
const res = await apiFetch(chatWithUrl(otherUserId, postId, "/messages"), {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ content }),
});
if (!res.ok) {
// ApiError несёт статус и текст сервера: ChatPage покажет «слишком
// много попыток» на 429 и причину отказа на 400
const err = await readApiError(res);
console.warn("startChat failed:", err.status, err.serverMessage);
throw err;
}
const chat = await res.json();
cacheChatPost(chat, postInfo);
return chat;
}, []);
const fetchMessages = useCallback(async (chatId) => {
const res = await apiFetch(`${API_URL}/api/v1/chats/${chatId}/messages`);
// Без этой проверки 5xx с JSON-телом ошибки превращался в пустой список,
// и только что отправленное сообщение выглядело как потерянное.
if (!res.ok) throw new Error(`Error ${res.status}`);
const data = await res.json();
return Array.isArray(data) ? data : (data.items ?? data.content ?? []);
}, []);
const markAsRead = useCallback(async (chatId) => {
clearChatUnread(chatId);
try {
await apiFetch(`${API_URL}/api/v1/chats/${chatId}/read`, {
method: "POST",
});
} catch (e) {
console.error("Failed to mark as read:", e);
}
}, [clearChatUnread]);
return { chats, loading, error, fetchChats, findChat, startChat, fetchMessages, markAsRead };
}
function chatWithUrl(otherUserId, postId, suffix = "") {
const url = new URL(`${API_URL}/api/v1/chats/with/${otherUserId}${suffix}`);
if (postId) url.searchParams.set("postId", postId);
return url;
}
// Причину отказа (чат с собой, чужое объявление и т.п.) пишем в консоль,
// иначе 400 выглядит как необъяснимый сбой
async function logChatError(action, res) {
const body = await res.json().catch(() => null);
console.warn(`${action} failed:`, res.status, body?.message);
}
/**
* Объявление чата берём из ответа бэкенда: если чат оказался по другому
* объявлению, postInfo с карточки привязал бы к нему чужую картинку.
* postInfo — только дополнение (emoji) для того же объявления.
*/
function cacheChatPost(chat, postInfo) {
if (!chat?.id) return;
const sameAd = postInfo && (chat.post?.id ?? chat.postId) != null
&& String(chat.post?.id ?? chat.postId) === String(postInfo.id);
if (chat.post) {
setPostForChat(chat.id, { ...(sameAd ? postInfo : {}), ...chat.post });
} else if (sameAd) {
setPostForChat(chat.id, postInfo);
}
}