-
Notifications
You must be signed in to change notification settings - Fork 16
Expand file tree
/
Copy pathvalidate.ts
More file actions
62 lines (57 loc) · 1.66 KB
/
Copy pathvalidate.ts
File metadata and controls
62 lines (57 loc) · 1.66 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
55
56
57
58
59
60
61
62
import ansis from 'ansis';
import path from 'node:path';
import { ZodError, type ZodType, z } from 'zod';
type SchemaValidationContext = {
filePath?: string;
};
/**
* Autocompletes valid Zod Schema input for convience, but will accept any other data as well
*/
type ZodInputLooseAutocomplete<T extends ZodType> =
| z.input<T>
// eslint-disable-next-line @typescript-eslint/no-empty-object-type
| {}
| null
| undefined;
export class SchemaValidationError extends Error {
constructor(
error: ZodError,
schema: ZodType,
{ filePath }: SchemaValidationContext,
) {
const formattedError = z.prettifyError(error);
const schemaTitle = z.globalRegistry.get(schema)?.title;
const summary = [
'Invalid',
schemaTitle ? ansis.bold(schemaTitle) : 'data',
filePath &&
`in ${ansis.bold(path.relative(process.cwd(), filePath))} file`,
]
.filter(Boolean)
.join(' ');
super(`${summary}\n${formattedError}\n`);
this.name = SchemaValidationError.name;
}
}
export function validate<T extends ZodType>(
schema: T,
data: ZodInputLooseAutocomplete<T>,
context: SchemaValidationContext = {},
): z.output<T> {
const result = schema.safeParse(data);
if (result.success) {
return result.data;
}
throw new SchemaValidationError(result.error, schema, context);
}
export async function validateAsync<T extends ZodType>(
schema: T,
data: ZodInputLooseAutocomplete<T>,
context: SchemaValidationContext = {},
): Promise<z.output<T>> {
const result = await schema.safeParseAsync(data);
if (result.success) {
return result.data;
}
throw new SchemaValidationError(result.error, schema, context);
}