blob: bbf7d4d148edfdba721a44af89044d23641341ea (
plain)
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
|
/**
* Simple utility to validate objects against JSON Schemas
* In a real implementation, you would use a library like Ajv
*/
export class SchemaValidator {
/**
* Validates data against a JSON schema
* @param schema JSON Schema to validate against
* @param data Data to validate
* @returns True if valid, false otherwise
*/
static validate(schema: Record<string, unknown>, data: unknown): boolean {
// This is a simplified implementation
// In a real application, you would use a library like Ajv for proper validation
// Check for required fields
if (schema.required && Array.isArray(schema.required)) {
const required = schema.required as string[];
const dataObj = data as Record<string, unknown>;
for (const field of required) {
if (dataObj[field] === undefined) {
console.error(`Missing required field: ${field}`);
return false;
}
}
}
// Check property types if properties are defined
if (schema.properties && typeof schema.properties === 'object') {
const properties = schema.properties as Record<string, { type?: string }>;
const dataObj = data as Record<string, unknown>;
for (const [key, prop] of Object.entries(properties)) {
if (dataObj[key] !== undefined && prop.type) {
const expectedType = prop.type;
const actualType = Array.isArray(dataObj[key]) ? 'array' : typeof dataObj[key];
if (expectedType !== actualType) {
console.error(`Type mismatch for property "${key}": expected ${expectedType}, got ${actualType}`);
return false;
}
}
}
}
return true;
}
}
|