slight cleanup

This commit is contained in:
g
2025-02-07 19:30:49 +00:00
parent 40635ae667
commit 8900bbcc76
11 changed files with 438 additions and 477 deletions

View File

@@ -1,47 +1,35 @@
import { cookies } from "next/headers";
import { redirect } from "next/navigation";
import { cookies } from 'next/headers';
import { redirect } from 'next/navigation';
/**
* Fetch API with Authorization (for server-side usage only).
* @param endpoint - The API endpoint.
* @param options - Fetch options (optional).
* @returns Parsed JSON response.
* Server-side fetch wrapper with auth handling
*/
export async function fetchWithAuthorization<T = unknown>(
export const fetchServer = async <T = unknown>(
endpoint: string,
options: RequestInit = {}
): Promise<T> {
// Access the Authorization cookie securely
const cookieStore = await cookies();
const authToken = cookieStore.get("Authorization")?.value;
): Promise<T> => {
const cookieStore = cookies();
const authToken = await cookieStore.get('Authorization')?.value;
console.log("authToken", authToken);
if (!authToken) redirect('/login');
if (!authToken) {
redirect("/login");
try {
const res = await fetch(`${process.env.NEXT_PUBLIC_API_URL}${endpoint}`, {
...options,
headers: {
'Content-Type': 'application/json',
Authorization: `Bearer ${authToken}`,
...options.headers,
},
cache: 'no-store',
});
if (res.status === 401) redirect('/login');
if (!res.ok) throw new Error(`Request failed: ${res.statusText}`);
return res.json();
} catch (error) {
console.error(`Server request to ${endpoint} failed:`, error);
throw error;
}
const config: RequestInit = {
...options,
headers: {
"Content-Type": "application/json",
Authorization: `Bearer ${authToken}`,
...(options.headers || {}),
},
cache: "no-store",
};
const res = await fetch(`${process.env.NEXT_PUBLIC_API_URL}${endpoint}`, config);
if (res.status === 401) {
redirect("/login");
}
if (!res.ok) {
throw new Error(`Failed to fetch ${endpoint}: ${res.statusText}`);
}
const data = await res.json() as T;
return data as Promise<T>;
}
};