@4players/odin
Version:
A cross-platform SDK enabling developers to integrate real-time VoIP chat technology into their projects
72 lines (71 loc) • 2.48 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.validate = exports.create = void 0;
function create(schema) {
return schema;
}
exports.create = create;
function validate(value, root, schema) {
innerCheck(value, schema, [root]);
}
exports.validate = validate;
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}`);
}
}