Files
nahodka-front/src/hooks/useMyPosts.jsx
SlimusMinus 804018d2ce Campaign stats in admin, user posts via new route, safer ad creation
- Admin: campaign stats panel (impressions, clicks, CTR per campaign and ad) with date range
- My posts: GET /api/v1/users/{id}/posts with paging, fallback to the legacy route
- Ad creation: retry after a failed video upload reuses the created ad; show backend 400 text
- Fullscreen ad form: only absolute http(s) target URLs

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

80 lines
3.7 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 { API_URL } from "../config/authConstants";
import { apiFetch } from "../api/apiClient";
// Максимальный size страницы у бэкенда (spring.data.web.pageable.max-page-size)
const PAGE_SIZE = 50;
// Защита от бесконечного цикла, если бэкенд вдруг не отдаст признак last
const MAX_PAGES = 20;
/**
* Объявления пользователя: новый маршрут GET /api/v1/users/{userId}/posts
* (Page<PostResponse>). Подгружаем все страницы — «Мои объявления» показываются
* целиком, а своих объявлений у пользователя немного.
*
* @returns {Promise<object[]|null>} null — маршрута нет (старый бэкенд)
*/
async function fetchUserPostsPaged(userId) {
const all = [];
for (let page = 0; page < MAX_PAGES; page++) {
const params = new URLSearchParams({ page, size: PAGE_SIZE, sort: "createdAt,desc" });
const res = await apiFetch(`${API_URL}/api/v1/users/${userId}/posts?${params}`);
// Старый бэкенд: маршрута нет (404) либо /users/** закрыт без токена и
// неизвестный путь падает в 500 — откатываемся на прежний эндпоинт
if (page === 0 && (res.status === 404 || res.status === 405 || res.status >= 500)) return null;
if (!res.ok) throw new Error(`Error ${res.status}`);
const data = await res.json();
const items = Array.isArray(data) ? data : (data.content ?? data.items ?? []);
all.push(...items);
const last = Array.isArray(data) || typeof data.last !== "boolean" ? items.length < PAGE_SIZE : data.last;
if (last) break;
}
return all;
}
/** Прежний маршрут: GET /api/v1/posts/{userId} — список без пагинации. */
async function fetchUserPostsLegacy(userId) {
const res = await apiFetch(`${API_URL}/api/v1/posts/${userId}`);
if (res.status === 404) return [];
if (!res.ok) throw new Error(`Error ${res.status}`);
const data = await res.json();
return Array.isArray(data) ? data : (data.items ?? data.content ?? []);
}
/**
* Загружает объявления текущего пользователя по userId.
*
* Запросы — через apiFetch: своему автору бэкенд отдаёт и неопубликованные
* объявления (MODERATION/REJECTED), но только авторизованному запросу.
*/
export function useMyPosts(userId) {
const [myAds, setMyAds] = useState([]);
const [loading, setLoading] = useState(false);
const [error, setError] = useState("");
// Ответ для прошлого пользователя (вышли и вошли под другим) не должен
// перетереть список нового
const requestIdRef = useRef(0);
const loadMyPosts = useCallback(async () => {
if (!userId) return;
const requestId = ++requestIdRef.current;
setLoading(true);
setError("");
try {
const posts = (await fetchUserPostsPaged(userId)) ?? (await fetchUserPostsLegacy(userId));
if (requestId !== requestIdRef.current) return;
setMyAds(posts.map(ad => ({
...ad,
type: ad.type ? ad.type.toLowerCase() : "loss",
})));
} catch (err) {
if (requestId !== requestIdRef.current) return;
setError(err.message || "Failed to load your ads");
} finally {
if (requestId === requestIdRef.current) setLoading(false);
}
}, [userId]);
return { myAds, loading, error, loadMyPosts };
}