Files
group-2-threaded-project-pe…/web/lib/cartApi.js
augmentedpotato 1010d57b79 Stripe Payment
2026-04-09 22:27:03 -06:00

85 lines
2.1 KiB
JavaScript

const BASE = "/api/v1/cart";
function authHeaders(token) {
return {
"Content-Type": "application/json",
Authorization: `Bearer ${token}`,
};
}
async function handleResponse(res) {
if (res.status === 204) return null;
const data = await res.json();
if (!res.ok) throw new Error(data.message || "Cart request failed");
return data;
}
export async function fetchCart(token, storeId) {
const res = await fetch(`${BASE}?storeId=${storeId}`, {
headers: authHeaders(token),
});
if (res.status === 204) return null;
const data = await res.json();
if (!res.ok) throw new Error(data.message || "Failed to fetch cart");
return data;
}
export async function apiAddToCart(token, { prodId, storeId, quantity }) {
const res = await fetch(`${BASE}/add`, {
method: "POST",
headers: authHeaders(token),
body: JSON.stringify({ prodId, storeId, quantity }),
});
return handleResponse(res);
}
export async function apiUpdateCartItem(token, { cartItemId, quantity }) {
const res = await fetch(`${BASE}/update`, {
method: "PUT",
headers: authHeaders(token),
body: JSON.stringify({ cartItemId, quantity }),
});
return handleResponse(res);
}
export async function apiRemoveCartItem(token, cartItemId) {
const res = await fetch(`${BASE}/remove/${cartItemId}`, {
method: "DELETE",
headers: authHeaders(token),
});
return handleResponse(res);
}
export async function apiClearCart(token, storeId) {
const res = await fetch(`${BASE}/clear?storeId=${storeId}`, {
method: "DELETE",
headers: authHeaders(token),
});
return handleResponse(res);
}
export async function apiApplyCoupon(token, storeId, couponCode) {
const res = await fetch(`${BASE}/apply-coupon?storeId=${storeId}`, {
method: "POST",
headers: authHeaders(token),
body: JSON.stringify({ couponCode }),
});
return handleResponse(res);
}
export async function apiCheckout(token, { storeId, paymentMethodId }) {
const res = await fetch(`${BASE}/checkout`, {
method: "POST",
headers: authHeaders(token),
body: JSON.stringify({ storeId, paymentMethodId }),
});
return handleResponse(res);
}