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

76
lib/api-utils.ts Normal file
View File

@@ -0,0 +1,76 @@
/**
* API utilities for consistent request handling
*/
/**
* Normalizes a URL to ensure it passes through the Next.js API proxy
* This ensures all client-side requests go through the Next.js rewrites.
*
* @param url The endpoint URL to normalize
* @returns A normalized URL with proper /api prefix
*/
export function normalizeApiUrl(url: string): string {
if (url.startsWith('/api/')) {
return url; // Already has /api/ prefix
} else {
// Add /api prefix, handling any leading slashes
const cleanUrl = url.startsWith('/') ? url : `/${url}`;
return `/api${cleanUrl}`;
}
}
/**
* Constructs a server-side API URL for backend requests
* Used in Server Components and API routes to directly access the backend API
*
* @param endpoint The API endpoint path
* @returns A complete URL to the backend API
*/
export function getServerApiUrl(endpoint: string): string {
const apiUrl = process.env.SERVER_API_URL || 'https://internal-api.inboxi.ng/api';
const cleanEndpoint = endpoint.startsWith('/') ? endpoint.substring(1) : endpoint;
return apiUrl.endsWith('/')
? `${apiUrl}${cleanEndpoint}`
: `${apiUrl}/${cleanEndpoint}`;
}
/**
* Get the authentication token from cookies or localStorage
*/
export function getAuthToken(): string | null {
if (typeof document === 'undefined') return null; // Guard for SSR
return document.cookie
.split('; ')
.find(row => row.startsWith('Authorization='))
?.split('=')[1] || localStorage.getItem('Authorization');
}
/**
* Check if the user is logged in
*/
export function isAuthenticated(): boolean {
return !!getAuthToken();
}
/**
* Creates standard API request headers with authentication
*
* @param token Optional auth token (fetched automatically if not provided)
* @param customHeaders Additional headers to include
* @returns Headers object ready for fetch requests
*/
export function createApiHeaders(token?: string | null, customHeaders: Record<string, string> = {}): Headers {
const headers = new Headers({
'Content-Type': 'application/json',
...customHeaders
});
const authToken = token || getAuthToken();
if (authToken) {
headers.set('Authorization', `Bearer ${authToken}`);
}
return headers;
}