f330efb1ad
Build & Deploy / Build & Push Docker Image (push) Successful in 3m1s
Test / Type Check (all packages) (push) Successful in 55s
Build & Deploy / Deploy to VPS (push) Successful in 5s
Test / API Unit Tests (push) Successful in 47s
Test / Homepage Unit Tests (push) Successful in 42s
Test / Carplace Unit Tests (push) Successful in 42s
Test / Admin Unit Tests (push) Successful in 40s
Test / Dashboard Unit Tests (push) Successful in 41s
Test / API Integration Tests (push) Successful in 1m0s
80 lines
2.2 KiB
TypeScript
80 lines
2.2 KiB
TypeScript
export function normalizeApiBase(value: string): string {
|
|
const base = value.replace(/\/+$/, '')
|
|
if (/\/api$/.test(base)) return `${base}/v1`
|
|
return /\/api\/v1$/.test(base) ? base : `${base}/api/v1`
|
|
}
|
|
|
|
export function resolveApiBase(): string {
|
|
const value = typeof window === 'undefined'
|
|
? (process.env.API_INTERNAL_URL || 'http://localhost:4000/api/v1')
|
|
: (process.env.NEXT_PUBLIC_API_URL || '/dashboard/api/v1')
|
|
|
|
return normalizeApiBase(value)
|
|
}
|
|
|
|
export const API_BASE = resolveApiBase()
|
|
|
|
export const EMPLOYEE_PROFILE_KEY = 'employee_profile'
|
|
|
|
export async function apiFetch<T>(path: string, options?: RequestInit): Promise<T> {
|
|
const isFormData = typeof FormData !== 'undefined' && options?.body instanceof FormData
|
|
|
|
const headers: Record<string, string> = {
|
|
...(options?.headers as Record<string, string> ?? {}),
|
|
}
|
|
|
|
if (!isFormData) {
|
|
headers['Content-Type'] = 'application/json'
|
|
}
|
|
|
|
const res = await fetch(`${resolveApiBase()}${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 isFormData = typeof FormData !== 'undefined' && options?.body instanceof FormData
|
|
const res = await fetch(`${resolveApiBase()}${path}`, {
|
|
...options,
|
|
headers: {
|
|
...(isFormData ? {} : { '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
|
|
}
|