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) {
|
2020-02-09 06:03:29 +01:00
|
|
|
if (typeof val !== "string") {
|
2020-07-15 01:29:15 +02:00
|
|
|
return var_name + " is not a string";
|
2018-05-22 21:50:24 +02:00
|
|
|
}
|
|
|
|
};
|
|
|
|
|
|
|
|
exports.check_record = function (var_name, val, fields) {
|
2020-02-09 06:03:18 +01:00
|
|
|
if (typeof val !== "object") {
|
2020-07-15 01:29:15 +02:00
|
|
|
return var_name + " is not a record";
|
2018-05-22 21:50:24 +02:00
|
|
|
}
|
|
|
|
|
2020-02-08 01:38:48 +01:00
|
|
|
const field_results = Object.entries(fields).map(([field_name, f]) => {
|
2018-05-22 21:50:24 +02:00
|
|
|
if (val[field_name] === undefined) {
|
2020-07-15 01:29:15 +02:00
|
|
|
return field_name + " is missing";
|
2018-05-22 21:50:24 +02:00
|
|
|
}
|
|
|
|
return f(field_name, val[field_name]);
|
|
|
|
});
|
|
|
|
|
2020-07-15 01:29:15 +02:00
|
|
|
const msg = field_results.filter(Boolean).sort().join(", ");
|
2018-05-22 21:50:24 +02:00
|
|
|
|
|
|
|
if (msg) {
|
2020-07-15 01:29:15 +02:00
|
|
|
return "in " + var_name + " " + msg;
|
2018-05-22 21:50:24 +02:00
|
|
|
}
|
|
|
|
};
|
|
|
|
|
|
|
|
exports.check_array = function (var_name, val, checker) {
|
2020-02-08 06:27:03 +01:00
|
|
|
if (!Array.isArray(val)) {
|
2020-07-15 01:29:15 +02:00
|
|
|
return var_name + " is not an array";
|
2018-05-22 21:50:24 +02:00
|
|
|
}
|
|
|
|
|
2020-02-08 05:29:01 +01:00
|
|
|
for (const item of val) {
|
2020-07-15 01:29:15 +02:00
|
|
|
const msg = checker("item", item);
|
2018-05-22 21:50:24 +02:00
|
|
|
|
2020-02-08 05:29:01 +01:00
|
|
|
if (msg) {
|
2020-07-15 01:29:15 +02:00
|
|
|
return "in " + var_name + " we found an item where " + msg;
|
2018-05-22 21:50:24 +02:00
|
|
|
}
|
|
|
|
}
|
|
|
|
};
|
|
|
|
|
2019-10-25 09:45:13 +02:00
|
|
|
window.schema = exports;
|