-
Notifications
You must be signed in to change notification settings - Fork 1
/
optional.ts
105 lines (101 loc) · 2.78 KB
/
optional.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
import { makeSchema, narrow, Schema } from "../schema";
import { ValidationIssue, ValidationResult } from "../validation";
export function optional<I, O, M>(
schema: Schema<I, O, M>
): Schema<I | undefined, O | undefined, { required: false } & M> {
return makeSchema(
(v, o) => {
if (v !== undefined) {
return schema.validate(v, o);
}
},
async (v, o) => {
if (v !== undefined) {
return schema.validateAsync(v, o);
}
},
() => ({ ...schema.meta(), required: false }),
(v, o) =>
v === undefined ? (v as undefined) : schema.parse(v, o).parsedValue
);
}
export function nullable<I, O, M>(
schema: Schema<I, O, M>
): Schema<I | null, O | null, M> {
return makeSchema(
(v, o) => {
if (v !== null) {
return schema.validate(v, o);
}
},
async (v, o) => {
if (v !== null) {
return schema.validateAsync(v, o);
}
},
() => ({ ...schema.meta() }),
(v, o) => {
const result = v === null ? undefined : schema.parse(v, o).parsedValue;
// eslint-disable-next-line unicorn/no-null
return result ?? null;
}
);
}
export function nullish<I, O, M>(
schema: Schema<I, O, M>
): Schema<I | undefined | null, O | undefined | null, { required: false } & M> {
return makeSchema(
(v, o) => {
if (v !== undefined && v !== null) {
return schema.validate(v, o);
}
},
async (v, o) => {
if (v !== undefined && v !== null) {
return schema.validateAsync(v, o);
}
},
() => ({ ...schema.meta(), required: false }),
(v, o) =>
v !== undefined && v !== null
? schema.parse(v, o).parsedValue
: (v as undefined | null)
);
}
export function required<I, O, M>(
schema: Schema<I, O, M>,
issue?: string
): Schema<
NonNullable<I>,
NonNullable<O>,
Omit<M, "required"> & { required: true }
> {
type V = ValidationResult<NonNullable<I>>;
return makeSchema(
(v, o) => {
if (v === undefined || v === null) {
return new ValidationIssue("required", issue, v) as V;
}
return schema.validate(v, o);
},
async (v, o) => {
if (v === undefined || v === null) {
return new ValidationIssue("required", issue, v) as V;
}
return schema.validateAsync(v, o);
},
() => ({ ...schema.meta(), required: true }),
(v, o) => schema.parse(v, o).parsedValue as NonNullable<O>
);
}
export function defaultValue<I, O, M>(
schema: Schema<I, O, M>,
value: O
): Schema<I, NonNullable<O>, M> {
return narrow(schema, (v) => (v as NonNullable<O>) ?? value);
}
export function nullToUndefined<I, O, M>(
schema: Schema<I | undefined | null, O | undefined | null, M>
): Schema<I | undefined | null, O | undefined, M> {
return narrow(schema, (v) => v ?? undefined);
}