-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathValidator.ts
162 lines (148 loc) · 4.3 KB
/
Validator.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
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
export type Args = { [_: string]: any };
export interface Validator {
type: string;
extends?: Validator[];
convert?: (value: any) => Promise<any> | any;
check: (value: any) => Promise<Args | undefined> | Args | undefined;
message: (
value: any,
args?: Args,
) => Promise<string | undefined> | string | undefined;
}
export interface ValidationError {
type: string;
param?: string[];
message?: string | null;
args: Args;
}
export type Validatable = Schema | Validator | Validator[];
export const ArraySymbol: unique symbol = Symbol("ArraySymbol");
export type Schema = { [key: string]: Validatable } | {
[ArraySymbol]: Validatable;
};
export async function validate(
value: any,
validators: Validatable,
{ doConversion = false, converted = undefined, doValidation = true }: {
doConversion?: boolean;
converted?: any;
doValidation?: boolean;
} = {},
): Promise<ValidationError[]> {
const options = { doConversion, converted, doValidation };
if (Array.isArray(validators) || instanceofValidator(validators)) {
return validateValue(value, validators, options);
} else {
return validateSchema(value, validators, options);
}
}
export function instanceofValidator(value: any): value is Validator {
return value &&
value.hasOwnProperty("type") && typeof value.type === "string" &&
value.hasOwnProperty("check") && typeof value.check === "function" &&
value.hasOwnProperty("message") && typeof value.message === "function";
}
export async function validateValue(
value: any,
validators: Validator | Validator[],
{ doConversion = false, converted = undefined, doValidation = true }: {
doConversion?: boolean;
converted?: any;
doValidation?: boolean;
} = {},
): Promise<ValidationError[]> {
const options = { doConversion, converted, doValidation };
if (!Array.isArray(validators)) {
validators = [validators];
}
const result: ValidationError[] = [];
for (const validator of validators) {
// 1. convert
if (doConversion && validator.convert) {
value = await validator.convert(value);
}
// 2. extends
if (validator.extends) {
const prerequisites = await validate(value, validator.extends, options);
if (prerequisites.length > 0) {
result.push(...prerequisites);
continue;
}
}
// 3. check
const args = doValidation ? await validator.check(value) : undefined;
// 4. message
if (args !== undefined) {
const message = await validator.message(value, args);
result.push({
type: validator.type,
args,
message,
});
}
}
if (converted) {
converted.output = value;
}
return result;
}
export async function validateSchema(
value: any,
validators: Schema,
{ doConversion = false, converted = undefined, doValidation = true }: {
doConversion?: boolean;
converted?: any;
doValidation?: boolean;
} = {},
): Promise<ValidationError[]> {
const conv: any = {};
const options = { doConversion, converted: conv, doValidation };
// Validate array
if (validators.hasOwnProperty(ArraySymbol)) {
const v = validators as { [ArraySymbol]: Validatable };
if (Array.isArray(value)) {
if (converted) {
converted.output = [];
}
const arr: ValidationError[][] = [];
for (const val of value) {
const errors = await validate(val, v[ArraySymbol], options);
arr.push(errors);
if (converted) {
converted.output.push(conv.output);
}
}
const errors = arr.flatMap((val, idx) =>
(val ?? []).map((error) => ({
...error,
param: [`[${idx}]`, ...(error.param || [])],
}))
);
return errors;
} else {
return [{
type: "array",
param: ["[]"],
message: "Array expected!",
args: {},
}];
}
}
// Validate object
const v = validators as { [key: string]: Validatable };
const valErrors: ValidationError[] = [];
if (converted) {
converted.output = {};
}
for (const prop in validators) {
if (!validators.hasOwnProperty(prop)) {
continue;
}
const errors = await validate(value && value[prop], v[prop], options);
valErrors.push(...(errors ?? []));
if (converted) {
converted.output[prop] = conv.output;
}
}
return valErrors;
}