UNPKG

blow-data

Version:
87 lines (86 loc) 2.79 kB
'use strict'; const types = require('blow-types'); const util_1 = require('util'); const manager_1 = require('./manager'); class ModelPropertyMetadata { constructor(options) { this._name = options.name; this._columnName = util_1.isUndefined(options.columnName) ? options.name : options.columnName; this._index = util_1.isUndefined(options.index) ? false : options.index; this._id = util_1.isUndefined(options.id) ? false : options.id; this._hidden = util_1.isUndefined(options.hidden) ? false : options.hidden; this._validations = new Map(); const type = (util_1.isString(options.type) ? { name: options.type } : options.type); this._type = types.get(type); this._validations.set(type.name.toLowerCase(), true); if (!this._type) { this._type = types.build(manager_1.manager.getModel(type.name ? type.name : type)); } if (util_1.isObject(options.validations)) { Object.keys(options.validations).forEach(key => { this._validations.set(key, options.validations[key]); }); } if (!util_1.isUndefined(options.default)) { if (util_1.isFunction(options.default)) { this._default = options.default; } else { this._default = () => options.default; } } else { this._default = undefined; } } get name() { return this._name; } get columnName() { return this._columnName; } get type() { return this._type; } get default() { return this._default; } get id() { return this._id; } get index() { return this._index; } get hidden() { return this._hidden; } get validations() { return this._validations.entries(); } apply(model) { const property = this; const getter = function () { let value = this._data.get(property.name); if (util_1.isUndefined(value) && property.default) { value = property.default.bind(this)(); this._data.set(property.name, value); } return value; }; const setter = function (value) { value = property.type.parse(value); this._data.set(property.name, value); }; Object.defineProperty(model.prototype, this.name, { configurable: false, enumerable: true, get: getter, set: setter }); } static inspect(value) { const type = types.inspect(value); return { type: type }; } } exports.ModelPropertyMetadata = ModelPropertyMetadata;