forked from Lilly-Protocol/lily-sdk
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathresponse-validator.ts
More file actions
33 lines (29 loc) · 1.08 KB
/
Copy pathresponse-validator.ts
File metadata and controls
33 lines (29 loc) · 1.08 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
export interface ValidationRule {
field: string;
type: 'string' | 'number' | 'boolean' | 'object' | 'array';
required?: boolean;
validate?: (value: unknown) => boolean;
}
export class ResponseValidator {
constructor(private rules: Record<string, ValidationRule[]>) {}
validate(endpoint: string, data: unknown): { valid: boolean; errors: string[] } {
const rules = this.rules[endpoint];
if (!rules) return { valid: true, errors: [] };
const errors: string[] = [];
const obj = (data || {}) as Record<string, unknown>;
for (const rule of rules) {
const value = obj[rule.field];
if (value === undefined || value === null) {
if (rule.required) errors.push(`Missing required field: ${rule.field}`);
continue;
}
if (typeof value !== rule.type) {
errors.push(`Field ${rule.field} expected ${rule.type}, got ${typeof value}`);
}
if (rule.validate && !rule.validate(value)) {
errors.push(`Field ${rule.field} failed custom validation`);
}
}
return { valid: errors.length === 0, errors };
}
}