UNPKG

blow-data

Version:
66 lines (65 loc) 2.06 kB
'use strict'; const util_1 = require('util'); const helpers = require('./helpers'); const Validator_1 = require('./Validator'); class BaseModel { constructor(data) { this._data = new Map(); if (!util_1.isUndefined(data)) { this.merge(data); } } static get metadata() { return this._metadata; } static get connection() { return this._connection; } static get validator() { if (!this._validator) { const syncSchema = helpers.getMetadata(this).validationSchema; const asyncSchema = helpers.getMetadata(this).asyncValidationSchema; this._validator = new Validator_1.Validator(syncSchema, asyncSchema); } return this._validator; } validate() { return helpers.getCtor(this).validator.validate(this); } merge(data) { const metadata = helpers.getMetadata(this); Object.keys(data).forEach(key => { if (metadata.isAllowedProperty(key)) { this[key] = data[key]; } }); return this; } toJSON(withHidden) { const json = {}; withHidden = util_1.isUndefined(withHidden) ? true : withHidden; for (const property of helpers.getMetadata(this).properties) { const value = this[property.name]; if (!util_1.isUndefined(value) && (withHidden || !property.hidden)) { json[property.name] = value; } } for (const relation of helpers.getMetadata(this).relations) { if (relation.type === 'belongsTo') { const value = this[relation.foreignKey]; if (!util_1.isUndefined(value) && (withHidden || !relation.hidden)) { json[relation.foreignKey] = value; } } } return json; } toSafeJSON() { return this.toJSON(false); } inspect() { return this.toJSON(); } } BaseModel.ready = false; exports.BaseModel = BaseModel;