Files
magistr/frontend/react/shared/api-client.js
dipatrik10 9458a4a59d fix(frontend): исправлены дефекты P1 из аудита React (2.1-2.4)
2.1 Гонки запросов: общий механизм latest-request-wins
- shared/latest-request.js (createLatestRequest) + use-latest-request.js
- clientWithSignal в api-client.js: AbortSignal без правки сигнатур сервисов
- ScheduleViewTab/ScheduleVersionsTab/ScheduleQualityTab/RequestDialog:
  устаревшие ответы не применяются, кнопки блокируются на время загрузки
- смена семестра в анализе качества очищает зависимые данные

2.2 Пожелания преподавателя: semesterId=0 невозможен
- resolveDefaultSemester: текущий -> ближайший будущий -> последний завершённый
- явный пустой пункт «Выберите семестр», блокировка сетки/дат/переключателей
- кнопка «Повторить» при ошибке метаданных

2.3 Dirty/hash-навигация: отмена возвращает URL через replaceState
- confirmedHashRef + navigatingRef, hash-эффект с [role] deps

2.4 Диалог заявки: ошибка отправки показывается, диалог не закрывается
- контракт onSubmitted true/false, защита от двойной отправки

Тесты: latest-request.test.mjs (14 сценариев) + статические проверки
в тематических тестах; всего 266 проверок, бюджеты бандлов в норме
(teacher cold load 88648/90000 gzip).
2026-10-11 21:08:29 +03:00

117 lines
3.7 KiB
JavaScript

import { clearAuthState, fetchWithAuth } from '../../auth-session.js';
const DEFAULT_API_ERROR = 'Не удалось выполнить запрос';
const UNAUTHORIZED_ERROR = 'Требуется повторный вход в систему';
export class ApiRequestError extends Error {
constructor(message, { data = null, status = 0 } = {}) {
super(message);
this.name = 'ApiRequestError';
this.data = data;
this.status = status;
}
}
export async function requestJson(
endpoint,
{ errorMessage = DEFAULT_API_ERROR, headers: initialHeaders, json, ...options } = {},
{
fetchImpl = fetchWithAuth,
onUnauthorized = () => window.location.replace('/')
} = {}
) {
if (typeof endpoint !== 'string' || !endpoint.startsWith('/api/')) {
throw new ApiRequestError('Разрешены только same-origin запросы к API');
}
const headers = new Headers(initialHeaders || {});
headers.set('Accept', 'application/json');
let body = options.body;
if (json !== undefined) {
headers.set('Content-Type', 'application/json');
body = JSON.stringify(json);
}
const response = await fetchImpl(endpoint, {
...options,
body,
headers
});
const data = await readResponseData(response);
if (response.status === 401) {
clearAuthState();
onUnauthorized();
throw new ApiRequestError(UNAUTHORIZED_ERROR, { data, status: response.status });
}
if (!response.ok) {
throw new ApiRequestError(errorMessage, { data, status: response.status });
}
return data;
}
export const apiClient = Object.freeze({
delete: (endpoint, options = {}, dependencies) => requestJson(
endpoint,
{ ...options, method: 'DELETE' },
dependencies
),
get: (endpoint, options = {}, dependencies) => requestJson(
endpoint,
{ ...options, method: 'GET' },
dependencies
),
post: (endpoint, json, options = {}, dependencies) => requestJson(
endpoint,
{ ...options, json, method: 'POST' },
dependencies
),
put: (endpoint, json, options = {}, dependencies) => requestJson(
endpoint,
{ ...options, json, method: 'PUT' },
dependencies
)
});
/**
* Привязка AbortSignal к клиенту: каждый запрос обёртки передаёт сигнал
* в fetch, поэтому устаревший запрос прерывается защитой от гонок
* (см. shared/latest-request.js). Без сигнала возвращается исходный
* клиент без обёртки.
*/
export function clientWithSignal(client, signal) {
if (!signal) return client;
const withSignal = options => ({ ...(options || {}), signal });
return {
get: (endpoint, options, dependencies) => client.get(endpoint, withSignal(options), dependencies),
post: (endpoint, json, options, dependencies) => client.post(endpoint, json, withSignal(options), dependencies),
put: (endpoint, json, options, dependencies) => client.put(endpoint, json, withSignal(options), dependencies),
delete: (endpoint, options, dependencies) => client.delete(endpoint, withSignal(options), dependencies)
};
}
async function readResponseData(response) {
if (response.status === 204) {
return null;
}
const text = await response.text();
if (!text) {
return null;
}
const contentType = response.headers.get('Content-Type') || '';
if (!contentType.includes('application/json')) {
return text;
}
try {
return JSON.parse(text);
} catch (error) {
return null;
}
}