UNPKG

@backland/schema

Version:

TypeScript schema declaration and validation library with static type inference

74 lines (72 loc) 2.35 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.UnionField = void 0; var _utils = require("@backland/utils"); var _CircularDeps = require("../CircularDeps"); var _FieldType = require("./FieldType"); class UnionField extends _FieldType.FieldType { // utils = { fieldTypes: [] }; static is(item) { var _item$utils; return (item === null || item === void 0 ? void 0 : item.typeName) === 'union' && Array.isArray(item === null || item === void 0 ? void 0 : (_item$utils = item.utils) === null || _item$utils === void 0 ? void 0 : _item$utils.fieldTypes); } constructor(def) { super({ def: def, name: 'union' }); const { parseObjectField } = _CircularDeps.CircularDeps; this.utils.fieldTypes = def.map((el, index) => { try { return parseObjectField(`UnionItem_${index}`, el, true); } catch (e) { let message = `Filed to parse type:`; message += `\n${(0, _utils.inspectObject)(el, { tabSize: 2 })}`; e.stack = message + '\n' + e.stack; throw e; } }); const hasOptional = this.utils.fieldTypes.some(el => el.optional); if (hasOptional) { this.toOptional(); } this.parse = this.applyParser({ parse: input => { if (input === undefined && this.optional) return input; const messages = []; const objectErrors = []; for (let parser of this.utils.fieldTypes) { try { return parser.parse(input); } catch (e) { messages.push(`As ${parser.typeName} throws: ${e.message}`); if (parser.typeName === 'object' && (0, _utils.getTypeName)(input) === 'Object') { objectErrors.push(e); } } } if (objectErrors.length) { throw objectErrors[0]; } const expected = (0, _utils.uniq)(this.utils.fieldTypes.map(el => el.typeName)).join(' or '); let errorMessage = `Expected value to match one of the following types: ${expected}.`; messages.forEach(err => errorMessage += `\n- ${err}`); throw new Error(errorMessage); } }); } static create = def => { return new UnionField(def); }; } exports.UnionField = UnionField; //# sourceMappingURL=UnionField.js.map