UNPKG

@4players/odin

Version:

A cross-platform SDK enabling developers to integrate real-time VoIP chat technology into their projects

67 lines (66 loc) 2.32 kB
export function create(schema) { return schema; } export function validate(value, root, schema) { innerCheck(value, schema, [root]); } function innerCheck(value, schema, path) { if (schema.array === true) { assertPath(Array.isArray(value), path, 'is not an array'); for (let i = 0; i < value.length; ++i) { path.push(i); innerCheckValue(value[i], schema, path); path.pop(); } } else { innerCheckValue(value, schema, path); } } function innerCheckValue(value, schema, path) { if (schema.optional && (value === undefined || value === null)) return; if (schema.type === 'Object') { assertPath(typeof value === 'object' && Array.isArray(value) === false, path, 'is not an object'); assertPath(value !== null && value !== undefined, path, 'must not be null'); for (const field of Object.keys(schema.fields)) { const fieldSchema = schema.fields[field]; path.push(field); if (field in value) { const fieldValue = value[field]; innerCheck(fieldValue, fieldSchema, path); } else { assertPath(fieldSchema.optional, path, 'is missing'); } path.pop(); } } else { switch (schema.type) { case 'Number': assertPath(typeof value === 'number', path, 'is not a number'); break; case 'Bigint': assertPath(typeof value === 'bigint', path, 'is not a bigint'); break; case 'String': assertPath(typeof value === 'string', path, 'is not a string'); break; case 'Boolean': assertPath(typeof value === 'boolean', path, 'is not a Bool'); break; case 'U8': assertPath(checkTypedArrayType(value), path, 'is not a Bool'); break; } } } function checkTypedArrayType(someTypedArray) { return (someTypedArray && someTypedArray.constructor && someTypedArray.constructor.name) || null; } function assertPath(expr, path, msg) { if (!expr) { throw new Error(`Field validation failed '${path.join('.')}'; ${msg}`); } }