hmmmammamam

This commit is contained in:
NotII
2025-03-24 00:08:32 +00:00
parent ce9f4e4d49
commit c65511aa5d
11 changed files with 229 additions and 123 deletions

View File

@@ -1,11 +1,17 @@
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="))
@@ -16,6 +22,7 @@ export const apiRequest = async <T = any>(endpoint: string, method: string = "GE
throw new Error("No authentication token found");
}
// Prepare request options
const options: RequestInit = {
method,
headers: {
@@ -29,16 +36,8 @@ export const apiRequest = async <T = any>(endpoint: string, method: string = "GE
options.body = JSON.stringify(body);
}
// Always use the Next.js API proxy to ensure all requests go through rewrites
// Format the endpoint to ensure it has the /api prefix
let url;
if (endpoint.startsWith('/api/')) {
url = endpoint; // Already has /api/ prefix
} else {
// Add /api prefix and ensure no duplicate slashes
const cleanEndpoint = endpoint.startsWith('/') ? endpoint : `/${endpoint}`;
url = `/api${cleanEndpoint}`;
}
// Normalize URL to ensure it uses the Next.js API proxy
const url = normalizeApiUrl(endpoint);
const res = await fetchData(url, options);
@@ -51,11 +50,11 @@ export const apiRequest = async <T = any>(endpoint: string, method: string = "GE
return res;
} catch (error: unknown) {
if (error instanceof Error) {
console.error(`🚨 API Request Error: ${error.message}`);
console.error(`API Request Error: ${error.message}`);
throw new Error(error.message);
}
console.error("An unknown error occurred", error);
console.error("An unknown error occurred", error);
throw new Error("An unknown error occurred");
}
};