UNPKG

typescript-domain

Version:

Decorator-based transformation of JSON or plain Javascript objects to classes

79 lines (78 loc) 3.01 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.Model = exports.Entity = void 0; const metadata_storage_1 = require("./metadata-storage"); const validation_1 = require("./validation"); class Entity { _debugFunction; _debugSkipUndef; _c = null; constructor(_data, _debugFunction, _debugSkipUndef) { this._debugFunction = _debugFunction; this._debugSkipUndef = _debugSkipUndef; } isValid() { return true; } update(data) { if (this._c) { this._init(this._c, data); } } _init(constructor, data) { this._c = constructor; const entityMetadata = metadata_storage_1.defaultMetadataStorage.getMetadata(constructor); if (!entityMetadata) { return; } for (const key of Object.keys(this)) { const fieldMetadata = entityMetadata.find(({ field }) => field === key); if (Object.prototype.hasOwnProperty.call(this, key) && fieldMetadata) { const hasAlias = fieldMetadata.alias && Object.prototype.hasOwnProperty.call(data, fieldMetadata.alias); const originalValue = data ? data[fieldMetadata.alias && hasAlias ? fieldMetadata.alias : fieldMetadata.field] : null; const { validatedValue, debugInfo } = (0, validation_1.validateValue)(originalValue, fieldMetadata.type, fieldMetadata.array, this._debugFunction, this._debugSkipUndef); if (this._debugFunction && debugInfo && (!this._debugSkipUndef || debugInfo !== validation_1.DEBUG_INFO.EMPTY)) { this._debugFunction({ class: constructor.name, field: fieldMetadata.field, info: debugInfo, value: JSON.stringify(originalValue) }); } const instance = this; const defaultValue = instance[key]; instance[key] = (!data || !Object.prototype.hasOwnProperty.call(data, fieldMetadata.alias && hasAlias ? fieldMetadata.alias : key)) && defaultValue ? defaultValue : validatedValue; } } } } exports.Entity = Entity; function Model(constructor) { return class extends constructor { // eslint-disable-next-line @typescript-eslint/no-explicit-any constructor(...args) { super(...args); try { this['_init'](constructor, args[0]); } catch (e) { console.error(e); console.error('Maybe you forgot to extend Entity on this component?'); throw e; } } }; } exports.Model = Model;