survey-webapp/SurveyFrontend/src/api/BaseApi.ts
Tatiana Nikolaeva 5a1cc7c43c api requests
2025-05-22 20:23:09 +05:00

63 lines
No EOL
2 KiB
TypeScript
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.

const BASE_URL = "https://survey.slavagm.ru/api";
interface RequestConfig {
method: string;
headers: Record<string, string>;
body?: BodyInit | null;
}
/**
* Создаёт конфигурацию для fetch-запроса
* @param method HTTP-метод (GET, POST, PUT, DELETE)
* @param isFormData Флаг, указывающий, что отправляется FormData
* @returns Конфигурация для fetch-запроса
*/
const createRequestConfig = (method: string, isFormData: boolean = false): RequestConfig => {
const token = localStorage.getItem("token");
const config: RequestConfig = {
method,
headers: {},
};
// Добавляем заголовок авторизации, если есть токен
if (token) {
config.headers.Authorization = `Bearer ${token}`;
}
// Добавляем Content-Type, если это не FormData
if (!isFormData) {
config.headers["Content-Type"] = "application/json";
}
return config;
};
/**
* Обрабатывает ответ от сервера
* @param response Ответ от fetch
* @returns Распарсенные данные или ошибку
*/
const handleResponse = async (response: Response) => {
// Проверяем, есть ли контент в ответе
const responseText = await response.text();
if (!responseText) {
if (response.ok) {
return null; // Если ответ пустой, но статус 200, возвращаем null
}
throw new Error(`HTTP ${response.status}: ${response.statusText}`);
}
try {
const data = JSON.parse(responseText);
if (!response.ok) {
throw new Error(data.message || `HTTP ${response.status}`);
}
return data;
} catch (e) {
throw new Error(`Не удалось разобрать ответ сервера: ${e}`);
}
};
export { BASE_URL, createRequestConfig, handleResponse };