UNPKG

@zcorky/schema

Version:

Object schema validation written with TypeScript, inspired by dayjs and schema

67 lines 2.28 kB
"use strict"; var __importStar = (this && this.__importStar) || function (mod) { if (mod && mod.__esModule) return mod; var result = {}; if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k]; result["default"] = mod; return result; }; Object.defineProperty(exports, "__esModule", { value: true }); const is_1 = require("@zcorky/is"); const constants_1 = require("./constants"); const Types = __importStar(require("../types")); const schemaOf = (schema, type) => schema instanceof type; const oneOf = (schema, types) => { return types.some((t) => schemaOf(schema, t)); }; function validate(schema, value, options) { const path = options && options.path || constants_1.DEFAULT_OPTIONS.path; if (is_1.undef(value)) { if (!is_1.undef(schema.getMeta('default'))) { return schema.getMeta('default'); } if (!schema.getMeta('required')) { return value; } } if (oneOf(schema, [Types.string, Types.number, Types.boolean])) { return schema.validate(path, value, options); } if (schemaOf(schema, Types.object)) { const v = schema.validate(path, value, options); if (schema.getMeta('nullable') && v === null) { return null; } const o = schema; return o .keys() .reduce((prev, key) => { const nextPath = `${path}.${key}`; const notUndefinedValue = validate(o.get(key), v[key], { ...options, path: nextPath, }); if (!is_1.undef(notUndefinedValue)) { prev[key] = notUndefinedValue; } return prev; }, {}); } if (schemaOf(schema, Types.array)) { const v = schema.validate(path, value, options); const o = schema; const s = o.getType(); if (schema.getMeta('nullable') && v === null) { return null; } return v.map((ev, index) => { const nextPath = `${path}.${index}`; return validate(s, ev, { ...options, path: nextPath, }); }); } } exports.validate = validate; //# sourceMappingURL=validate.js.map