Files
ember-market-frontend/lib/storeHelper.ts
2025-03-24 00:08:32 +00:00

60 lines
1.7 KiB
TypeScript

import { fetchData } from '@/lib/data-service';
import { normalizeApiUrl } from './api-utils';
/**
* Sends authenticated API requests, ensuring they go through the Next.js API proxy
*/
export const apiRequest = async <T = any>(endpoint: string, method: string = "GET", body?: T | null) => {
try {
// Enforce client-side execution
if (typeof document === "undefined") {
throw new Error("API requests must be made from the client side.");
}
// Get authentication token
const authToken = document.cookie
.split("; ")
.find((row) => row.startsWith("Authorization="))
?.split("=")[1];
if (!authToken){
document.location.href = "/login";
throw new Error("No authentication token found");
}
// Prepare request options
const options: RequestInit = {
method,
headers: {
Authorization: `Bearer ${authToken}`,
"Content-Type": "application/json",
},
credentials: "include",
};
if (body) {
options.body = JSON.stringify(body);
}
// Normalize URL to ensure it uses the Next.js API proxy
const url = normalizeApiUrl(endpoint);
const res = await fetchData(url, options);
if (!res) {
const errorResponse = await res.json().catch(() => null);
const errorMessage = errorResponse?.error || res.statusText || "Unknown error";
throw new Error(`Failed to ${method} ${endpoint}: ${errorMessage}`);
}
return res;
} 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");
}
};