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

36 lines
1.1 KiB
TypeScript

export const apiRequest = async <T = any>(endpoint: string, method: string = "GET", body?: T | null) => {
try {
const authToken = document.cookie.split("; ").find(row => row.startsWith("Authorization="))?.split("=")[1];
if (!authToken) throw new Error("No authentication token found");
const options: RequestInit = {
method,
headers: {
Authorization: `Bearer ${authToken}`,
"Content-Type": "application/json",
},
credentials: "include",
};
if (body) {
options.body = JSON.stringify(body);
}
const res = await fetch(`${process.env.NEXT_PUBLIC_API_URL}${endpoint}`, options);
if (!res.ok) {
throw new Error(`Failed to ${method} ${endpoint}: ${res.statusText}`);
}
return await res.json();
} catch (error: unknown) {
if (error instanceof Error) {
console.error(`Error in API request: ${error.message}`);
throw new Error(error.message);
}
console.error("An unknown error occurred", error);
throw new Error("An unknown error occurred");
}
};