This commit is contained in:
+17
-23
@@ -1,63 +1,57 @@
|
||||
"use client";
|
||||
|
||||
import { useMemo } from "react";
|
||||
import { useAuth } from "@/context/AuthContext";
|
||||
|
||||
const API_BASE_URL =
|
||||
process.env.NEXT_PUBLIC_API_BASE_URL ?? "";
|
||||
// API routes now handled by Next.js /api routes (server-side)
|
||||
// Authentication happens via HTTP-only cookies automatically
|
||||
|
||||
type JsonValue = any;
|
||||
|
||||
export function useApi() {
|
||||
const { token } = useAuth();
|
||||
|
||||
return useMemo(() => {
|
||||
function authHeaders(extra?: HeadersInit): HeadersInit {
|
||||
const base: Record<string, string> = {};
|
||||
if (token) base.Authorization = `Bearer ${token}`;
|
||||
return { ...base, ...(extra as any) };
|
||||
}
|
||||
|
||||
async function get(path: string, init?: RequestInit) {
|
||||
return fetch(`${API_BASE_URL}${path}`, {
|
||||
// Path should now point to Next.js API routes (e.g., /api/builds)
|
||||
return fetch(path, {
|
||||
...init,
|
||||
headers: authHeaders(init?.headers),
|
||||
credentials: 'include', // Include cookies in requests
|
||||
});
|
||||
}
|
||||
|
||||
async function post(path: string, body: JsonValue, init?: RequestInit) {
|
||||
return fetch(`${API_BASE_URL}${path}`, {
|
||||
return fetch(path, {
|
||||
method: "POST",
|
||||
...init,
|
||||
headers: authHeaders({
|
||||
credentials: 'include',
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
...(init?.headers as any),
|
||||
}),
|
||||
},
|
||||
body: JSON.stringify(body),
|
||||
});
|
||||
}
|
||||
|
||||
async function put(path: string, body: JsonValue, init?: RequestInit) {
|
||||
return fetch(`${API_BASE_URL}${path}`, {
|
||||
return fetch(path, {
|
||||
method: "PUT",
|
||||
...init,
|
||||
headers: authHeaders({
|
||||
credentials: 'include',
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
...(init?.headers as any),
|
||||
}),
|
||||
},
|
||||
body: JSON.stringify(body),
|
||||
});
|
||||
}
|
||||
|
||||
async function del(path: string, init?: RequestInit) {
|
||||
return fetch(`${API_BASE_URL}${path}`, {
|
||||
return fetch(path, {
|
||||
method: "DELETE",
|
||||
...init,
|
||||
headers: authHeaders(init?.headers),
|
||||
credentials: 'include',
|
||||
headers: init?.headers,
|
||||
});
|
||||
}
|
||||
|
||||
// ✅ stable reference unless token changes
|
||||
return { get, post, put, del };
|
||||
}, [token]);
|
||||
}, []);
|
||||
}
|
||||
Reference in New Issue
Block a user