survey-webapp/SurveyFrontend/src/api/AnswerApi.ts
2025-05-25 00:08:36 +05:00

85 lines
No EOL
2.7 KiB
TypeScript

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;
}
}