Spaces:
Sleeping
Sleeping
Download src/lib/client/api.ts from shahzaib24681012/teamsync: direct link, hf CLI and curl.
- Browser
- Download file 1.64 kB
-
https://huggingface.co/spaces/shahzaib24681012/teamsync/resolve/main/src/lib/client/api.ts
- Command line
-
hf download hf://spaces/shahzaib24681012/teamsync/src/lib/client/api.ts
-
curl -L -o api.ts https://huggingface.co/spaces/shahzaib24681012/teamsync/resolve/main/src/lib/client/api.ts
1.64 kB
| 'use client'; | |
| /** Fetch wrapper with automatic access-token refresh on 401. */ | |
| let refreshing: Promise<boolean> | null = null; | |
| async function tryRefresh(): Promise<boolean> { | |
| if (!refreshing) { | |
| refreshing = fetch('/api/auth/refresh', { method: 'POST' }) | |
| .then((r) => r.ok) | |
| .catch(() => false) | |
| .finally(() => setTimeout(() => (refreshing = null), 100)); | |
| } | |
| return refreshing; | |
| } | |
| export class ApiClientError extends Error { | |
| status: number; | |
| constructor(status: number, message: string) { | |
| super(message); | |
| this.status = status; | |
| } | |
| } | |
| export async function api<T = unknown>(path: string, init?: RequestInit & { json?: unknown }): Promise<T> { | |
| const opts: RequestInit = { ...init }; | |
| if (init?.json !== undefined) { | |
| opts.body = JSON.stringify(init.json); | |
| opts.headers = { 'Content-Type': 'application/json', ...(init.headers ?? {}) }; | |
| } | |
| let res = await fetch(path, opts); | |
| if (res.status === 401 && !path.startsWith('/api/auth/')) { | |
| const ok = await tryRefresh(); | |
| if (ok) res = await fetch(path, opts); | |
| else if (typeof window !== 'undefined') { | |
| window.location.href = '/login'; | |
| throw new ApiClientError(401, 'Session expired'); | |
| } | |
| } | |
| if (!res.ok) { | |
| let message = `Request failed (${res.status})`; | |
| try { | |
| const data = await res.json(); | |
| if (data?.error) message = data.error; | |
| else if (data?.message) message = data.message; | |
| } catch { /* not json */ } | |
| throw new ApiClientError(res.status, message); | |
| } | |
| const ct = res.headers.get('content-type') ?? ''; | |
| return (ct.includes('json') ? res.json() : res.text()) as Promise<T>; | |
| } | |