2018-05-22 21:50:24 +02:00
|
|
|
/*
|
|
|
|
|
|
|
|
These runtime schema validators are defensive and
|
|
|
|
should always succeed, so we don't necessarily want
|
|
|
|
to translate these. These are very similar to server
|
|
|
|
side validators in zerver/lib/validator.py.
|
|
|
|
|
|
|
|
*/
|
|
|
|
|
|
|
|
exports.check_string = function (var_name, val) {
|
|
|
|
if (!_.isString(val)) {
|
|
|
|
return var_name + ' is not a string';
|
|
|
|
}
|
|
|
|
};
|
|
|
|
|
|
|
|
exports.check_record = function (var_name, val, fields) {
|
|
|
|
if (!_.isObject(val)) {
|
|
|
|
return var_name + ' is not a record';
|
|
|
|
}
|
|
|
|
|
2019-11-02 00:06:25 +01:00
|
|
|
const field_results = _.map(fields, function (f, field_name) {
|
2018-05-22 21:50:24 +02:00
|
|
|
if (val[field_name] === undefined) {
|
|
|
|
return field_name + ' is missing';
|
|
|
|
}
|
|
|
|
return f(field_name, val[field_name]);
|
|
|
|
});
|
|
|
|
|
2019-11-02 00:06:25 +01:00
|
|
|
const msg = _.filter(field_results).sort().join(', ');
|
2018-05-22 21:50:24 +02:00
|
|
|
|
|
|
|
if (msg) {
|
|
|
|
return 'in ' + var_name + ' ' + msg;
|
|
|
|
}
|
|
|
|
};
|
|
|
|
|
|
|
|
exports.check_array = function (var_name, val, checker) {
|
|
|
|
if (!_.isArray(val)) {
|
|
|
|
return var_name + ' is not an array';
|
|
|
|
}
|
|
|
|
|
2019-11-02 00:06:25 +01:00
|
|
|
let msg;
|
2018-05-22 21:50:24 +02:00
|
|
|
|
|
|
|
_.find(val, function (item) {
|
2019-11-02 00:06:25 +01:00
|
|
|
const res = checker('item', item);
|
2018-05-22 21:50:24 +02:00
|
|
|
|
|
|
|
if (res) {
|
|
|
|
msg = res;
|
|
|
|
return msg;
|
|
|
|
}
|
|
|
|
});
|
|
|
|
|
|
|
|
if (msg) {
|
|
|
|
return 'in ' + var_name + ' we found an item where ' + msg;
|
|
|
|
}
|
|
|
|
};
|
|
|
|
|
2019-10-25 09:45:13 +02:00
|
|
|
window.schema = exports;
|