Update the store helper and broadcast dialog
This commit is contained in:
@@ -1,36 +1,54 @@
|
||||
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");
|
||||
try {
|
||||
if (typeof document === "undefined") {
|
||||
throw new Error("API requests must be made from the client side.");
|
||||
}
|
||||
};
|
||||
|
||||
|
||||
const authToken = document.cookie
|
||||
.split("; ")
|
||||
.find((row) => row.startsWith("Authorization="))
|
||||
?.split("=")[1];
|
||||
|
||||
if (!authToken){
|
||||
// go to /login
|
||||
document.location.href = "/login";
|
||||
throw new Error("No authentication token found");
|
||||
}
|
||||
|
||||
// ✅ API Request Options
|
||||
const options: RequestInit = {
|
||||
method,
|
||||
headers: {
|
||||
Authorization: `Bearer ${authToken}`,
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
credentials: "include",
|
||||
};
|
||||
|
||||
if (body) {
|
||||
options.body = JSON.stringify(body);
|
||||
}
|
||||
|
||||
const API_URL = process.env.NEXT_PUBLIC_API_URL;
|
||||
if (!API_URL) throw new Error("NEXT_PUBLIC_API_URL is not set in environment variables");
|
||||
|
||||
const res = await fetch(`${API_URL}${endpoint}`, options);
|
||||
|
||||
if (!res.ok) {
|
||||
const errorResponse = await res.json().catch(() => null);
|
||||
const errorMessage = errorResponse?.error || res.statusText || "Unknown error";
|
||||
throw new Error(`Failed to ${method} ${endpoint}: ${errorMessage}`);
|
||||
}
|
||||
|
||||
// ✅ Return JSON response
|
||||
return await res.json();
|
||||
} catch (error: unknown) {
|
||||
if (error instanceof Error) {
|
||||
console.error(`🚨 API Request Error: ${error.message}`);
|
||||
throw new Error(error.message);
|
||||
}
|
||||
|
||||
console.error("❌ An unknown error occurred", error);
|
||||
throw new Error("An unknown error occurred");
|
||||
}
|
||||
};
|
||||
Reference in New Issue
Block a user