Posts API stage 2: one post at /posts/{id}, no legacy user-posts fallback

- Post detail and map focus load GET /api/v1/posts/{id}
- My posts use only GET /api/v1/users/{id}/posts
- README: requires the stage 2 backend (deploy backend first)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
SlimusMinus
2026-10-21 00:05:20 +03:00
parent d09c2c71ce
commit ec713f3da1
4 changed files with 19 additions and 32 deletions

View File

@@ -21,7 +21,7 @@ export default function PostDetailModal({ postId, onClose, onLocationClick, onAu
setLoading(true);
setError(null);
try {
const res = await apiFetch(`${API_URL}/api/v1/posts/detail/${postId}`);
const res = await apiFetch(`${API_URL}/api/v1/posts/${encodeURIComponent(postId)}`);
if (!res.ok) throw new Error("Failed to load post");
const data = await res.json();
if (!cancelled) {

View File

@@ -8,20 +8,15 @@ const PAGE_SIZE = 50;
const MAX_PAGES = 20;
/**
* Объявления пользователя: новый маршрут GET /api/v1/users/{userId}/posts
* (Page<PostResponse>). Подгружаем все страницы — «Мои объявления» показываются
* целиком, а своих объявлений у пользователя немного.
*
* @returns {Promise<object[]|null>} null — маршрута нет (старый бэкенд)
* Объявления пользователя: GET /api/v1/users/{userId}/posts (Page<PostResponse>).
* Подгружаем все страницы — «Мои объявления» показываются целиком, а своих
* объявлений у пользователя немного.
*/
async function fetchUserPostsPaged(userId) {
async function fetchUserPosts(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 ?? []);
@@ -32,15 +27,6 @@ async function fetchUserPostsPaged(userId) {
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.
*
@@ -61,7 +47,7 @@ export function useMyPosts(userId) {
setLoading(true);
setError("");
try {
const posts = (await fetchUserPostsPaged(userId)) ?? (await fetchUserPostsLegacy(userId));
const posts = await fetchUserPosts(userId);
if (requestId !== requestIdRef.current) return;
setMyAds(posts.map(ad => ({
...ad,

View File

@@ -337,7 +337,7 @@ export default function MainFeed() {
// Клик по локации на карточке — карта с фокусом на этом объявлении.
//
// Координаты берём из карточки, а если их там нет (объявление создано без
// карты, либо лента отдаёт null) — догружаем их из /api/v1/posts/detail/{id}.
// карты, либо лента отдаёт null) — догружаем их из /api/v1/posts/{id}.
// Без этого карта открывалась на дефолтном центре Москвы: MapView получает
// lat/lng из URL, а без них инициализируется на MAP_CENTER, и маркера
// объявления в загруженных границах нет — фокус не к чему было привязать.
@@ -350,9 +350,9 @@ export default function MainFeed() {
if (focusLat === null || focusLng === null) {
try {
// apiFetch, а не fetch: /detail/{id} владельцу отдаёт его собственные
// apiFetch, а не fetch: /posts/{id} владельцу отдаёт его собственные
// неопубликованные посты, а анонимному запросу бэкенд ответит 404.
const res = await apiFetch(`${API_URL}/api/v1/posts/detail/${ad.id}`);
const res = await apiFetch(`${API_URL}/api/v1/posts/${ad.id}`);
if (res.ok) {
const data = await res.json();
const detailLat = toCoordinate(data?.latitude);