validation.ts 1.86 KB
import { z, type ZodTypeAny } from 'zod';

/**
 * 请求参数校验失败。
 * 由 `parseJsonBody` / `parseWith` 在 zod `safeParse` 不通过时抛出,
 * 全局路由分发器捕获后映射为 HTTP 400,并在响应体中附带结构化的 `issues`。
 */
export class ValidationError extends Error {
    readonly issues: z.ZodIssue[];
    constructor(issues: z.ZodIssue[]) {
        super('请求参数校验失败');
        this.name = 'ValidationError';
        this.issues = issues;
    }
}

/**
 * 用 zod schema 校验一个「已解析为对象」的 JSON 值。
 * 成功返回解析后(含默认值/转换)的数据;失败抛出 `ValidationError`。
 */
export function parseWith<S extends ZodTypeAny>(json: unknown, schema: S): z.infer<S> {
    const result = schema.safeParse(json);
    if (!result.success) throw new ValidationError(result.error.issues);
    return result.data;
}

/** 把 zod issues 整理成可返回前端的精简结构(path + message)。 */
export function formatIssues(issues: z.ZodIssue[]): { path: string; message: string }[] {
    return issues.map((i) => ({
        path: i.path.join('.') || '(root)',
        message: i.message,
    }));
}

/**
 * 读取请求体字符串并按 zod schema 校验。
 * 复用于所有需要 JSON 入参的路由:解析失败或 schema 不通过都抛 `ValidationError`。
 */
export async function readAndParse<S extends ZodTypeAny>(
    readBody: (req: import('node:http').IncomingMessage) => Promise<string>,
    req: import('node:http').IncomingMessage,
    schema: S,
): Promise<z.infer<S>> {
    const text = await readBody(req);
    let json: unknown;
    try {
        json = text ? JSON.parse(text) : {};
    } catch {
        throw new ValidationError([
            { code: 'custom', path: [], message: 'Invalid JSON body' } as z.ZodIssue,
        ]);
    }
    return parseWith(json, schema);
}