-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.ts
123 lines (108 loc) · 3.36 KB
/
index.ts
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
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
import { z } from "./deps.ts";
/**
* Parameters for parsing a form.
* @property schema - The Zod schema to validate the form data.
* @property data - The form data to parse.
*/
export type ParseFormParams = {
schema: z.ZodType;
data: Record<string, unknown> | FormData | URLSearchParams;
};
/**
* The result of parsing a form. Either the form data is valid or there are errors.
* @property errors - A key-value dictionary of errors.
* @property zodError - The Zod error object.
* @property validData - The valid form data.
*/
export type ParseFormResult<T extends z.ZodType> = {
errors?: never;
zodError?: never;
validData: z.infer<T>;
} | {
errors: Record<string, string>;
zodError: z.ZodError<unknown>;
validData?: never;
};
/**
* Parse form data using a Zod schema and return a friendly key-value dict of errors
* @param params - The parameters for the form parsing.
* @param options - Additional options for the form parsing.
* @returns The result of the form parsing.
* @example """
* const schema = z.object({
* email: z.string().email(),
* password: z.string().min(8),
* });
* const data = { email: "jason", password: "12345678" };
* const { validData, errors } = parseForm({ schema, data });
* """
*/
export function parseForm(
params: ParseFormParams,
options?: { stripEmptyStrings?: boolean },
): ParseFormResult<typeof params.schema> {
const { schema, data } = params;
let unknownData: Record<string, unknown>;
if (data instanceof FormData || data instanceof URLSearchParams) {
unknownData = extractFormData(data);
} else {
unknownData = data;
}
if (options?.stripEmptyStrings) {
Object.keys(unknownData).forEach((key) => {
if (unknownData[key] === "") unknownData[key] = undefined;
});
}
const parseResults = schema.safeParse(unknownData);
if (parseResults.success) {
return { validData: parseResults.data };
}
const zodError = parseResults.error;
return { errors: flattenErrors(parseResults), zodError };
}
function flattenErrors(result: z.SafeParseError<unknown>) {
return result.error.errors.reduce<Record<string, string>>(
(prev: Record<string, string>, next) => {
const result = { ...prev };
const key = next.path.join(".");
result[key] = next.message;
// we'll cover more cases here as we need them
switch (next.code) {
case "invalid_union":
next.unionErrors.forEach((unionError) => {
unionError.errors.forEach((error) => {
result[error.path.join(".")] = error.message;
});
});
break;
case "invalid_type":
case "invalid_literal":
case "custom":
case "invalid_union_discriminator":
case "invalid_enum_value":
case "unrecognized_keys":
case "invalid_arguments":
case "invalid_return_type":
case "invalid_date":
case "invalid_string":
case "too_small":
case "too_big":
case "invalid_intersection_types":
case "not_multiple_of":
case "not_finite":
default:
break;
}
return result;
},
{},
);
}
function extractFormData(data: FormData | URLSearchParams): Record<string, unknown> {
const result: Record<string, unknown> = {};
for (const [key, value] of data) {
result[key] = value;
}
return result;
}
export default parseForm;