@backland/schema
Version:
TypeScript schema declaration and validation library with static type inference
73 lines (72 loc) • 3.11 kB
JavaScript
function _defineProperty(obj, key, value) { key = _toPropertyKey(key); if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
function _toPropertyKey(arg) { var key = _toPrimitive(arg, "string"); return typeof key === "symbol" ? key : String(key); }
function _toPrimitive(input, hint) { if (typeof input !== "object" || input === null) return input; var prim = input[Symbol.toPrimitive]; if (prim !== undefined) { var res = prim.call(input, hint || "default"); if (typeof res !== "object") return res; throw new TypeError("@@toPrimitive must return a primitive value."); } return (hint === "string" ? String : Number)(input); }
import { getTypeName } from '@backland/utils';
import { inspectObject } from '@backland/utils';
import { uniq } from '@backland/utils';
import { CircularDeps } from '../CircularDeps';
import { FieldType } from './FieldType';
export class UnionField extends FieldType {
//
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'
});
_defineProperty(this, "parse", void 0);
_defineProperty(this, "utils", {
fieldTypes: []
});
var {
parseObjectField
} = CircularDeps;
this.utils.fieldTypes = def.map((el, index) => {
try {
return parseObjectField("UnionItem_".concat(index), el, true);
} catch (e) {
var message = "Filed to parse type:";
message += "\n".concat(inspectObject(el, {
tabSize: 2
}));
e.stack = message + '\n' + e.stack;
throw e;
}
});
var 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;
var messages = [];
var objectErrors = [];
for (var parser of this.utils.fieldTypes) {
try {
return parser.parse(input);
} catch (e) {
messages.push("As ".concat(parser.typeName, " throws: ").concat(e.message));
if (parser.typeName === 'object' && getTypeName(input) === 'Object') {
objectErrors.push(e);
}
}
}
if (objectErrors.length) {
throw objectErrors[0];
}
var expected = uniq(this.utils.fieldTypes.map(el => el.typeName)).join(' or ');
var errorMessage = "Expected value to match one of the following types: ".concat(expected, ".");
messages.forEach(err => errorMessage += "\n- ".concat(err));
throw new Error(errorMessage);
}
});
}
}
_defineProperty(UnionField, "create", def => {
return new UnionField(def);
});
//# sourceMappingURL=UnionField.js.map