model-layer
Version:
78 lines • 2.48 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.OrType = void 0;
const Type_1 = require("./Type");
const utils_1 = require("../utils");
const AnyType_1 = require("./AnyType");
const errors_1 = require("../errors");
class OrType extends Type_1.Type {
constructor({ or, ...otherParams }) {
super(otherParams);
if (!Array.isArray(or)) {
throw new errors_1.RequiredOrArrayError({});
}
if (!or.length) {
throw new errors_1.EmptyOrArrayError({});
}
for (let i = 0, n = or.length; i < n; i++) {
const elem = or[i];
if (elem instanceof Type_1.Type) {
continue;
}
throw new errors_1.InvalidOrTypeError({
index: i,
invalidValue: utils_1.invalidValuesAsString(elem)
});
}
this.or = or;
}
static prepareDescription(description, key) {
if (description.type === "or") {
// prepare OR description
try {
description.or = description.or.map((childDescription) => Type_1.Type.create(childDescription, key));
}
catch (err) {
return;
}
}
}
prepare(originalValue, key, model) {
if (originalValue == null) {
return null;
}
let value;
let currentType = null;
for (let i = 0, n = this.or.length; i < n; i++) {
const description = this.or[i];
try {
value = description.prepare(originalValue, key, model);
}
catch (err) {
continue;
}
currentType = description;
break;
}
if (!currentType) {
const valueAsString = utils_1.invalidValuesAsString(originalValue);
throw new errors_1.InvalidOrValueError({
key,
invalidValue: valueAsString,
typesNames: this.or.map((childDescription) => childDescription.type)
});
}
return value;
}
clone(value, stack) {
return AnyType_1.clone(value, stack);
}
equal(selfValue, otherValue, stack) {
return AnyType_1.equal(selfValue, otherValue, stack);
}
toJSON(value, stack) {
return AnyType_1.value2json(value, stack);
}
}
exports.OrType = OrType;
//# sourceMappingURL=OrType.js.map