UNPKG

model-layer

Version:
118 lines 4.02 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.ObjectType = void 0; const Type_1 = require("./Type"); const utils_1 = require("../utils"); const errors_1 = require("../errors"); class ObjectType extends Type_1.Type { constructor({ nullAsEmpty = false, emptyAsNull = false, element, ...otherParams }) { super(otherParams); this.element = element; this.nullAsEmpty = nullAsEmpty; this.emptyAsNull = emptyAsNull; if (nullAsEmpty && emptyAsNull) { throw new errors_1.ConflictNullAndEmptyObjectParameterError({}); } } static prepareDescription(description, key) { if (description.type === "object") { // prepare element description description.element = Type_1.Type.create(description.element || "any", key); } } prepare(originalObject, modelKey, parentModel) { if (originalObject == null) { if (this.nullAsEmpty) { const value = {}; Object.freeze(value); return value; } return null; } const elementDescription = this.element; const elementTypeAsString = elementDescription.typeAsString(); const isObjectValue = (typeof originalObject === "object" && !Array.isArray(originalObject) && !(originalObject instanceof RegExp)); if (!isObjectValue) { const valueAsString = utils_1.invalidValuesAsString(originalObject); throw new errors_1.InvalidObjectError({ elementType: elementTypeAsString, key: modelKey, invalidValue: valueAsString }); } const object = {}; let isEmpty = true; for (const key in originalObject) { let element = originalObject[key]; try { element = elementDescription.prepare(element, key, parentModel); } catch (err) { const valueAsString = utils_1.invalidValuesAsString(originalObject); throw new errors_1.InvalidObjectElementError({ modelKey, objectKey: key, elementType: elementTypeAsString, invalidValue: valueAsString, childError: err.message }); } object[key] = element; isEmpty = false; } if (this.emptyAsNull) { if (isEmpty) { return null; } } Object.freeze(object); return object; } toJSON(value, stack) { const obj = value; const json = {}; for (const key in obj) { const objValue = obj[key]; json[key] = this.element.toJSON(objValue, [...stack]); } return json; } clone(value, stack, parentModel) { const obj = value; const json = {}; for (const key in obj) { const objValue = obj[key]; json[key] = this.element.clone(objValue, stack, parentModel); } return json; } equal(selfObj, otherObj, stack) { if (selfObj == null) { return otherObj === null; } if (!utils_1.isObject(otherObj)) { return false; } for (const key in selfObj) { const selfValue = selfObj[key]; const otherValue = otherObj[key]; const isEqual = this.element.equal(selfValue, otherValue, stack); if (!isEqual) { return false; } } // check additional keys from otherObj for (const key in otherObj) { if (key in selfObj) { continue; } // exists unknown property for selfObj return false; } return true; } } exports.ObjectType = ObjectType; //# sourceMappingURL=ObjectType.js.map