"use server"; import { redirect } from "next/navigation"; import { Block, PageMeta, PageStatus, PageType } from "./types"; import { archivePage, createPage, deletePage, updatePage } from "./repository"; import { revalidatePath } from "next/cache"; import { deleteNavLinkByPageId } from "../navlinks/repository"; import { validatePage } from "./validation"; import { requireAdmin } from "../user/require"; import { runAction } from "../run-action"; import type { ActionResult } from "../action-result"; import { uploadImage, removeImage, getImageUrl } from "../image"; import { getBlocksByPageId } from "./repository"; export async function savePageAction(params: { id: string | null, slug: string, title: string, type: PageType, status: PageStatus, blocks: Block[], meta?: PageMeta }): Promise { return runAction(async () => { await requireAdmin(); const parsed = validatePage(params); if (!parsed.success) { throw new Error(parsed.errors.join("; ")); } if (params.id) { await updatePage(params.id, params.title, params.type, params.status, params.blocks, params.meta); revalidatePath(`/${params.type.toLowerCase()}/${params.slug}`); revalidatePath(`/${params.type.toLowerCase()}`); } else { const page = await createPage(params.slug, params.title, params.type, params.status, params.blocks, params.meta); revalidatePath(`/${params.type.toLowerCase()}`); redirect(`/${params.type.toLowerCase()}/${page.slug}`); } }); } export async function archivePageAction(id: string, slug: string, type: PageType): Promise { return runAction(async () => { await requireAdmin(); await archivePage(id); await deleteNavLinkByPageId(id); revalidatePath(`/${type.toLowerCase()}/${slug}`); revalidatePath(`/${type.toLowerCase()}`); }); } export async function deletePageAction(id: string, type: PageType): Promise { return runAction(async () => { await requireAdmin(); const blocks = await getBlocksByPageId(id); const imageKeys = blocks .filter((b) => b.type === "IMAGE") .map((b) => (b.content as { type: "IMAGE"; url: string }).url) .filter(Boolean); if (imageKeys.length) { await Promise.allSettled(imageKeys.map(removeImage)); } await deletePage(id); revalidatePath(`/${type.toLowerCase()}`); }); } export async function uploadPageImage(file: File): Promise { await requireAdmin(); return uploadImage(file, "pages/images", { maxHeight: 800 }); } export async function removePageImages(keys: string[]): Promise { await requireAdmin(); await Promise.allSettled(keys.map(removeImage)); } export async function getImagePreviewUrl(key: string): Promise { return getImageUrl(key); }