Files
ember-market-frontend/lib/shippingHelper.ts
2025-02-07 04:43:47 +00:00

108 lines
2.7 KiB
TypeScript

export const fetchShippingMethods = async (authToken: string) => {
try {
const res = await fetch(
`${process.env.NEXT_PUBLIC_API_URL}/shipping-options`,
{
headers: {
Authorization: `Bearer ${authToken}`,
"Content-Type": "application/json",
},
credentials: "include",
}
);
if (!res.ok) throw new Error("Failed to fetch shipping options");
return await res.json();
} catch (error) {
console.error("Error loading shipping options:", error);
throw error;
}
};
interface ShippingMethod {
name: string;
price: number;
_id?: string;
}
export const addShippingMethod = async (
authToken: string,
newShipping: Omit<ShippingMethod, "_id">
): Promise<ShippingMethod[]> => {
try {
const res = await fetch(
`${process.env.NEXT_PUBLIC_API_URL}/shipping-options`,
{
method: "POST",
headers: {
Authorization: `Bearer ${authToken}`,
"Content-Type": "application/json",
},
credentials: "include",
body: JSON.stringify(newShipping),
}
);
if (!res.ok) {
const errorData = await res.json();
throw new Error(errorData.message || "Failed to add shipping method");
}
return await res.json();
} catch (error) {
console.error("Error adding shipping method:", error);
throw new Error(
error instanceof Error
? error.message
: "An unexpected error occurred while adding shipping method"
);
}
};
export const deleteShippingMethod = async (authToken: string, id: string) => {
try {
const res = await fetch(
`${process.env.NEXT_PUBLIC_API_URL}/shipping-options/${id}`,
{
method: "DELETE",
headers: { Authorization: `Bearer ${authToken}` },
credentials: "include",
}
);
if (!res.ok) throw new Error("Failed to delete shipping method");
// Since there is no content, just return success status.
return { success: res.status === 204 };
} catch (error) {
console.error("Error deleting shipping method:", error);
throw error;
}
};
export const updateShippingMethod = async (
authToken: string,
id: string,
updatedShipping: any
) => {
try {
const res = await fetch(
`${process.env.NEXT_PUBLIC_API_URL}/shipping-options/${id}`,
{
method: "PUT",
headers: {
Authorization: `Bearer ${authToken}`,
"Content-Type": "application/json",
},
credentials: "include",
body: JSON.stringify(updatedShipping),
}
);
if (!res.ok) throw new Error("Failed to update shipping method");
return await res.json();
} catch (error) {
console.error("Error updating shipping method:", error);
throw error;
}
};