-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmakeZodErrorMap.ts
More file actions
104 lines (91 loc) · 2.4 KB
/
Copy pathmakeZodErrorMap.ts
File metadata and controls
104 lines (91 loc) · 2.4 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
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
import { FormatDateOptions, IntlShape } from '@formatjs/intl'
import { z } from 'zod'
import { errorMessages } from './errorMessages'
// Docs https://zod.dev/ERROR_HANDLING?id=error-map-priority
export function makeZodErrorMap<T>(
issue: z.ZodIssueOptionalMessage,
intl: IntlShape<T>
) {
const descriptorItem = getDescriptorItem<T>(issue, intl)
return descriptorItem.key in errorMessages
? {
message: intl.formatMessage(
errorMessages[descriptorItem.key as keyof typeof errorMessages],
descriptorItem.values
),
}
: { message: intl.formatMessage(errorMessages['default']) }
}
export function getDescriptorItem<T>(
issue: z.ZodIssueOptionalMessage,
intl: IntlShape<T>
): {
key: string
values?: Record<string, string | number>
} {
if (issue.code === z.ZodIssueCode.invalid_string) {
return {
key: `string.invalid.${issue.validation}`,
}
}
if (issue.code === z.ZodIssueCode.not_multiple_of) {
return {
key: `number.${issue.code}`,
}
}
if (issue.code === z.ZodIssueCode.invalid_date) {
return { key: `date.${issue.code}` }
}
if (
issue.code === z.ZodIssueCode.too_small &&
issue.type === 'string' &&
issue.minimum === 1
) {
return { key: 'string.required' }
}
if (
issue.code === z.ZodIssueCode.too_small ||
issue.code === z.ZodIssueCode.too_big
) {
let value =
issue.code === z.ZodIssueCode.too_small
? issue.minimum
: issue.code === z.ZodIssueCode.too_big
? issue.maximum
: '-'
if (issue.type === 'date') {
const date = new Date(value)
if (isNaN(date.getTime())) {
value = '-'
} else {
const dateOptions: FormatDateOptions = {
day: '2-digit',
month: '2-digit',
year: 'numeric',
}
const timeOptions: FormatDateOptions | null =
date.getHours() === 0 && date.getMinutes() === 0
? null
: {
hour: '2-digit',
minute: '2-digit',
}
value = intl.formatDate(value, {
...dateOptions,
...timeOptions,
})
}
}
return {
key: issue.exact
? `${issue.type}.exact`
: `${issue.type}.${issue.code}.${
issue.inclusive ? 'inclusive' : 'exclusive'
}`,
values: {
value,
},
}
}
return { key: 'default' }
}