Spaces:
Sleeping
Sleeping
Download packages/web/src/apiClient.ts from WorstCardGame/worst-card-game: direct link, hf CLI and curl.
- Browser
- Download file 1.22 kB
-
https://huggingface.co/spaces/WorstCardGame/worst-card-game/resolve/main/packages/web/src/apiClient.ts
- Command line
-
hf download hf://spaces/WorstCardGame/worst-card-game/packages/web/src/apiClient.ts
-
curl -L -o apiClient.ts https://huggingface.co/spaces/WorstCardGame/worst-card-game/resolve/main/packages/web/src/apiClient.ts
1.22 kB
| /** | |
| * 全站 API 請求收斂點。 | |
| * | |
| * - **Activity 模式**:iframe 跨站 cookie 不可靠,改用 Bearer token 認身分。登入握手拿到自家 session token | |
| * 後呼叫 `setBearerToken()`,之後每個 `/api` 請求自動帶 `Authorization: Bearer <token>`。 | |
| * - **網頁模式**:token 為 null,`apiFetch` 行為等同直接 `fetch`(同源 session cookie 由瀏覽器自動帶)。 | |
| * | |
| * 整個 api.ts 都走 `apiFetch`,所以「身分憑證怎麼帶」只在這一個收斂點決定,加新模式不必散改各處。 | |
| */ | |
| let bearer: string | null = null; | |
| /** 設定/清除 Activity 的 session bearer token(登入握手成功後呼叫;登出傳 null)。 */ | |
| export function setBearerToken(token: string | null): void { | |
| bearer = token; | |
| } | |
| export function getBearerToken(): string | null { | |
| return bearer; | |
| } | |
| /** fetch 包一層:有 bearer 就加 Authorization 標頭,否則原樣(走同源 cookie)。 */ | |
| export function apiFetch(input: string, init: RequestInit = {}): Promise<Response> { | |
| if (!bearer) return fetch(input, init); | |
| const headers = new Headers(init.headers); | |
| headers.set("Authorization", `Bearer ${bearer}`); | |
| return fetch(input, { ...init, headers }); | |
| } | |