Files
crosscode-platform/apps/accounts/frontend/src/lib/api.ts
T
joshuaandClaude Opus 5.5 f202a5a88e Accounts 1.0.0 frontend and @crosscode/ui
Sign-in steps (password, sign-up, email code, two-step sign-in and its
setup with recovery codes, privacy notice, news question), forgot and
reset password, the account page, admin (people, deletions, church
profile, linked products, settings, notice, licence, audit) and setup.
Strict CSP with a nonce per page; church colours from the profile.
@crosscode/ui gets its first components (shell, card, fields, buttons).
Plan: roles stay in each product (asked 2026-11-18).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-18 13:42:45 +02:00

27 lines
1.4 KiB
TypeScript

/**
* Calls to the backend from the browser (same address, under /api). Errors come back as
* { error: { code, message, fields? } }; `call` returns them instead of throwing.
*/
export type ApiError = { code: string; message: string; fields?: Record<string, string> };
export type ApiResult<T> = { ok: true; status: number; data: T } | { ok: false; status: number; error: ApiError };
export async function call<T = Record<string, unknown>>(method: "GET" | "POST" | "PUT" | "DELETE", path: string, body?: unknown): Promise<ApiResult<T>> {
let res: Response;
try {
res = await fetch(`/api/v2${path}`, {
method,
credentials: "same-origin",
headers: body !== undefined ? { "Content-Type": "application/json" } : undefined,
body: body !== undefined ? JSON.stringify(body) : undefined,
});
} catch {
return { ok: false, status: 0, error: { code: "OFFLINE", message: "We couldn't reach the server. Check your connection and try again." } };
}
const json = (await res.json().catch(() => ({}))) as { error?: ApiError };
if (!res.ok) return { ok: false, status: res.status, error: json.error ?? { code: "ERROR", message: "Something went wrong. Please try again." } };
return { ok: true, status: res.status, data: json as T };
}
/** Where to sign in to Accounts' own pages, coming back to `returnTo`. */
export const selfSignIn = (returnTo: string, extra = "") => `/api/self/signin?returnTo=${encodeURIComponent(returnTo)}${extra}`;