UNPKG

flowjv

Version:

Flow based approach to JSON validation!

86 lines (85 loc) 3.1 kB
"use strict"; 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 __spread = (this && this.__spread) || function () { for (var ar = [], i = 0; i < arguments.length; i++) ar = ar.concat(__read(arguments[i])); return ar; }; Object.defineProperty(exports, "__esModule", { value: true }); exports.execPrimitiveFlow = void 0; var jsonexpression_1 = require("../../../jsonexpression"); var immutable_1 = require("../../../helper/immutable"); var execPrimitiveFlow = function (flow, data, options) { var _a, _b; var validations = flow.validations || []; var errorMsgs = []; var ref = immutable_1.get(data.data, data.refPath || []); if (options === null || options === void 0 ? void 0 : options.typeCheck) { switch (flow.type) { case "boolean": case "number": case "string": { if (ref && typeof ref !== flow.type) { errorMsgs.push(flow.errTypeMsg || "TypeError: value for key " + ((_a = data.refPath) === null || _a === void 0 ? void 0 : _a.join(".")) + " is expected to be of type " + flow.type); } break; } case "enum": { if (ref && !flow.items.find(function (v) { return v.value === ref; })) { errorMsgs.push(flow.errTypeMsg || "EnumError: value for key " + ((_b = data.refPath) === null || _b === void 0 ? void 0 : _b.join(".")) + " should be one of the enum defined."); } break; } } } if (flow.isRequired) { switch (flow.type) { case "boolean": case "number": case "string": case "enum": { if (ref == null) { errorMsgs.push(flow.errRequiredMsg || "Value is required."); } break; } } } switch (flow.type) { case "enum": case "boolean": case "number": case "string": case "custom": { errorMsgs.push.apply(errorMsgs, __spread(validations .map(function (_a) { var logic = _a.logic, err = _a.err; var result = !!jsonexpression_1.execJSONExpression(logic, data); return result ? null : err || "Error"; }) .filter(function (v) { return v !== null; }))); break; } } return { errors: [{ msgs: errorMsgs, refPath: data.refPath || [] }], isValid: errorMsgs.length === 0, }; }; exports.execPrimitiveFlow = execPrimitiveFlow;