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,6 +1,7 @@
'use client';
import { toast } from "@/components/ui/use-toast";
import { normalizeApiUrl, getAuthToken, createApiHeaders } from "./api-utils";
type FetchMethod = 'GET' | 'POST' | 'PUT' | 'DELETE' | 'PATCH';
@@ -11,53 +12,26 @@ interface FetchOptions {
headers?: HeadersInit;
}
// Helper function to get auth token from cookies
function getAuthToken(): string | null {
if (typeof document === 'undefined') return null; // Guard for SSR
return document.cookie
.split('; ')
.find(row => row.startsWith('Authorization='))
?.split('=')[1] || null;
}
/**
* Client-side fetch utility that ensures all requests go through the Next.js API proxy
*/
export async function fetchClient<T>(
endpoint: string,
options: FetchOptions = {}
): Promise<T> {
const { method = 'GET', body, headers = {}, ...rest } = options;
// Always use the Next.js API proxy by creating a path starting with /api/
// This ensures requests go through Next.js rewrites
const normalizedEndpoint = endpoint.startsWith('/') ? endpoint : `/${endpoint}`;
// Normalize the endpoint to ensure it starts with /api/
const url = normalizeApiUrl(endpoint);
// Construct the URL to always use the Next.js API routes
let url;
if (normalizedEndpoint.startsWith('/api/')) {
url = normalizedEndpoint; // Already has /api/ prefix
} else {
url = `/api${normalizedEndpoint}`; // Add /api/ prefix
}
// Get auth token from cookies
const authToken = getAuthToken();
// Prepare headers with authentication if token exists
const requestHeaders: Record<string, string> = {
'Content-Type': 'application/json',
...(headers as Record<string, string>),
};
if (authToken) {
// Backend expects "Bearer TOKEN" format
requestHeaders['Authorization'] = `Bearer ${authToken}`;
console.log('Authorization header set to:', `Bearer ${authToken.substring(0, 10)}...`);
}
// Get auth token and prepare headers
const requestHeaders = createApiHeaders(null, headers as Record<string, string>);
// Log request details (useful for debugging)
console.log('API Request:', {
url,
method,
hasAuthToken: !!authToken
hasAuthToken: requestHeaders.has('Authorization')
});
const fetchOptions: RequestInit = {
@@ -76,24 +50,22 @@ export async function fetchClient<T>(
if (!response.ok) {
const errorData = await response.json().catch(() => ({}));
const errorMessage = errorData.message || errorData.error || 'An error occurred';
const errorMessage = errorData.message || errorData.error || `Request failed with status ${response.status}`;
throw new Error(errorMessage);
}
// Handle 204 No Content responses
if (response.status === 204) {
return {} as T;
}
const data = await response.json();
return data;
return await response.json();
} catch (error) {
console.error('API request failed:', error);
// Only show toast if this is a client-side error (not during SSR)
// Only show toast in browser environment
if (typeof window !== 'undefined') {
const message = error instanceof Error ? error.message : 'Failed to connect to server';
toast({
title: 'Error',
description: message,