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>
This commit is contained in:
SlimusMinus
2026-10-20 02:03:42 +03:00
parent 67de963d6d
commit db37befb8d
34 changed files with 1005 additions and 260 deletions

96
src/api/apiErrors.js Normal file
View File

@@ -0,0 +1,96 @@
// src/api/apiErrors.js
import i18n from "../i18n";
/**
* Ошибка REST-запроса к бэкенду.
*
* Бэкенд отвечает в формате ErrorResponse
* {timestamp, status, error, message, path, details}; /auth/login и
* /auth/register — 400 {message}; фильтр безопасности — 401/403 {message}.
* Здесь всё это сводится к одному объекту, чтобы UI не разбирал тело сам.
*/
export class ApiError extends Error {
constructor(status, { code = null, message = "", details = null, retryAfterSeconds = null } = {}) {
super(message || `HTTP ${status}`);
this.name = "ApiError";
this.status = status;
this.code = code;
this.details = details;
this.retryAfterSeconds = retryAfterSeconds;
// Было ли сообщение прислано сервером (а не собрано из статуса)
this.serverMessage = message || "";
}
}
/**
* Retry-After бывает числом секунд или HTTP-датой. Заголовок доступен
* только если бэкенд отдаёт его в Access-Control-Expose-Headers (иначе при
* кросс-доменном запросе браузер его прячет) — тогда вернётся null.
*/
export function parseRetryAfter(value, now = Date.now()) {
if (!value) return null;
const trimmed = String(value).trim();
if (/^\d+$/.test(trimmed)) return Number(trimmed);
const date = Date.parse(trimmed);
if (Number.isNaN(date)) return null;
return Math.max(0, Math.ceil((date - now) / 1000));
}
/** Читает тело ошибки и собирает ApiError. Тело может быть пустым или не JSON. */
export async function readApiError(res) {
let body = null;
try {
body = await res.json();
} catch {
body = null;
}
return new ApiError(res.status, {
code: typeof body?.error === "string" ? body.error : null,
message: typeof body?.message === "string" ? body.message : "",
details: body?.details ?? null,
retryAfterSeconds: parseRetryAfter(res.headers?.get?.("Retry-After")),
});
}
/** Бросает ApiError, если ответ не 2xx; иначе возвращает сам ответ. */
export async function ensureOk(res) {
if (!res.ok) throw await readApiError(res);
return res;
}
export function isRateLimited(err) {
return err?.status === 429;
}
/**
* Текст ошибки для пользователя.
*
* - 429 — «слишком много попыток, повторите через N мин» (без автоповтора:
* повтор в цикле только продлил бы блокировку);
* - 413 — файл больше лимита бэкенда;
* - сбой сети (fetch бросил TypeError) — «нет связи»;
* - 400/404/409/422 — сообщение бэкенда (оно на русском и по делу);
* - остальное (5xx и т.п.) — переданный fallback.
*/
export function describeApiError(err, fallback) {
const t = i18n.t.bind(i18n);
if (!err) return fallback || t("errors.unknown");
if (err.status === 429) {
const seconds = err.retryAfterSeconds;
if (seconds && seconds > 0) {
return seconds >= 60
? t("errors.tooManyRequestsMinutes", { minutes: Math.ceil(seconds / 60) })
: t("errors.tooManyRequestsSeconds", { seconds });
}
return err.serverMessage || t("errors.tooManyRequests");
}
if (err.status === 413) return t("errors.payloadTooLarge");
if (err instanceof TypeError || err.name === "TypeError") return t("errors.network");
if (err instanceof ApiError) {
if (err.status >= 400 && err.status < 500 && err.serverMessage) return err.serverMessage;
return fallback || t("errors.unknown");
}
return err.message || fallback || t("errors.unknown");
}