my-recipes/frontend/src/notificationApi.js

70 lines
2.2 KiB
JavaScript

const API_BASE_URL = window.__ENV__?.API_BASE || window._env_?.VITE_API_URL || import.meta.env.VITE_API_URL || "http://192.168.1.100:8000";
function getAuthHeaders() {
const token = localStorage.getItem("auth_token");
return {
"Content-Type": "application/json",
...(token && { Authorization: `Bearer ${token}` }),
};
}
export async function getNotifications(unreadOnly = false) {
const url = `${API_BASE_URL}/notifications${unreadOnly ? '?unread_only=true' : ''}`;
const response = await fetch(url, {
method: "GET",
headers: getAuthHeaders(),
});
if (!response.ok) {
if (response.status === 401) {
throw new Error("Unauthorized");
}
const errorData = await response.json().catch(() => ({ detail: "Failed to fetch notifications" }));
throw new Error(errorData.detail || "Failed to fetch notifications");
}
return response.json();
}
export async function markNotificationAsRead(notificationId) {
const response = await fetch(`${API_BASE_URL}/notifications/${notificationId}/read`, {
method: "PATCH",
headers: getAuthHeaders(),
});
if (!response.ok) {
const errorData = await response.json().catch(() => ({ detail: "Failed to mark notification as read" }));
throw new Error(errorData.detail || "Failed to mark notification as read");
}
return response.json();
}
export async function markAllNotificationsAsRead() {
const response = await fetch(`${API_BASE_URL}/notifications/read-all`, {
method: "PATCH",
headers: getAuthHeaders(),
});
if (!response.ok) {
const errorData = await response.json().catch(() => ({ detail: "Failed to mark all notifications as read" }));
throw new Error(errorData.detail || "Failed to mark all notifications as read");
}
return response.json();
}
export async function deleteNotification(notificationId) {
const response = await fetch(`${API_BASE_URL}/notifications/${notificationId}`, {
method: "DELETE",
headers: getAuthHeaders(),
});
if (!response.ok) {
const errorData = await response.json().catch(() => ({ detail: "Failed to delete notification" }));
throw new Error(errorData.detail || "Failed to delete notification");
}
return response.json();
}