query functions for response options

This commit is contained in:
Tatiana Nikolaeva 2025-05-25 00:08:36 +05:00
parent 51f3469031
commit e961d53d6c
5 changed files with 106 additions and 17 deletions

View file

@ -0,0 +1,85 @@
import {BASE_URL, createRequestConfig, handleResponse} from "./BaseApi.ts";
export const getAnswerVariants = async (surveyId: number, questionId: number) => {
try{
const response = await fetch(`${BASE_URL}/surveys/${surveyId}/questions/${questionId}/answerVariants`, {
...createRequestConfig('GET')
})
return await handleResponse(response)
}catch(err){
console.error(`Error receiving response options: ${err}`);
throw err;
}
}
export const addNewAnswerVariant = async (surveyId: number, questionId: number) => {
const token = localStorage.getItem("token");
if (!token) {
throw new Error("Токен отсутствует");
}
try{
const response = await fetch(`${BASE_URL}/surveys/${surveyId}/questions/${questionId}/answerVariants`, {
...createRequestConfig('POST'),
body: JSON.stringify({
surveyId: surveyId,
questionId: questionId,
}),
})
if (!response.ok) {
throw new Error(`Ошибка: ${response.status}`);
}
return await handleResponse(response)
}
catch(err){
console.error(`Error adding a new response option: ${err}`);
throw err;
}
}
export const updateAnswerVariant = async (surveyId: number, questionId: number, id: number) => {
const token = localStorage.getItem("token");
if (!token) {
throw new Error("Токен отсутствует");
}
try{
const response = await fetch(`${BASE_URL}/surveys/${surveyId}/questions/${questionId}/answerVariants/${id}`, {
...createRequestConfig('PUT'),
body: JSON.stringify({
surveyId: surveyId,
questionId: questionId,
id: id
})
})
if (!response.ok) {
throw new Error(`Ошибка: ${response.status}`);
}
return await handleResponse(response)
}
catch(err){
console.error(`Error updating the response option: ${err}`);
}
}
export const deleteAnswerVariant = async (surveyId: number, questionId: number, id: number) => {
const token = localStorage.getItem("token");
if (!token) {
throw new Error('Токен отсутствует');
}
try{
const response = await fetch(`${BASE_URL}/surveys/${surveyId}/questions/${questionId}/answerVariants/${id}`, {
...createRequestConfig('DELETE'),
})
const responseData = await handleResponse(response);
if (response.ok && !responseData){
return {success: true};
}
return responseData;
}
catch(err){
console.error(`Error deleting a answer: ${err}`);
throw err;
}
}

View file

@ -10,16 +10,10 @@ interface IRegistrationData extends IAuthData{
firstName: string; firstName: string;
lastName: string; lastName: string;
} }
//
// interface IUserData{
// username: string;
// firstName: string;
// lastName: string;
// email: string;
// }
export const getCurrentUser = async (): Promise<IRegistrationData> => { export const getCurrentUser = async (): Promise<IRegistrationData> => {
const token = localStorage.getItem("token"); const token = localStorage.getItem("token");
if (!token) { if (!token) {
throw new Error("Токен отсутствует"); throw new Error("Токен отсутствует");
} }
@ -32,6 +26,8 @@ export const getCurrentUser = async (): Promise<IRegistrationData> => {
} }
}); });
console.log(response);
if (response.status === 401) { if (response.status === 401) {
localStorage.removeItem("token"); localStorage.removeItem("token");
throw new Error("Сессия истекла. Пожалуйста, войдите снова."); throw new Error("Сессия истекла. Пожалуйста, войдите снова.");

View file

@ -20,12 +20,10 @@ const createRequestConfig = (method: string, isFormData: boolean = false): Reque
headers: {}, headers: {},
}; };
// Добавляем заголовок авторизации, если есть токен
if (token) { if (token) {
config.headers.Authorization = `Bearer ${token}`; config.headers.Authorization = `Bearer ${token}`;
} }
// Добавляем Content-Type, если это не FormData
if (!isFormData) { if (!isFormData) {
config.headers["Content-Type"] = "application/json"; config.headers["Content-Type"] = "application/json";
} }
@ -39,12 +37,16 @@ const createRequestConfig = (method: string, isFormData: boolean = false): Reque
* @returns Распарсенные данные или ошибку * @returns Распарсенные данные или ошибку
*/ */
const handleResponse = async (response: Response) => { const handleResponse = async (response: Response) => {
// Проверяем, есть ли контент в ответе
const responseText = await response.text(); const responseText = await response.text();
if (!responseText) { if (!responseText) {
if (response.status === 401) {
window.location.href = '/auth/login';
throw new Error('Требуется авторизация');
}
if (response.ok) { if (response.ok) {
return null; // Если ответ пустой, но статус 200, возвращаем null return null;
} }
throw new Error(`HTTP ${response.status}: ${response.statusText}`); throw new Error(`HTTP ${response.status}: ${response.statusText}`);
} }

View file

@ -5,14 +5,16 @@ export interface INewQuestion{
questionType: string; questionType: string;
} }
export interface IQuestion extends INewQuestion { export interface IAnswerVariant{
id: number;
surveyId: number;
answerVariants: Array<{
id: number; id: number;
questionId: number; questionId: number;
text: string; text: string;
}> }
export interface IQuestion extends INewQuestion {
id: number;
surveyId: number;
answerVariants: IAnswerVariant[];
} }
export const addNewQuestion = async (surveyId: number, question: INewQuestion) => { export const addNewQuestion = async (surveyId: number, question: INewQuestion) => {

View file

@ -13,12 +13,16 @@ export interface Question {
id: number; id: number;
text: string; text: string;
questionType: 'singleanswerquestion' | 'multipleanswerquestion'; questionType: 'singleanswerquestion' | 'multipleanswerquestion';
answerVariants?: {
id?: number;
text: string;
}[];
} }
const QuestionsList: React.FC<QuestionsListProps> = ({questions, setQuestions, surveyId}) => { const QuestionsList: React.FC<QuestionsListProps> = ({questions, setQuestions, surveyId}) => {
const [selectedType, setSelectedType] = useState<'single' | 'multiply'>('single'); const [selectedType, setSelectedType] = useState<'single' | 'multiply'>('single');
const [localQuestionId, setLocalQuestionId] = useState(1001); // Начинаем с 2, так как первый вопрос имеет ID=1 const [localQuestionId, setLocalQuestionId] = useState(2);
const handleAddQuestion = () => { const handleAddQuestion = () => {
const newQuestion: Question = { const newQuestion: Question = {