model-layer
Version:
102 lines • 3.15 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.ModelType = exports.MakeModelType = void 0;
const Type_1 = require("./Type");
const Model_1 = require("../Model");
const utils_1 = require("../utils");
const errors_1 = require("../errors");
function MakeModelType(params) {
return {
...params,
type: "model"
};
}
exports.MakeModelType = MakeModelType;
MakeModelType.isTypeHelper = true;
class ModelType extends Type_1.Type {
constructor(params) {
super(params);
this.Model = params.Model;
}
static prepareDescription(description) {
const isCustomModel = (typeof description.type === "function" &&
description.type.prototype instanceof Model_1.Model);
if (isCustomModel) {
const CustomModel = description.type;
description.type = "model";
description.Model = CustomModel;
}
}
prepare(value, key, model) {
if (value == null) {
return null;
}
const CustomModel = this.Model;
const className = CustomModel.name;
if (value instanceof CustomModel) {
value.parent = model;
return value;
}
if (utils_1.isNaN(value) ||
typeof value === "boolean" ||
typeof value === "number" ||
typeof value === "string" ||
value instanceof Date ||
value instanceof RegExp ||
Array.isArray(value)) {
const valueAsString = utils_1.invalidValuesAsString(value);
throw new errors_1.InvalidModelError({
key,
className,
invalidValue: valueAsString
});
}
try {
value = new CustomModel(value);
}
catch (err) {
const valueAsString = utils_1.invalidValuesAsString(value);
// show child error
throw new errors_1.InvalidModelError({
key,
className,
invalidValue: valueAsString,
modelError: err.message
});
}
value.parent = model;
return value;
}
typeAsString() {
return this.Model.name;
}
toJSON(model, stack) {
if (stack.includes(model)) {
throw new errors_1.CircularStructureToJSONError({});
}
stack.push(model);
return model.toJSON(stack);
}
clone(model, stack, parentModel) {
const modelClone = model.clone(stack);
modelClone.parent = parentModel;
return modelClone;
}
equal(selfModel, otherModel, stack) {
if (selfModel == null) {
return otherModel === null;
}
if (!otherModel) {
return false;
}
// stop circular recursion
const stacked = stack.get(selfModel);
if (stacked) {
return stacked === otherModel;
}
stack.add(selfModel, otherModel);
return selfModel.equal(otherModel, stack);
}
}
exports.ModelType = ModelType;
//# sourceMappingURL=ModelType.js.map