validation.ts
1.86 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
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);
}