add first files
This commit is contained in:
@@ -0,0 +1,80 @@
|
||||
const API_BASE = process.env.NEXT_PUBLIC_API_URL ?? 'http://localhost:4000/api/v1'
|
||||
|
||||
async function getClerkToken(): Promise<string | null> {
|
||||
try {
|
||||
// In Next.js App Router, the Clerk session token is available via the Clerk SDK
|
||||
// For client-side calls, we read it from a cookie set by @clerk/nextjs
|
||||
if (typeof window !== 'undefined') {
|
||||
// Client-side: use window.__clerk if available
|
||||
const clerk = (window as any).__clerk
|
||||
if (clerk?.session) {
|
||||
return await clerk.session.getToken()
|
||||
}
|
||||
}
|
||||
return null
|
||||
} catch {
|
||||
return null
|
||||
}
|
||||
}
|
||||
|
||||
export async function apiFetch<T>(path: string, options?: RequestInit): Promise<T> {
|
||||
const token = await getClerkToken()
|
||||
|
||||
const headers: Record<string, string> = {
|
||||
'Content-Type': 'application/json',
|
||||
...(options?.headers as Record<string, string> ?? {}),
|
||||
}
|
||||
|
||||
if (token) {
|
||||
headers['Authorization'] = `Bearer ${token}`
|
||||
}
|
||||
|
||||
const res = await fetch(`${API_BASE}${path}`, {
|
||||
...options,
|
||||
headers,
|
||||
credentials: 'include',
|
||||
})
|
||||
|
||||
let json: any
|
||||
try {
|
||||
json = await res.json()
|
||||
} catch {
|
||||
throw new Error(`HTTP ${res.status}: ${res.statusText}`)
|
||||
}
|
||||
|
||||
if (!res.ok) {
|
||||
const err = new Error(json?.message ?? json?.error ?? `Request failed with status ${res.status}`) as any
|
||||
err.code = json?.error
|
||||
err.statusCode = res.status
|
||||
throw err
|
||||
}
|
||||
|
||||
return (json?.data ?? json) as T
|
||||
}
|
||||
|
||||
export async function apiFetchServer<T>(path: string, token: string, options?: RequestInit): Promise<T> {
|
||||
const res = await fetch(`${API_BASE}${path}`, {
|
||||
...options,
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
'Authorization': `Bearer ${token}`,
|
||||
...(options?.headers as Record<string, string> ?? {}),
|
||||
},
|
||||
cache: 'no-store',
|
||||
})
|
||||
|
||||
let json: any
|
||||
try {
|
||||
json = await res.json()
|
||||
} catch {
|
||||
throw new Error(`HTTP ${res.status}: ${res.statusText}`)
|
||||
}
|
||||
|
||||
if (!res.ok) {
|
||||
const err = new Error(json?.message ?? `Request failed with status ${res.status}`) as any
|
||||
err.statusCode = res.status
|
||||
throw err
|
||||
}
|
||||
|
||||
return (json?.data ?? json) as T
|
||||
}
|
||||
Reference in New Issue
Block a user