This commit is contained in:
g
2025-02-07 04:43:47 +00:00
parent d3e19c7e09
commit 6c4f3f0866
94 changed files with 11777 additions and 0 deletions

47
lib/server-utils.ts Normal file
View File

@@ -0,0 +1,47 @@
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.
*/
export async function fetchWithAuthorization<T = unknown>(
endpoint: string,
options: RequestInit = {}
): Promise<T> {
// Access the Authorization cookie securely
const cookieStore = await cookies();
const authToken = cookieStore.get("Authorization")?.value;
console.log("authToken", authToken);
if (!authToken) {
redirect("/login");
}
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>;
}