flowjv
Version:
Flow based approach to JSON validation!
82 lines (81 loc) • 3.29 kB
JavaScript
;
var __assign = (this && this.__assign) || function () {
__assign = Object.assign || function(t) {
for (var s, i = 1, n = arguments.length; i < n; i++) {
s = arguments[i];
for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
t[p] = s[p];
}
return t;
};
return __assign.apply(this, arguments);
};
var __read = (this && this.__read) || function (o, n) {
var m = typeof Symbol === "function" && o[Symbol.iterator];
if (!m) return o;
var i = m.call(o), r, ar = [], e;
try {
while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);
}
catch (error) { e = { error: error }; }
finally {
try {
if (r && !r.done && (m = i["return"])) m.call(i);
}
finally { if (e) throw e.error; }
}
return ar;
};
var __spreadArray = (this && this.__spreadArray) || function (to, from) {
for (var i = 0, il = from.length, j = to.length; i < il; i++, j++)
to[j] = from[i];
return to;
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.validateArrayType = void 0;
var immutable_1 = require("../../../helper/immutable");
var simple_1 = require("../simple");
var object_1 = require("./object");
function validateArrayType(schema, payload, config) {
var _a, _b;
var data = immutable_1.get(payload.data, payload.refPath, []);
var allErrors = [];
var arrErrors = [];
if (schema.isRequired && typeof data === "undefined") {
arrErrors.push((_b = (_a = schema.errMsgs) === null || _a === void 0 ? void 0 : _a.required) !== null && _b !== void 0 ? _b : "Array at " + payload.refPath.join(".") + " is required.");
}
if (typeof data !== "undefined" && !Array.isArray(data)) {
arrErrors.push("Type expected at " + payload.refPath.join(".") + " should of type array.");
}
else if (typeof data !== "undefined") {
var itemSchema = schema.itemSchema;
for (var i = 0; i < data.length; i++) {
var itemKeyPath = __spreadArray(__spreadArray([], __read(payload.refPath)), [i]);
switch (itemSchema.type) {
case "object": {
var errors = object_1.validateObjectType(itemSchema, __assign(__assign({}, payload), { refPath: itemKeyPath }), config).errors;
if (errors.length > 0) {
allErrors.push.apply(allErrors, __spreadArray([], __read(errors)));
}
break;
}
default: {
var errors = simple_1.validateSimpleType(itemSchema, __assign(__assign({}, payload), { refPath: itemKeyPath }), config).errors;
if (errors.length > 0) {
allErrors.push({ key: itemKeyPath, msgs: errors });
}
break;
}
}
}
}
if (arrErrors.length > 0) {
allErrors = __spreadArray([{ key: payload.refPath, msgs: arrErrors }], __read(allErrors));
}
return {
isValid: !(allErrors.length > 0 || arrErrors.length > 0),
errors: allErrors,
payload: payload,
};
}
exports.validateArrayType = validateArrayType;