@edgeguideab/expect
Version:
Check for user input in a consistent way and generate error messages for missings
67 lines (66 loc) • 2.88 kB
JavaScript
;
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.validateObject = void 0;
var isRecord_1 = __importDefault(require("../util/isRecord"));
var index_1 = require("../util/index");
var validation_1 = require("../util/validation");
function validateObject(_a) {
var parameter = _a.parameter, value = _a.value, options = _a.options, input = _a.input, schema = _a.schema, _b = _a.visitedParams, visitedParams = _b === void 0 ? [] : _b, validate = _a.validate;
if (!(0, isRecord_1.default)(value) || Array.isArray(value))
return { valid: false };
var errorCode = options.errorCode, keys = options.keys, strictKeyCheck = options.strictKeyCheck;
if (Object.keys(value).some(function (key) { return (0, validation_1.isUnsafe)(key); })) {
return {
valid: false,
error: errorCode || "Object contained unsafe prototype keys",
};
}
if (!keys)
return { valid: true };
var validKeys = Object.keys(keys).filter(function (key) { return keys[key] != null; });
var parsed = Object.create(null);
var error = Object.create(null);
if (strictKeyCheck) {
var uncheckedKeys = Object.keys(value).filter(function (key) { return !validKeys.includes(key); });
if (uncheckedKeys.length) {
return {
valid: false,
error: errorCode ||
"Object contained unchecked keys " + JSON.stringify(uncheckedKeys.join(", ")),
};
}
}
var invalidKeys = validKeys.filter(function (key) {
var option = keys[key];
var keyType = typeof option === "object" && option !== null ? option.type : option;
if (!keyType)
return true;
var keyOptions = typeof option === "object" && option !== null
? option
: { type: keyType };
var validation = validate({
type: keyType,
parameter: Array.isArray(parameter)
? parameter.concat(key)
: [parameter, key],
value: value[key],
options: keyOptions,
input: input,
schema: schema,
visitedParams: visitedParams.concat((0, index_1.formatParameter)(parameter)),
});
if (!validation.valid)
error[key] = validation.error;
else {
var parsedValue = "parsed" in validation ? validation.parsed : value[key];
if (parsedValue !== undefined)
parsed[key] = parsedValue;
}
return !validation.valid;
});
return invalidKeys.length ? { valid: false, error: error } : { valid: true, parsed: parsed };
}
exports.validateObject = validateObject;