Files
sorsfonalak/services/frontend/src/lib/forumServer.ts
T

45 lines
1.9 KiB
TypeScript
Raw Normal View History

// Forum service calls from server components, with the visitor's session.
// Without FORUM_URL the forum is switched off (no menu item, its pages 404).
import "server-only";
import { cookies } from "next/headers";
import { BackendError, SESSION_COOKIE } from "./server";
export const FORUM_URL = (process.env.FORUM_URL ?? "").replace(/\/$/, "");
export function forumEnabled(): boolean {
return FORUM_URL !== "";
}
/** The answer of a forum GET: the data, or why there is none. */
export type ForumResult<T> = { ok: true; data: T } | { ok: false; status: 401 | 404 };
/** GET from the forum service as the visitor (logged in or not). */
export async function forumGet<T>(path: string): Promise<ForumResult<T>> {
if (!forumEnabled()) return { ok: false, status: 404 };
const token = (await cookies()).get(SESSION_COOKIE)?.value;
const headers: HeadersInit = token ? { authorization: `Bearer ${token}` } : {};
const res = await fetch(`${FORUM_URL}${path}`, { headers, cache: "no-store" });
if (res.status === 401 || res.status === 404) return { ok: false, status: res.status };
// Not allowed (e.g. the moderation log for a member): the page does not exist for them.
if (res.status === 403) return { ok: false, status: 404 };
if (!res.ok) throw new BackendError(res.status, `${path}: HTTP ${res.status}`);
return { ok: true, data: (await res.json()) as T };
}
/** The public forum pages for the sitemap (nothing when the forum is off or does not answer). */
export async function forumSitemap(): Promise<{
topics: { slug: string; updated: string | null }[];
threads: { id: number; slug: string; updated: string }[];
}> {
const empty = { topics: [], threads: [] };
if (!forumEnabled()) return empty;
try {
const res = await fetch(`${FORUM_URL}/v1/forum/sitemap`, { next: { revalidate: 3600 } });
return res.ok ? await res.json() : empty;
} catch {
return empty;
}
}