init project

This commit is contained in:
root
2026-04-23 00:21:02 -04:00
parent 23826c5528
commit 9191fd32f0
64 changed files with 10229 additions and 0 deletions
+52
View File
@@ -0,0 +1,52 @@
import { apiUrl } from '../lib/apiOrigin'
const TOKEN_KEY = 'alrahma_api_token'
export function getStoredToken(): string | null {
return localStorage.getItem(TOKEN_KEY)
}
export function setStoredToken(token: string | null): void {
if (token) localStorage.setItem(TOKEN_KEY, token)
else localStorage.removeItem(TOKEN_KEY)
}
export class ApiHttpError extends Error {
readonly status: number
readonly body: unknown
constructor(message: string, status: number, body: unknown) {
super(message)
this.name = 'ApiHttpError'
this.status = status
this.body = body
}
}
export async function apiFetch<T>(
path: string,
init: RequestInit = {},
opts: { attachAuth?: boolean } = {},
): Promise<T> {
const attachAuth = opts.attachAuth !== false
const headers = new Headers(init.headers)
if (!headers.has('Accept')) headers.set('Accept', 'application/json')
const token = getStoredToken()
if (attachAuth && token && !headers.has('Authorization')) {
headers.set('Authorization', `Bearer ${token}`)
}
const res = await fetch(apiUrl(path), { ...init, headers })
const body: unknown = await res.json().catch(() => null)
if (!res.ok) {
const msg =
typeof body === 'object' && body !== null && 'message' in body
? String((body as { message?: unknown }).message ?? '')
: ''
throw new ApiHttpError(msg || `HTTP ${res.status}`, res.status, body)
}
return body as T
}