@edgeguideab/expect
Version:
Check for user input in a consistent way and generate error messages for missings
52 lines (51 loc) • 1.67 kB
JavaScript
;
var index_1 = require("./types/index");
var validation_1 = require("./util/validation");
function expect(schema, input) {
if (!isObject(schema)) {
throw new Error("Invalid validation schema");
}
var parsedValues = Object.create(null);
var errors = Object.create(null);
var valid = true;
Object.keys(schema)
.filter(function (key) { return !(0, validation_1.isUnsafe)(key); })
.filter(function (key) { return schema[key] !== undefined; })
.forEach(function (parameter) {
if (!isObject(input)) {
valid = false;
errors[parameter] = "Invalid input";
return;
}
var options = schema[parameter];
var value = input[parameter];
var validation = (0, index_1.validate)({
input: input,
value: value,
schema: schema,
options: options,
parameter: parameter,
visitedParams: [],
type: typeof options === "string" ? options : options.type,
});
if (!validation.valid) {
valid = false;
if (validation.error)
errors[parameter] = validation.error;
return;
}
if (validation.parsed !== undefined) {
parsedValues[parameter] = validation.parsed;
}
});
return {
isValid: valid,
errors: function () { return errors; },
getParsed: function () { return parsedValues; },
wereMet: function () { return valid; },
};
}
function isObject(val) {
return val !== null && typeof val === "object";
}
module.exports = expect;