Spaces:
Sleeping
Sleeping
Download frontend/src/lib/api.ts from Ethscriptions/cut: direct link, hf CLI and curl.
- Browser
- Download file 1.52 kB
-
https://huggingface.co/spaces/Ethscriptions/cut/resolve/main/frontend/src/lib/api.ts
- Command line
-
hf download hf://spaces/Ethscriptions/cut/frontend/src/lib/api.ts
-
curl -L -o api.ts https://huggingface.co/spaces/Ethscriptions/cut/resolve/main/frontend/src/lib/api.ts
1.52 kB
| export function api(path: string) { | |
| return `${import.meta.env.BASE_URL}api/${path.replace(/^\/+/, '')}` | |
| } | |
| const KEY_STORE = 'cut-admin-key' | |
| export function getAdminKey() { | |
| try { | |
| return localStorage.getItem(KEY_STORE) || '' | |
| } catch { | |
| return '' | |
| } | |
| } | |
| export function setAdminKey(key: string) { | |
| try { | |
| if (key) localStorage.setItem(KEY_STORE, key) | |
| else localStorage.removeItem(KEY_STORE) | |
| } catch { | |
| /* private mode */ | |
| } | |
| } | |
| export class ApiError extends Error { | |
| status: number | |
| needsKey: boolean | |
| constructor(message: string, status: number, needsKey = false) { | |
| super(message) | |
| this.status = status | |
| this.needsKey = needsKey | |
| } | |
| } | |
| /** JSON request helper; sends the saved admin key and turns error bodies into ApiError. */ | |
| export async function request<T = unknown>(path: string, init: { method?: string; body?: unknown } = {}): Promise<T> { | |
| const headers: Record<string, string> = {} | |
| const key = getAdminKey() | |
| if (key) headers['x-admin-key'] = key | |
| if (init.body !== undefined) headers['content-type'] = 'application/json' | |
| const res = await fetch(api(path), { | |
| method: init.method || (init.body !== undefined ? 'POST' : 'GET'), | |
| headers, | |
| body: init.body !== undefined ? JSON.stringify(init.body) : undefined, | |
| }) | |
| let body: any = null | |
| try { | |
| body = await res.json() | |
| } catch { | |
| /* empty body */ | |
| } | |
| if (!res.ok) throw new ApiError(body?.error || `请求失败(${res.status})`, res.status, Boolean(body?.needsKey)) | |
| return body as T | |
| } | |