Files
eu/lib/pages/validation.ts
T

46 lines
2.0 KiB
TypeScript

import { z } from "zod";
const blockContentSchema = z.discriminatedUnion("type", [
z.object({ type: z.literal("PARAGRAPH"), text: z.string() }),
z.object({ type: z.literal("HEADING"), text: z.string(), level: z.union([z.literal(1), z.literal(2), z.literal(3)]) }),
z.object({ type: z.literal("QUOTE"), text: z.string(), author: z.string().optional() }),
z.object({ type: z.literal("DIVIDER") }),
z.object({ type: z.literal("CALLOUT"), title: z.string(), text: z.string() }),
z.object({ type: z.literal("IMAGE"), url: z.string(), caption: z.string().optional() }),
z.object({ type: z.literal("LIST"), style: z.enum(["BULLET", "ORDERED"]), items: z.array(z.string()) }),
z.object({ type: z.literal("TABLE"), headers: z.array(z.string()), rows: z.array(z.array(z.string())) }),
z.object({ type: z.literal("LINK"), label: z.string(), href: z.string() }),
]);
export const pageSchema = z.object({
id: z.string().nullable(),
title: z.string().min(1, "Title is required"),
slug: z.string().min(1, "Slug is required"),
type: z.enum(["NEWS", "PAGE"]),
status: z.enum(["DRAFT", "PUBLISHED", "ARCHIVED"]),
blocks: z.array(z.object({
id: z.string(),
pageId: z.string(),
parentId: z.string().nullable(),
type: z.enum(["PARAGRAPH", "HEADING", "QUOTE", "DIVIDER", "CALLOUT", "IMAGE", "LIST", "TABLE", "LINK"]),
position: z.number(),
content: blockContentSchema,
})),
meta: z.object({
location: z.string().optional(),
tags: z.array(z.string()).optional(),
}).optional(),
});
export type PageFormData = z.infer<typeof pageSchema>;
export function validatePage(data: unknown): { success: true; data: PageFormData } | { success: false; errors: string[] } {
const result = pageSchema.safeParse(data);
if (!result.success) {
const fieldErrors = result.error.flatten().fieldErrors ?? {};
const messages = Object.values(fieldErrors).flat().filter(Boolean);
return { success: false, errors: messages };
}
return { success: true, data: result.data };
}