Files
nahodka-front/src/hooks/usePostMutation.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

79 lines
3.4 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 } from "react";
import { useTranslation } from 'react-i18next';
import { API_URL } from "../config/authConstants";
import { apiFetch } from "../api/apiClient";
import { describeApiError, readApiError } from "../api/apiErrors";
/**
* Универсальная мутация для создания и обновления объявления.
* Заменяет отдельные хуки useCreatePost и useUpdatePost.
*
* Логика выбора метода:
* id передан → PUT /api/v1/posts/:id (обновление)
* id не передан → POST /api/v1/posts (создание)
*
* В режиме adminMode (правка чужого объявления из админ-панели) используется
* PUT /api/v1/admin/posts/:id. Создание через админку не поддерживается:
* приходит без id — падаем обратно на пользовательский POST.
*
* Авторизация (Authorization header + авто-обновление токена при истечении)
* обрабатывается внутри apiFetch.
*
* save() возвращает:
* { ok: true, data } — успешный ответ сервера (data может быть null,
* если бэкенд ответил без тела)
* { blocked: true } — контент заблокирован модерацией
* null — серверная ошибка (свойство error содержит текст)
*
* @param {{adminMode?: boolean}} [options]
*/
export function usePostMutation({ adminMode = false } = {}) {
const { t } = useTranslation();
const [loading, setLoading] = useState(false);
const [error, setError] = useState("");
/**
* @param {string|null} id — id объявления при обновлении, null при создании
* @param {FormData} data — данные формы
* @returns {Promise<{ok:true,data:object|null}|{blocked:boolean, reason:string}|null>}
*/
const save = async (id, data) => {
setLoading(true);
setError("");
try {
const isAdminEdit = adminMode && !!id;
const url = isAdminEdit
? `${API_URL}/api/v1/admin/posts/${id}`
: (id ? `${API_URL}/api/v1/posts/${id}` : `${API_URL}/api/v1/posts`);
const method = id ? "PUT" : "POST";
const res = await apiFetch(url, {
method,
body: data,
});
if (!res.ok) {
const apiError = await readApiError(res);
// Причина блокировки — в message, метки модели — в details.labels
if (apiError.code === "CONTENT_BLOCKED") {
return { blocked: true, reason: apiError.serverMessage };
}
// 429 — лимит создания объявлений (20 в час), 413 — слишком большие
// фото, 400 — текст проверки полей с сервера
throw new Error(describeApiError(apiError, t('post.serverError', { status: res.status })));
}
let payload = null;
try { payload = await res.json(); } catch { payload = null; }
return { ok: true, data: payload };
} catch (e) {
setError(describeApiError(e, t('post.unknownError')));
return null;
} finally {
setLoading(false);
}
};
return { save, loading, error };
}