flowjv
Version:
Flow based approach to JSON validation!
67 lines (66 loc) • 2.68 kB
JavaScript
;
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.validateSimpleType = void 0;
var helper_1 = require("../helper");
var immutable_1 = require("../../../helper/immutable");
function validateSimpleType(schema, payload, config) {
var _a, _b, _c, _d, _e, _f;
var value = immutable_1.get(payload.data, payload.refPath);
var errors = [];
// Required check
var isRequiredError = schema.isRequired
? immutable_1.get(payload.data, payload.refPath) === undefined
: false;
isRequiredError &&
errors.push((_b = (_a = schema.errMsgs) === null || _a === void 0 ? void 0 : _a.required) !== null && _b !== void 0 ? _b : helper_1.ErrorMsgs.required);
// Type check
if (config.typeCheck) {
var typeError = void 0;
switch (schema.type) {
case "string":
case "number":
case "boolean":
var type = typeof value;
typeError =
value !== undefined &&
config.typeCheck &&
type !== schema.type &&
((_d = (_c = schema.errMsgs) === null || _c === void 0 ? void 0 : _c.type) !== null && _d !== void 0 ? _d : helper_1.ErrorMsgs.type);
break;
case "enum":
typeError =
value !== undefined &&
schema.items.findIndex(function (v) { return v.value === value; }) === -1 &&
((_f = (_e = schema.errMsgs) === null || _e === void 0 ? void 0 : _e.type) !== null && _f !== void 0 ? _f : helper_1.ErrorMsgs.type);
}
typeError && errors.push(typeError);
}
// Validations
schema.validations && errors.push.apply(errors, __spreadArray([], __read(helper_1.executeValidations(schema.validations, payload))));
return {
isValid: errors.length === 0,
errors: errors,
};
}
exports.validateSimpleType = validateSimpleType;