app/frontend/app/utils/api/dishApi.ts

149 lines
3.7 KiB
TypeScript

import {DishType} from "@/types/DishType";
import {apiRequest} from "@/utils/api/apiRequest";
export const listDishes = async (): Promise<DishType[]> => {
const token = localStorage.getItem('token');
if (!token) {
throw new Error('No token found in localStorage.');
}
return apiRequest.get(`/api/dishes`, {
headers: {
Authorization: `Bearer ${token}`,
}})
.then((data) => {
if (data?.payload?.dishes) {
return data.payload.dishes as DishType[];
}
throw new Error('SOMETHING WENT WRONG');
})
.catch((error) => {
throw error;
});
};
export const fetchDish = async (id: number): Promise<DishType> => {
const token = localStorage.getItem('token');
if (!token) {
throw new Error('No token found in localStorage.');
}
return apiRequest.get(`/api/dishes/${id}`, {
headers: {
Authorization: `Bearer ${token}`,
}})
.then((data) => {
if (data?.payload?.dish) {
return data.payload.dish as DishType;
}
throw new Error('SOMETHING WENT WRONG');
})
.catch((error) => {
throw error;
});
};
export const createDish = async (
name: string,
// recurrence: number,
// userIds: number[]
) => {
const token = localStorage.getItem('token');
if (!token) {
throw new Error('No token found in localStorage.');
}
return apiRequest.post(`/api/dishes`, {
name,
// recurrence,
// users: userIds,
}, {
headers: {
Authorization: `Bearer ${token}`,
},
}).catch(() => {
throw new Error("Failed to create dish. Please try again later.");
});
};
export const updateDish = async (dish_id: number, name: string) => {
const token = localStorage.getItem('token');
if (!token) {
throw new Error('No token found in localStorage.');
}
return apiRequest.put(`/api/dishes/${dish_id}`, {name}, {
headers: {
Authorization: `Bearer ${token}`,
}})
.catch((error) => {
throw error;
});
};
export const deleteDish = async (id: number) => {
const token = localStorage.getItem('token');
if (!token) {
throw new Error('No token found in localStorage.');
}
return apiRequest.delete(`/api/dishes/${id}`, {
headers: {
Authorization: `Bearer ${token}`,
}})
.then((data) => {
return data;
})
.catch((error) => {
throw error;
});
};
export const addUserToDish = async (dish_id: number, user_id: number) => {
const token = localStorage.getItem('token');
if (!token) {
throw new Error('No token found in localStorage.');
}
return apiRequest.post(`/api/dishes/${dish_id}/users/add`, {
users: [user_id],
}, {
headers: {
Authorization: `Bearer ${token}`,
}
})
.then((data) => {
return data;
})
.catch((error) => {
throw error;
});
};
export const removeUserFromDish = async (dish_id: number, user_id: number) => {
const token = localStorage.getItem('token');
if (!token) {
throw new Error('No token found in localStorage.');
}
return apiRequest.post(`/api/dishes/${dish_id}/users/remove`, {
users: [user_id],
}, {
headers: {
Authorization: `Bearer ${token}`,
}
})
.then((data) => {
return data;
})
.catch((error) => {
throw error;
});
};