Admin API and screens: dashboard and setup checklist, template and style, pages and blocks, ministries, leadership, media library with the storage limit, publish and history. Pending changes with who and when, discard one, one Publish, restore any version (each version keeps the working copy's rows, never sent to visitors). Preview on the site's own addresses with a bar (widths, back, publish); shared preview links for 7 days or until revoked. Roles checked, same-origin changes only. Publish refreshes the public pages at once (WEBSITE_CONTENT_CACHE_SECONDS). E2E on a production build: the admin's flows and axe on every screen. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
30 lines
1.7 KiB
TypeScript
30 lines
1.7 KiB
TypeScript
"use client";
|
|
|
|
/** The admin API from the browser (same origin: the session cookie goes along, and so does Origin). */
|
|
export class AdminError extends Error {
|
|
constructor(message: string, public code: string, public status: number, public fields: Record<string, string> = {}) {
|
|
super(message);
|
|
}
|
|
}
|
|
|
|
export async function api<T = unknown>(path: string, opts: { method?: string; body?: unknown; raw?: Blob } = {}): Promise<T> {
|
|
const res = await fetch(`/api/v1/admin${path}`, {
|
|
method: opts.method ?? (opts.body !== undefined || opts.raw ? "POST" : "GET"),
|
|
headers: opts.raw ? { "Content-Type": "application/octet-stream" } : opts.body !== undefined ? { "Content-Type": "application/json" } : undefined,
|
|
body: opts.raw ?? (opts.body !== undefined ? JSON.stringify(opts.body) : undefined),
|
|
cache: "no-store",
|
|
});
|
|
const data = await res.json().catch(() => null);
|
|
if (!res.ok) {
|
|
const e = (data as { error?: { message?: string; code?: string; fields?: Record<string, string> } } | null)?.error;
|
|
// Signed out: off to sign in (a route on the backend), and back to this page.
|
|
// eslint-disable-next-line @next/next/no-location-assign-relative-destination
|
|
if (res.status === 401) window.location.href = `/api/auth/signin?returnTo=${encodeURIComponent(window.location.pathname)}`;
|
|
throw new AdminError(e?.message ?? `Something went wrong (${res.status}).`, e?.code ?? "ERROR", res.status, e?.fields ?? {});
|
|
}
|
|
return data as T;
|
|
}
|
|
|
|
export const ROLE_NAMES: Record<string, string> = { owner: "Owner", admin: "Admin", editor: "Editor", ministry_leader: "Ministry leader", viewer: "Viewer" };
|
|
export const canEdit = (role: string) => ["owner", "admin", "editor"].includes(role);
|