diff --git a/examples/datasource-app.js b/examples/datasource-app.js index b61b9a53..d22b0691 100644 --- a/examples/datasource-app.js +++ b/examples/datasource-app.js @@ -78,6 +78,11 @@ User.create({name: 'Ray'}, function (err, data) { console.log(data); }); +User.scope('minors', {age: {le: 16}}); +User.minors(function(err, kids) { + console.log('Kids: ', kids); +}); + var Article = ds.define('Article', {title: String}); var Tag = ds.define('Tag', {name: String}); Article.hasAndBelongsToMany('tags'); diff --git a/index.js b/index.js index c766f771..34949bb5 100644 --- a/index.js +++ b/index.js @@ -1,9 +1,9 @@ var fs = require('fs'); -var path = require('path'); -exports.ModelBuilder = exports.LDL = require('./lib/model-builder').ModelBuilder; -exports.DataSource = exports.Schema = require('./lib/datasource').DataSource; +exports.ModelBuilder = exports.LDL = require('./lib/model-builder.js').ModelBuilder; +exports.DataSource = exports.Schema = require('./lib/datasource.js').DataSource; exports.ModelBaseClass = require('./lib/model.js'); +exports.Connector = require('./lib/connector.js'); var baseSQL = './lib/sql'; diff --git a/lib/connector.js b/lib/connector.js new file mode 100644 index 00000000..9587dda0 --- /dev/null +++ b/lib/connector.js @@ -0,0 +1,131 @@ +module.exports = Connector; + +/** + * Base class for LooopBack connector. This is more a collection of useful + * methods for connectors than a super class + * @constructor + */ +function Connector(name, settings) { + this._models = {}; + this.name = name; + this.settings = settings || {}; +} + +/** + * Set the relational property to indicate the backend is a relational DB + * @type {boolean} + */ +Connector.prototype.relational = false; + +/** + * Execute a command with given parameters + * @param {String} command The command such as SQL + * @param {Object[]} [params] An array of parameters + * @param {Function} [callback] The callback function + */ +Connector.prototype.execute = function (command, params, callback) { + throw new Error('query method should be declared in connector'); +}; + + +/** + * Look up the data source by model name + * @param {String} model The model name + * @returns {DataSource} The data source + */ +Connector.prototype.getDataSource = function(model) { + var m = this._models[model]; + if(!m) { + console.trace('Model not found: ' + model); + } + return m && m.model.dataSource; +}; + +/** + * Get the id property name + * @param {String} model The model name + * @returns {String} The id property name + */ +Connector.prototype.idName = function (model) { + return this.getDataSource(model).idName(model); +}; + +/** + * Get the id property names + * @param {String} model The model name + * @returns {[String]} The id property names + */ +Connector.prototype.idNames = function (model) { + return this.getDataSource(model).idNames(model); +}; + + +/** + * Get the id index (sequence number, starting from 1) + * @param {String} model The model name + * @param {String} prop The property name + * @returns {Number} The id index, undefined if the property is not part of the primary key + */ +Connector.prototype.id = function (model, prop) { + var p = this._models[model].properties[prop]; + if(!p) { + console.trace('Property not found: ' + model +'.' + prop); + } + return p.id; +}; + +/** + * Hook to be called by DataSource for defining a model + * @param {Object} modelDefinition The model definition + */ +Connector.prototype.define = function (modelDefinition) { + if (!modelDefinition.settings) { + modelDefinition.settings = {}; + } + this._models[modelDefinition.model.modelName] = modelDefinition; +}; + +/** + * Hook to be called by DataSource for defining a model property + * @param {String} model The model name + * @param {String} propertyName The property name + * @param {Object} propertyDefinition The object for property metadata + */ +Connector.prototype.defineProperty = function (model, propertyName, propertyDefinition) { + this._models[model].properties[propertyName] = propertyDefinition; +}; + +/** + * Disconnect from the connector + */ +Connector.prototype.disconnect = function disconnect(cb) { + // NO-OP +}; + +/** + * Get the id value for the given model + * @param {String} model The model name + * @param {Object} data The model instance data + * @returns {*} The id value + * + */ +Connector.prototype.getIdValue = function(model, data) { + return data && data[this.idName(model)]; +}; + +/** + * Set the id value for the given model + * @param {String} model The model name + * @param {Object} data The model instance data + * @param {*} value The id value + * + */ +Connector.prototype.setIdValue = function(model, data, value) { + if(data) { + data[this.idName(model)] = value; + } +}; + + + + diff --git a/lib/connectors/memory.js b/lib/connectors/memory.js index 2749c040..7af66e29 100644 --- a/lib/connectors/memory.js +++ b/lib/connectors/memory.js @@ -1,7 +1,15 @@ +var util = require('util'); +var Connector = require('../connector'); var geo = require('../geo'); var utils = require('../utils'); -exports.initialize = function initializeSchema(dataSource, callback) { +/** + * Initialize the Oracle connector against the given data source + * + * @param {DataSource} dataSource The loopback-datasource-juggler dataSource + * @param {Function} [callback] The callback function + */ +exports.initialize = function initializeDataSource(dataSource, callback) { dataSource.connector = new Memory(); dataSource.connector.connect(callback); }; @@ -13,15 +21,18 @@ function Memory(m) { this.isTransaction = true; this.cache = m.cache; this.ids = m.ids; + this.constructor.super_.call(this, 'memory'); this._models = m._models; } else { this.isTransaction = false; this.cache = {}; this.ids = {}; - this._models = {}; + this.constructor.super_.call(this, 'memory'); } } +util.inherits(Memory, Connector); + Memory.prototype.connect = function(callback) { if (this.isTransaction) { this.onTransactionExec = callback; @@ -30,50 +41,13 @@ Memory.prototype.connect = function(callback) { } }; -Memory.prototype.define = function defineModel(descr) { - var m = descr.model.modelName; - this._models[m] = descr; +Memory.prototype.define = function defineModel(definition) { + this.constructor.super_.prototype.define.apply(this, [].slice.call(arguments)); + var m = definition.model.modelName; this.cache[m] = {}; this.ids[m] = 1; }; -/** - * Get the id property name for the given model - * @param {String} model The model name - * @returns {String} The id property name - * - * @private - */ -Memory.prototype.idName = function(model) { - return (this.dataSource && this.dataSource.idName && this.dataSource.idName(model)) || 'id'; -}; - -/** - * Get the id value for the given model - * @param {String} model The model name - * @param {Object} data The model instance data - * @returns {*} The id value - * - * @private - */ -Memory.prototype.getIdValue = function(model, data) { - return data && data[this.idName(model)]; -}; - -/** - * Set the id value for the given model - * @param {String} model The model name - * @param {Object} data The model instance data - * @param {*} value The id value - * - * @private - */ -Memory.prototype.setIdValue = function(model, data, value) { - if(data) { - data[this.idName(model)] = value; - } -}; - Memory.prototype.create = function create(model, data, callback) { // FIXME: [rfeng] We need to generate unique ids based on the id type // FIXME: [rfeng] We don't support composite ids yet diff --git a/lib/dao.js b/lib/dao.js index b172298c..9bee58a3 100644 --- a/lib/dao.js +++ b/lib/dao.js @@ -59,7 +59,7 @@ DataAccessObject._forDB = function (data) { } var res = {}; Object.keys(data).forEach(function (propName) { - var type = this.whatTypeName(propName); + var type = this.getPropertyType(propName); if (type === 'JSON' || type === 'Any' || type === 'Object' || data[propName] instanceof Array) { res[propName] = JSON.stringify(data[propName]); } else { @@ -202,17 +202,7 @@ setRemoting(DataAccessObject.create, { }); function stillConnecting(dataSource, obj, args) { - if (dataSource.connected) return false; // Connected - - var method = args.callee; - // Set up a callback after the connection is established to continue the method call - dataSource.once('connected', function () { - method.apply(obj, [].slice.call(args)); - }); - if (!dataSource.connecting) { - dataSource.connect(); - } - return true; + return dataSource.ready(obj, args); } /** @@ -381,7 +371,7 @@ DataAccessObject.find = function find(params, cb) { // normalize fields as array of included property names if(fields) { - params.fields = fieldsToArray(fields, Object.keys(this.properties)); + params.fields = fieldsToArray(fields, Object.keys(this.definition.properties)); } if(near) { @@ -729,7 +719,7 @@ DataAccessObject.prototype.updateAttributes = function updateAttributes(data, cb inst._adapter().updateAttributes(model, getIdValue(inst.constructor, inst), inst.constructor._forDB(data), function (err) { if (!err) { - // update _was attrs + // update $was attrs Object.keys(data).forEach(function (key) { inst.__dataWas[key] = inst.__data[key]; }); @@ -790,6 +780,16 @@ function defineReadonlyProp(obj, key, value) { }); } +var defineScope = require('./scope.js').defineScope; + +/** + * Define scope + */ +DataAccessObject.scope = function (name, filter) { + defineScope(this, this, name, filter); +}; + + // jutil.mixin(DataAccessObject, validations.Validatable); jutil.mixin(DataAccessObject, Inclusion); jutil.mixin(DataAccessObject, Relation); diff --git a/lib/datasource.js b/lib/datasource.js index 027eb866..d854bd95 100644 --- a/lib/datasource.js +++ b/lib/datasource.js @@ -2,6 +2,7 @@ * Module dependencies */ var ModelBuilder = require('./model-builder.js').ModelBuilder; +var ModelDefinition = require('./model-definition.js'); var jutil = require('./jutil'); var ModelBaseClass = require('./model.js'); var DataAccessObject = require('./dao.js'); @@ -340,7 +341,7 @@ DataSource.prototype.createModel = DataSource.prototype.define = function define // pass control to connector this.connector.define({ model: NewClass, - properties: properties, + properties: NewClass.definition.properties, settings: settings }); } @@ -357,7 +358,6 @@ DataSource.prototype.createModel = DataSource.prototype.define = function define DataSource.prototype.mixin = function (ModelCtor) { var ops = this.operations(); - var self = this; var DAO = this.DataAccessObject; // mixin DAO @@ -366,7 +366,6 @@ DataSource.prototype.mixin = function (ModelCtor) { // decorate operations as alias functions Object.keys(ops).forEach(function (name) { var op = ops[name]; - var fn = op.scope[op.fnName]; var scope; if(op.enabled) { @@ -381,7 +380,7 @@ DataSource.prototype.mixin = function (ModelCtor) { 'scope', 'fnName', 'prototype' - ].indexOf(key) + ].indexOf(key); }) .forEach(function (key) { if(typeof op[key] !== 'undefined') { @@ -390,7 +389,7 @@ DataSource.prototype.mixin = function (ModelCtor) { }); } }); -} +}; /** * Attach an existing model to a data source. @@ -399,6 +398,10 @@ DataSource.prototype.mixin = function (ModelCtor) { */ DataSource.prototype.attach = function (ModelCtor) { + if(ModelCtor.dataSource === this) { + // Already attached to the data source + return; + } var properties = ModelCtor.dataSource.definitions[ModelCtor.modelName].properties; var settings = ModelCtor.dataSource.definitions[ModelCtor.modelName].settings; var className = ModelCtor.modelName; @@ -419,10 +422,7 @@ DataSource.prototype.attach = function (ModelCtor) { ModelCtor.dataSource = this; // add to def - this.definitions[className] = { - properties: properties, - settings: settings - }; + this.definitions[className] = new ModelDefinition(this, className, properties, settings); this.models[className] = ModelCtor; @@ -439,8 +439,9 @@ DataSource.prototype.attach = function (ModelCtor) { DataSource.prototype.defineProperty = function (model, prop, params) { ModelBuilder.prototype.defineProperty.call(this, model, prop, params); + var resolvedProp = this.definitions[model].properties[prop]; if (this.connector.defineProperty) { - this.connector.defineProperty(model, prop, params); + this.connector.defineProperty(model, prop, resolvedProp); } }; @@ -1179,12 +1180,7 @@ DataSource.prototype.freeze = function freeze() { * @param {String} modelName The model name */ DataSource.prototype.tableName = function (modelName) { - var settings = this.definitions[modelName].settings; - if(settings[this.connector.name]) { - return settings[this.connector.name].table || modelName; - } else { - return modelName; - } + return this.definitions[modelName].tableName(this.connector.name); }; /** @@ -1194,15 +1190,7 @@ DataSource.prototype.tableName = function (modelName) { * @returns {String} columnName */ DataSource.prototype.columnName = function (modelName, propertyName) { - if(!propertyName) { - return propertyName; - } - var property = this.definitions[modelName].properties[propertyName]; - if(property && property[this.connector.name]) { - return property[this.connector.name].columnName || propertyName; - } else { - return propertyName; - } + return this.definitions[modelName].columnName(this.connector.name, propertyName); }; /** @@ -1212,15 +1200,7 @@ DataSource.prototype.columnName = function (modelName, propertyName) { * @returns {Object} column metadata */ DataSource.prototype.columnMetadata = function (modelName, propertyName) { - if(!propertyName) { - return propertyName; - } - var property = this.definitions[modelName].properties[propertyName]; - if(property && property[this.connector.name]) { - return property[this.connector.name]; - } else { - return null; - } + return this.definitions[modelName].columnMetadata(this.connector.name, propertyName); }; /** @@ -1229,16 +1209,7 @@ DataSource.prototype.columnMetadata = function (modelName, propertyName) { * @returns {String[]} column names */ DataSource.prototype.columnNames = function (modelName) { - var props = this.definitions[modelName].properties; - var cols = []; - for(var p in props) { - if(props[p][this.connector.name]) { - cols.push(props[p][this.connector.name].columnName || p); - } else { - cols.push(p); - } - } - return cols; + return this.definitions[modelName].columnNames(this.connector.name); }; /** @@ -1247,7 +1218,7 @@ DataSource.prototype.columnNames = function (modelName) { * @returns {String} columnName for ID */ DataSource.prototype.idColumnName = function(modelName) { - return this.columnName(modelName, this.idName(modelName)); + return this.definitions[modelName].idColumnName(this.connector.name); }; /** @@ -1256,16 +1227,10 @@ DataSource.prototype.idColumnName = function(modelName) { * @returns {String} property name for ID */ DataSource.prototype.idName = function(modelName) { - var props = this.definitions[modelName].properties; - if(props.id && props.id.id) { - return 'id'; + if(!this.definitions[modelName].idName) { + console.log(this.definitions[modelName]); } - for(var key in props) { - if(props[key].id) { - return key; - } - } - return null; + return this.definitions[modelName].idName(); }; /** @@ -1274,20 +1239,7 @@ DataSource.prototype.idName = function(modelName) { * @returns {String[]} property names for IDs */ DataSource.prototype.idNames = function (modelName) { - var ids = []; - var props = this.definitions[modelName].properties; - for (var key in props) { - if (props[key].id && props[key].id > 0) { - ids.push({name: key, id: props[key].id}); - } - } - ids.sort(function (a, b) { - return a.key - b.key; - }); - var names = ids.map(function (id) { - return id.name; - }); - return names; + return this.definitions[modelName].idNames(); }; @@ -1358,6 +1310,7 @@ DataSource.prototype.copyModel = function copyModel(Master) { util.inherits(Slave, Master); + // Delegating static properties Slave.__proto__ = Master; hiddenProperty(Slave, 'dataSource', dataSource); @@ -1368,10 +1321,7 @@ DataSource.prototype.copyModel = function copyModel(Master) { // store class in model pool dataSource.models[className] = Slave; - dataSource.definitions[className] = { - properties: md.properties, - settings: md.settings - }; + dataSource.definitions[className] = new ModelDefinition(dataSource, md.name, md.properties, md.settings); if ((!dataSource.isTransaction) && dataSource.connector && dataSource.connector.define) { dataSource.connector.define({ @@ -1393,7 +1343,12 @@ DataSource.prototype.copyModel = function copyModel(Master) { */ DataSource.prototype.transaction = function() { var dataSource = this; - var transaction = new EventEmitter; + var transaction = new EventEmitter(); + + for (var p in dataSource) { + transaction[p] = dataSource[p]; + } + transaction.isTransaction = true; transaction.origin = dataSource; transaction.name = dataSource.name; @@ -1410,8 +1365,6 @@ DataSource.prototype.transaction = function() { dataSource.copyModel.call(transaction, dataSource.models[i]); } - transaction.connect = dataSource.connect; - transaction.exec = function(cb) { transaction.connector.exec(cb); }; @@ -1482,7 +1435,7 @@ DataSource.prototype.defineOperation = function (name, options, fn) { options.fn = fn; options.name = name; this._operations[name] = options; -} +}; /** * Check if the backend is a relational DB @@ -1490,7 +1443,31 @@ DataSource.prototype.defineOperation = function (name, options, fn) { */ DataSource.prototype.isRelational = function() { return this.connector && this.connector.relational; -} +}; + +/** + * Check if the data source is ready + * @param obj + * @param args + * @returns {boolean} + */ +DataSource.prototype.ready = function(obj, args) { + if (this.connected) { + // Connected + return false; + } + + var method = args.callee; + // Set up a callback after the connection is established to continue the method call + this.once('connected', function () { + method.apply(obj, [].slice.call(args)); + }); + if (!this.connecting) { + this.connect(); + } + return true; +}; + /** * Define a hidden property diff --git a/lib/jutil.js b/lib/jutil.js index e9cf7c26..d5b9e59b 100644 --- a/lib/jutil.js +++ b/lib/jutil.js @@ -24,12 +24,21 @@ exports.inherits = function (newClass, baseClass, options) { /** - * Mix in the base class into the new class - * @param newClass - * @param baseClass + * Mix in the a class into the new class + * @param newClass The target class to receive the mixin + * @param mixinClass The class to be mixed in * @param options */ -exports.mixin = function (newClass, baseClass, options) { +exports.mixin = function (newClass, mixinClass, options) { + if (Array.isArray(newClass._mixins)) { + if(newClass._mixins.indexOf(mixinClass) !== -1) { + return; + } + newClass._mixins.push(mixinClass); + } else { + newClass._mixins = [mixinClass]; + } + options = options || { staticProperties: true, instanceProperties: true, @@ -37,31 +46,25 @@ exports.mixin = function (newClass, baseClass, options) { }; if (options.staticProperties) { - Object.keys(baseClass).forEach(function (classProp) { - if (classProp !== 'super_' && (!newClass.hasOwnProperty(classProp) || options.override)) { - var pd = Object.getOwnPropertyDescriptor(baseClass, classProp); + Object.keys(mixinClass).forEach(function (classProp) { + if (classProp !== 'super_' && classProp !== '_mixins' && (!newClass.hasOwnProperty(classProp) || options.override)) { + var pd = Object.getOwnPropertyDescriptor(mixinClass, classProp); Object.defineProperty(newClass, classProp, pd); } }); } if (options.instanceProperties) { - if (baseClass.prototype) { - Object.keys(baseClass.prototype).forEach(function (instanceProp) { + if (mixinClass.prototype) { + Object.keys(mixinClass.prototype).forEach(function (instanceProp) { if (!newClass.hasOwnProperty(instanceProp) || options.override) { - var pd = Object.getOwnPropertyDescriptor(baseClass.prototype, instanceProp); + var pd = Object.getOwnPropertyDescriptor(mixinClass.prototype, instanceProp); Object.defineProperty(newClass.prototype, instanceProp, pd); } }); } } - if (Array.isArray(newClass._mixins)) { - newClass._mixins.push(baseClass); - } else { - newClass._mixins = [baseClass]; - } - return newClass; }; diff --git a/lib/model-builder.js b/lib/model-builder.js index a449bebf..25a18179 100644 --- a/lib/model-builder.js +++ b/lib/model-builder.js @@ -2,11 +2,12 @@ * Module dependencies */ -var i8n = require('inflection'); -var DefaultModelBaseClass = require('./model.js'); -var List = require('./list.js'); +var inflection = require('inflection'); var EventEmitter = require('events').EventEmitter; var util = require('util'); +var DefaultModelBaseClass = require('./model.js'); +var List = require('./list.js'); +var ModelDefinition = require('./model-definition.js'); // Set up types require('./types')(ModelBuilder); @@ -40,8 +41,12 @@ function ModelBuilder() { this.definitions = {}; } +// Inherit from EventEmitter util.inherits(ModelBuilder, EventEmitter); +// Create a default instance +ModelBuilder.defaultInstance = new ModelBuilder(); + /** * Define a model class * @@ -99,8 +104,6 @@ ModelBuilder.prototype.define = function defineClass(className, properties, sett settings.strict = false; } - this.buildSchema(className, properties); - // every class can receive hash of data as optional param var ModelClass = function ModelConstructor(data, dataSource) { if(!(this instanceof ModelConstructor)) { @@ -111,109 +114,144 @@ ModelBuilder.prototype.define = function defineClass(className, properties, sett hiddenProperty(this, 'dataSource', dataSource || this.constructor.dataSource); } }; - - // mix in EventEmitter (dont inherit from) - var events = new EventEmitter(); - ModelClass.on = events.on.bind(events); - ModelClass.once = events.once.bind(events); - ModelClass.emit = events.emit.bind(events); - ModelClass.setMaxListeners = events.setMaxListeners.bind(events); + // mix in EventEmitter (don't inherit from) + var events = new EventEmitter(); + for (var f in EventEmitter.prototype) { + if (typeof EventEmitter.prototype[f]) { + ModelClass[f] = events[f].bind(events); + } + } + + // Add metadata to the ModelClass hiddenProperty(ModelClass, 'dataSource', dataSource); hiddenProperty(ModelClass, 'schema', dataSource); // For backward compatibility hiddenProperty(ModelClass, 'modelName', className); - hiddenProperty(ModelClass, 'pluralModelName', pluralName || i8n.pluralize(className)); + hiddenProperty(ModelClass, 'pluralModelName', pluralName || inflection.pluralize(className)); hiddenProperty(ModelClass, 'relations', {}); util.inherits(ModelClass, ModelBaseClass); // inherit ModelBaseClass static methods for (var i in ModelBaseClass) { + if(i !== '_mixins') { ModelClass[i] = ModelBaseClass[i]; + } } ModelClass.getter = {}; ModelClass.setter = {}; - standartize(properties, settings); + var modelDefinition = new ModelDefinition(this, className, properties, settings); // store class in model pool this.models[className] = ModelClass; - this.definitions[className] = { - properties: properties, - settings: settings - }; + this.definitions[className] = modelDefinition; // expose properties on the ModelClass - ModelClass.properties = properties; - ModelClass.settings = settings; + ModelClass.definition = modelDefinition; var idInjection = settings.idInjection; if(idInjection !== false) { + // Default to true if undefined idInjection = true; } - for(var p in properties) { - if(properties[p].id) { - idInjection = false; - ModelClass.prototype.__defineGetter__('id', function () { - return this.__data[p]; - }); - break; - } + + var idNames = modelDefinition.idNames(); + if(idNames.length > 0) { + // id already exists + idInjection = false; } + // Add the id property if (idInjection) { - - ModelClass.prototype.__defineGetter__('id', function () { - return this.__data.id; - }); - // Set up the id property - properties.id = properties.id || { type: Number, id: 1, generated: true }; - if (!properties.id.id) { - properties.id.id = 1; - } + ModelClass.definition.defineProperty('id', { type: Number, id: 1, generated: true }); } + idNames = modelDefinition.idNames(); // Reload it after rebuild + // Create a virtual property 'id' + if (idNames.length === 1) { + var idProp = idNames[0]; + if (idProp !== 'id') { + Object.defineProperty(ModelClass.prototype, 'id', { + get: function () { + var idProp = ModelClass.definition.idNames[0]; + return this.__data[idProp]; + }, + configurable: true, + enumerable: false + }); + } + } else { + // Now the id property is an object that consists of multiple keys + Object.defineProperty(ModelClass.prototype, 'id', { + get: function () { + var compositeId = {}; + var idNames = ModelClass.definition.idNames(); + for (var p in idNames) { + compositeId[p] = this.__data[p]; + } + return compositeId; + }, + configurable: true, + enumerable: false + }); + } + + // A function to loop through the properties ModelClass.forEachProperty = function (cb) { - Object.keys(properties).forEach(cb); + Object.keys(ModelClass.definition.properties).forEach(cb); }; + // A function to attach the model class to a data source ModelClass.attachTo = function (dataSource) { dataSource.attach(this); }; - - ModelClass.extend = function (className, p, s) { - p = p || {}; - s = s || {}; - + + // A function to extend the model + ModelClass.extend = function (className, subclassProperties, subclassSettings) { + var properties = ModelClass.definition.properties; + var settings = ModelClass.definition.settings; + + subclassProperties = subclassProperties || {}; + subclassSettings = subclassSettings || {}; + // Merging the properties Object.keys(properties).forEach(function (key) { - // dont inherit the id property - if(key !== 'id' && typeof p[key] === 'undefined') { - p[key] = properties[key]; + // don't inherit the id property + if(key !== 'id' && typeof subclassProperties[key] === 'undefined') { + subclassProperties[key] = properties[key]; } }); - + + // Merge the settings Object.keys(settings).forEach(function (key) { - if(typeof s[key] === 'undefined') { - s[key] = settings[key]; + if(typeof subclassSettings[key] === 'undefined') { + subclassSettings[key] = settings[key]; } }); - - var c = dataSource.define(className, p, s, ModelClass); - - if(typeof c.setup === 'function') { - c.setup.call(c); + + // Define the subclass + var subClass = dataSource.define(className, subclassProperties, subclassSettings, ModelClass); + + // Calling the setup function + if(typeof subClass.setup === 'function') { + subClass.setup.call(subClass); } - return c; + return subClass; }; - ModelClass.registerProperty = function (attr) { - var prop = properties[attr]; + /** + * Register a property for the model class + * @param propertyName + */ + ModelClass.registerProperty = function (propertyName) { + var properties = modelDefinition.build(); + var prop = properties[propertyName]; var DataType = prop.type; if(!DataType) { - throw new Error('Invalid type for property ' + attr); + throw new Error('Invalid type for property ' + propertyName); } if (Array.isArray(DataType) || DataType === Array) { DataType = List; @@ -228,33 +266,33 @@ ModelBuilder.prototype.define = function defineClass(className, properties, sett if(prop.required) { var requiredOptions = typeof prop.required === 'object' ? prop.required : undefined; - ModelClass.validatesPresenceOf(attr, requiredOptions); + ModelClass.validatesPresenceOf(propertyName, requiredOptions); } - Object.defineProperty(ModelClass.prototype, attr, { + Object.defineProperty(ModelClass.prototype, propertyName, { get: function () { - if (ModelClass.getter[attr]) { - return ModelClass.getter[attr].call(this); + if (ModelClass.getter[propertyName]) { + return ModelClass.getter[propertyName].call(this); // Try getter first } else { - return this.__data && this.__data[attr]; + return this.__data && this.__data[propertyName]; // Try __data } }, set: function (value) { - if (ModelClass.setter[attr]) { - ModelClass.setter[attr].call(this, value); + if (ModelClass.setter[propertyName]) { + ModelClass.setter[propertyName].call(this, value); // Try setter first } else { if (!this.__data) { this.__data = {}; } if (value === null || value === undefined) { - this.__data[attr] = value; + this.__data[propertyName] = value; } else { if(DataType === List) { - this.__data[attr] = DataType(value, properties[attr].type, this.__data); + this.__data[propertyName] = DataType(value, properties[propertyName].type, this.__data); } else { // Assume the type constructor handles Constructor() call // If not, we should call new DataType(value).valueOf(); - this.__data[attr] = DataType(value); + this.__data[propertyName] = DataType(value); } } } @@ -263,21 +301,26 @@ ModelBuilder.prototype.define = function defineClass(className, properties, sett enumerable: true }); - ModelClass.prototype.__defineGetter__(attr + '_was', function () { - return this.__dataWas && this.__dataWas[attr]; + // $was --> __dataWas. + Object.defineProperty(ModelClass.prototype, propertyName + '$was', { + get: function () { + return this.__dataWas && this.__dataWas[propertyName]; + }, + configurable: true, + enumerable: false }); // FIXME: [rfeng] Do we need to keep the raw data? // Use $ as the prefix to avoid conflicts with properties such as _id - Object.defineProperty(ModelClass.prototype, '$' + attr, { + Object.defineProperty(ModelClass.prototype, '$' + propertyName, { get: function () { - return this.__data && this.__data[attr]; + return this.__data && this.__data[propertyName]; }, set: function (value) { if (!this.__data) { this.__data = {}; } - this.__data[attr] = value; + this.__data[propertyName] = value; }, configurable: true, enumerable: false @@ -290,29 +333,16 @@ ModelBuilder.prototype.define = function defineClass(className, properties, sett }; -function standartize(properties, settings) { - Object.keys(properties).forEach(function (key) { - var v = properties[key]; - if (typeof v === 'function' || Array.isArray(v)) { - properties[key] = { type: v }; - } - }); - // TODO: add timestamps fields - // when present in settings: {timestamps: true} - // or {timestamps: {created: 'created_at', updated: false}} - // by default property names: createdAt, updatedAt -} - /** - * Define single property named `prop` on `model` + * Define single property named `propertyName` on `model` * * @param {String} model - name of model - * @param {String} prop - name of property - * @param {Object} params - property settings + * @param {String} propertyName - name of property + * @param {Object} propertyDefinition - property settings */ -ModelBuilder.prototype.defineProperty = function (model, prop, params) { - this.definitions[model].properties[prop] = params; - this.models[model].registerProperty(prop); +ModelBuilder.prototype.defineProperty = function (model, propertyName, propertyDefinition) { + this.definitions[model].defineProperty(propertyName, propertyDefinition); + this.models[model].registerProperty(propertyName); }; /** @@ -340,11 +370,11 @@ ModelBuilder.prototype.defineProperty = function (model, prop, params) { */ ModelBuilder.prototype.extendModel = function (model, props) { var t = this; - standartize(props, {}); Object.keys(props).forEach(function (propName) { var definition = props[propName]; t.defineProperty(model, propName, definition); }); + t.definitions[model].build(true); }; @@ -391,106 +421,21 @@ function hiddenProperty(where, property, value) { }); } -/*! - * Define readonly property on object - * - * @param {Object} obj - * @param {String} key - * @param {Mixed} value - */ -function defineReadonlyProp(obj, key, value) { - Object.defineProperty(obj, key, { - writable: false, - enumerable: true, - configurable: true, - value: value - }); -} - /** - * Resolve the type string to be a function, for example, 'String' to String - * @param {String} type The type string, such as 'number', 'Number', 'boolean', or 'String'. It's case insensitive - * @returns {Function} if the type is resolved + * Get the schema name */ -ModelBuilder.prototype.getSchemaType = function(type) { - if (!type) { - return type; +ModelBuilder.prototype.getSchemaName = function (name) { + if (name) { + return name; } - if (Array.isArray(type) && type.length > 0) { - // For array types, the first item should be the type string - var itemType = this.getSchemaType(type[0]); - if (typeof itemType === 'function') { - return [itemType]; - } - else return itemType; // Not resolved, return the type string + if (typeof this._nameCount !== 'number') { + this._nameCount = 0; + } else { + this._nameCount++; } - if (typeof type === 'string') { - var schemaType = ModelBuilder.schemaTypes[type.toLowerCase()]; - if (schemaType) { - return schemaType; - } else { - return type; - } - } else if (type.constructor.name == 'Object') { - // We also support the syntax {type: 'string', ...} - if (type.type) { - return this.getSchemaType(type.type); - } else { - if(!this.anonymousTypesCount) { - this.anonymousTypesCount = 0; - } - this.anonymousTypesCount++; - return this.define('AnonymousType' + this.anonymousTypesCount, type, {idInjection: false}); - /* - console.error(type); - throw new Error('Missing type property'); - */ - } - } else if('function' === typeof type ) { - return type; - } - return type; + return 'AnonymousModel_' + this._nameCount; }; -/** - * Build a dataSource - * @param {String} name The name of the dataSource - * @param {Object} properties The properties of the dataSource - * @param {Object[]} associations An array of associations between models - * @returns {*} - */ -ModelBuilder.prototype.buildSchema = function(name, properties, associations) { - for (var p in properties) { - // console.log(name + "." + p + ": " + properties[p]); - var type = this.getSchemaType(properties[p]); - if (typeof type === 'string') { - // console.log('Association: ' + type); - if (Array.isArray(associations)) { - associations.push({ - source: name, - target: type, - relation: Array.isArray(properties[p]) ? 'hasMany' : 'belongsTo', - as: p - }); - delete properties[p]; - } - } else { - var typeDef = { - type: type - }; - for (var a in properties[p]) { - // Skip the type property but don't delete it Model.extend() shares same instances of the properties from the base class - if(a !== 'type') { - typeDef[a] = properties[p][a]; - } - } - properties[p] = typeDef; - } - } - return properties; -}; - - /** * Build models from dataSource definitions * @@ -506,27 +451,30 @@ ModelBuilder.prototype.buildSchema = function(name, properties, associations) { ModelBuilder.prototype.buildModels = function (schemas) { var models = {}; - if (Array.isArray(schemas)) { - // An array already - } else if (schemas.properties && schemas.name) { - // Only one item - schemas = [schemas]; - } else { - // Anonymous dataSource - schemas = [ - { - name: 'Anonymous', - properties: schemas - } - ]; + // Normalize the schemas to be an array of the schema objects {name: , properties: {}, options: {}} + if (!Array.isArray(schemas)) { + if (schemas.properties && schemas.name) { + // Only one item + schemas = [schemas]; + } else { + // Anonymous dataSource + schemas = [ + { + name: this.getSchemaName(), + properties: schemas, + options: {anonymous: true} + } + ]; + } } var associations = []; for (var s in schemas) { - var name = schemas[s].name; - var dataSource = this.buildSchema(name, schemas[s].properties, associations); - var model = this.define(name, dataSource, schemas[s].options); + var name = this.getSchemaName(schemas[s].name); + schemas[s].name = name; + var model = this.define(schemas[s].name, schemas[s].properties, schemas[s].options); models[name] = model; + associations = associations.concat(model.definition.associations); } // Connect the models based on the associations diff --git a/lib/model-definition.js b/lib/model-definition.js new file mode 100644 index 00000000..3ec785b1 --- /dev/null +++ b/lib/model-definition.js @@ -0,0 +1,356 @@ +var assert = require('assert'); +var util = require('util'); +var EventEmitter = require('events').EventEmitter; +var traverse = require('traverse'); +var ModelBaseClass = require('./model'); +var ModelBuilder = require('./model-builder'); + +/** + * Model definition + */ +module.exports = ModelDefinition; + +/** + * Constructor for ModelDefinition + * @param {ModelBuilder} modelBuilder A model builder instance + * @param {String|Object} name The model name or the schema object + * @param {Object} properties The model properties, optional + * @param {Object} settings The model settings, optional + * @returns {ModelDefinition} + * @constructor + * + */ +function ModelDefinition(modelBuilder, name, properties, settings) { + if (!(this instanceof ModelDefinition)) { + // Allow to call ModelDefinition without new + return new ModelDefinition(modelBuilder, name, properties, settings); + } + this.modelBuilder = modelBuilder || ModelBuilder.defaultInstance; + assert(name, 'name is missing'); + + if (arguments.length === 2 && typeof name === 'object') { + var schema = name; + this.name = schema.name; + this.rawProperties = schema.properties || {}; // Keep the raw property definitions + this.settings = schema.settings || {}; + } else { + assert(typeof name === 'string', 'name must be a string'); + this.name = name; + this.rawProperties = properties || {}; // Keep the raw property definitions + this.settings = settings || {}; + } + this.associations = []; + this.properties = null; +} + +util.inherits(ModelDefinition, EventEmitter); + +// Set up types +require('./types')(ModelDefinition); + + +/** + * Return table name for specified `modelName` + * @param {String} connectorType The connector type, such as 'oracle' or 'mongodb' + */ +ModelDefinition.prototype.tableName = function (connectorType) { + var settings = this.settings; + if(settings[connectorType]) { + return settings[connectorType].table || this.name; + } else { + return this.name; + } +}; + +/** + * Return column name for specified modelName and propertyName + * @param {String} connectorType The connector type, such as 'oracle' or 'mongodb' + * @param propertyName The property name + * @returns {String} columnName + */ +ModelDefinition.prototype.columnName = function (connectorType, propertyName) { + if(!propertyName) { + return propertyName; + } + this.build(); + var property = this.properties[propertyName]; + if(property && property[connectorType]) { + return property[connectorType].columnName || propertyName; + } else { + return propertyName; + } +}; + +/** + * Return column metadata for specified modelName and propertyName + * @param {String} connectorType The connector type, such as 'oracle' or 'mongodb' + * @param propertyName The property name + * @returns {Object} column metadata + */ +ModelDefinition.prototype.columnMetadata = function (connectorType, propertyName) { + if(!propertyName) { + return propertyName; + } + this.build(); + var property = this.properties[propertyName]; + if(property && property[connectorType]) { + return property[connectorType]; + } else { + return null; + } +}; + +/** + * Return column names for specified modelName + * @param {String} connectorType The connector type, such as 'oracle' or 'mongodb' + * @returns {String[]} column names + */ +ModelDefinition.prototype.columnNames = function (connectorType) { + this.build(); + var props = this.properties; + var cols = []; + for(var p in props) { + if(props[p][connectorType]) { + cols.push(props[p][connectorType].columnName || p); + } else { + cols.push(p); + } + } + return cols; +}; + +/** + * Find the ID properties sorted by the index + * @returns {Object[]} property name/index for IDs + */ +ModelDefinition.prototype.ids = function () { + if(this._ids) { + return this._ids; + } + var ids = []; + this.build(); + var props = this.properties; + for (var key in props) { + var id = props[key].id; + if(!id) { + continue; + } + if(typeof id !== 'number') { + id = 1; + } + ids.push({name: key, id: id}); + } + ids.sort(function (a, b) { + return a.key - b.key; + }); + this._ids = ids; + return ids; +}; + +/** + * Find the ID column name + * @param {String} modelName The model name + * @returns {String} columnName for ID + */ +ModelDefinition.prototype.idColumnName = function(connectorType) { + return this.columnName(connectorType, this.idName()); +}; + +/** + * Find the ID property name + * @returns {String} property name for ID + */ +ModelDefinition.prototype.idName = function() { + var id = this.ids()[0]; + if(this.properties.id && this.properties.id.id) { + return 'id'; + } else {} + return id && id.name; +}; + +/** + * Find the ID property names sorted by the index + * @returns {String[]} property names for IDs + */ +ModelDefinition.prototype.idNames = function () { + var ids = this.ids(); + var names = ids.map(function (id) { + return id.name; + }); + return names; +}; + +/** + * + * @returns {{}} + */ +ModelDefinition.prototype.indexes = function () { + this.build(); + var indexes = {}; + if (this.settings.indexes) { + for (var i in this.settings.indexes) { + indexes[i] = this.settings.indexes[i]; + } + } + for (var p in this.properties) { + if (this.properties[p].index) { + indexes[p + '_index'] = this.properties[p].index; + } + } + return indexes; +}; + +/** + * Resolve the type string to be a function, for example, 'String' to String + * @param {String} type The type string, such as 'number', 'Number', 'boolean', or 'String'. It's case insensitive + * @returns {Function} if the type is resolved + */ +ModelDefinition.prototype.resolveType = function(type) { + if (!type) { + return type; + } + if (Array.isArray(type) && type.length > 0) { + // For array types, the first item should be the type string + var itemType = this.resolveType(type[0]); + if (typeof itemType === 'function') { + return [itemType]; + } + else { + return itemType; // Not resolved, return the type string + } + } + if (typeof type === 'string') { + var schemaType = ModelDefinition.schemaTypes[type.toLowerCase()]; + if (schemaType) { + return schemaType; + } else { + return type; + } + } else if (type.constructor.name === 'Object') { + // We also support the syntax {type: 'string', ...} + if (type.type) { + return this.resolveType(type.type); + } else { + if(!this.anonymousTypesCount) { + this.anonymousTypesCount = 0; + } + this.anonymousTypesCount++; + return this.modelBuilder.define('AnonymousType' + this.anonymousTypesCount, + type, {anonymous: true, idInjection: false}); + /* + console.error(type); + throw new Error('Missing type property'); + */ + } + } else if('function' === typeof type ) { + return type; + } + return type; +}; + +/** + * Build a model definition + * @param {Boolean} force Forcing rebuild + */ +ModelDefinition.prototype.build = function (forceRebuild) { + if(forceRebuild) { + this.properties = null; + this.associations = []; + this._ids = null; + } + if (this.properties) { + return this.properties; + } + this.properties = {}; + for (var p in this.rawProperties) { + var type = this.resolveType(this.rawProperties[p]); + if (typeof type === 'string') { + if (Array.isArray(this.associations)) { + this.associations.push({ + source: this.name, + target: type, + relation: Array.isArray(this.rawProperties[p]) ? 'hasMany' : 'belongsTo', + as: p + }); + // delete this.rawProperties[p]; + } + } else { + var typeDef = { + type: type + }; + for (var a in this.rawProperties[p]) { + // Skip the type property but don't delete it Model.extend() shares same instances of the properties from the base class + if (a !== 'type') { + typeDef[a] = this.rawProperties[p][a]; + } + } + this.properties[p] = typeDef; + } + } + return this.properties; +}; + +/** + * Define a property + * @param {String} propertyName The property name + * @param {Object} propertyDefinition The property definition + */ +ModelDefinition.prototype.defineProperty = function (propertyName, propertyDefinition) { + this.rawProperties[propertyName] = propertyDefinition; + this.build(true); +}; + + +function isModelClass(cls) { + while (true) { + if (!cls) { + return false; + } + if (ModelBaseClass === cls) { + return true; + } + cls = cls.prototype; + } +} + +ModelDefinition.prototype.toJSON = function(forceRebuild) { + if(forceRebuild) { + this.json = null; + } + if(this.json) { + return json; + } + var json = { + name: this.name, + properties: {}, + settings: this.settings + }; + this.build(forceRebuild); + + var mapper = function(val) { + if(val === undefined || val === null) { + return val; + } + if('function' === typeof val.toJSON) { + // The value has its own toJSON() object + return val.toJSON(); + } + if('function' === typeof val) { + if(isModelClass(val)) { + if(val.settings && val.settings.anonymous) { + return val.definition && val.definition.toJSON(); + } else { + return val.modelName; + } + } + return val.name; + } else { + return val; + } + }; + for(var p in this.properties) { + json.properties[p] = traverse(this.properties[p]).map(mapper); + } + this.json = json; + return json; +}; diff --git a/lib/model.js b/lib/model.js index 2e69d3e0..766f7d45 100644 --- a/lib/model.js +++ b/lib/model.js @@ -52,7 +52,7 @@ ModelBaseClass.prototype._initProperties = function (data, applySetters) { var self = this; var ctor = this.constructor; - var properties = ctor.properties; + var properties = ctor.definition.build(); data = data || {}; Object.defineProperty(this, '__cachedRelations', { @@ -81,7 +81,7 @@ ModelBaseClass.prototype._initProperties = function (data, applySetters) { } // Check if the strict option is set to false for the model - var strict = ctor.settings.strict; + var strict = ctor.definition.settings.strict; for (var i in data) { if (i in properties) { @@ -99,56 +99,56 @@ ModelBaseClass.prototype._initProperties = function (data, applySetters) { } if (applySetters === true) { - Object.keys(data).forEach(function (attr) { - if((attr in properties) || (attr in ctor.relations)) { - self[attr] = self.__data[attr] || data[attr]; + Object.keys(data).forEach(function (propertyName) { + if((propertyName in properties) || (propertyName in ctor.relations)) { + self[propertyName] = self.__data[propertyName] || data[propertyName]; } }); } // Set the unknown properties as properties to the object if(strict === false) { - Object.keys(data).forEach(function (attr) { - if(!(attr in properties)) { - self[attr] = self.__data[attr] || data[attr]; + Object.keys(data).forEach(function (propertyName) { + if(!(propertyName in properties)) { + self[propertyName] = self.__data[propertyName] || data[propertyName]; } }); } - ctor.forEachProperty(function (attr) { + ctor.forEachProperty(function (propertyName) { - if ('undefined' === typeof self.__data[attr]) { - self.__data[attr] = self.__dataWas[attr] = getDefault(attr); + if ('undefined' === typeof self.__data[propertyName]) { + self.__data[propertyName] = self.__dataWas[propertyName] = getDefault(propertyName); } else { - self.__dataWas[attr] = self.__data[attr]; + self.__dataWas[propertyName] = self.__data[propertyName]; } }); - ctor.forEachProperty(function (attr) { + ctor.forEachProperty(function (propertyName) { - var type = properties[attr].type; + var type = properties[propertyName].type; if (BASE_TYPES.indexOf(type.name) === -1) { - if (typeof self.__data[attr] !== 'object' && self.__data[attr]) { + if (typeof self.__data[propertyName] !== 'object' && self.__data[propertyName]) { try { - self.__data[attr] = JSON.parse(self.__data[attr] + ''); + self.__data[propertyName] = JSON.parse(self.__data[propertyName] + ''); } catch (e) { - self.__data[attr] = String(self.__data[attr]); + self.__data[propertyName] = String(self.__data[propertyName]); } } if (type.name === 'Array' || Array.isArray(type)) { - if(!(self.__data[attr] instanceof List)) { - self.__data[attr] = new List(self.__data[attr], type, self); + if(!(self.__data[propertyName] instanceof List)) { + self.__data[propertyName] = new List(self.__data[propertyName], type, self); } } } }); - function getDefault(attr) { - var def = properties[attr]['default']; - if (isdef(def)) { + function getDefault(propertyName) { + var def = properties[propertyName]['default']; + if (def !== undefined) { if (typeof def === 'function') { return def(); } else { @@ -170,8 +170,8 @@ ModelBaseClass.defineProperty = function (prop, params) { this.dataSource.defineProperty(this.modelName, prop, params); }; -ModelBaseClass.whatTypeName = function (propName) { - var prop = this.properties[propName]; +ModelBaseClass.getPropertyType = function (propName) { + var prop = this.definition.properties[propName]; if(!prop) { // The property is not part of the definition return null; @@ -183,8 +183,8 @@ ModelBaseClass.whatTypeName = function (propName) { return prop.type.name; }; -ModelBaseClass.prototype.whatTypeName = function (propName) { - return this.constructor.whatTypeName(propName); +ModelBaseClass.prototype.getPropertyType = function (propName) { + return this.constructor.getPropertyType(propName); }; /** @@ -208,29 +208,29 @@ ModelBaseClass.prototype.toObject = function (onlySchema) { var data = {}; var self = this; - var schemaLess = this.constructor.settings.strict === false || !onlySchema; - this.constructor.forEachProperty(function (attr) { - if (self[attr] instanceof List) { - data[attr] = self[attr].toObject(!schemaLess); - } else if (self.__data.hasOwnProperty(attr)) { - if(self[attr] !== undefined && self[attr]!== null && self[attr].toObject) { - data[attr] = self[attr].toObject(!schemaLess); + var schemaLess = this.constructor.definition.settings.strict === false || !onlySchema; + this.constructor.forEachProperty(function (propertyName) { + if (self[propertyName] instanceof List) { + data[propertyName] = self[propertyName].toObject(!schemaLess); + } else if (self.__data.hasOwnProperty(propertyName)) { + if(self[propertyName] !== undefined && self[propertyName]!== null && self[propertyName].toObject) { + data[propertyName] = self[propertyName].toObject(!schemaLess); } else { - data[attr] = self[attr]; + data[propertyName] = self[propertyName]; } } else { - data[attr] = null; + data[propertyName] = null; } }); if (schemaLess) { - Object.keys(self.__data).forEach(function (attr) { - if (!data.hasOwnProperty(attr)) { - var val = self.hasOwnProperty(attr) ? self[attr] : self.__data[attr]; + Object.keys(self.__data).forEach(function (propertyName) { + if (!data.hasOwnProperty(propertyName)) { + var val = self.hasOwnProperty(propertyName) ? self[propertyName] : self.__data[propertyName]; if(val !== undefined && val!== null && val.toObject) { - data[attr] = val.toObject(!schemaLess); + data[propertyName] = val.toObject(!schemaLess); } else { - data[attr] = val; + data[propertyName] = val; } } }); @@ -256,11 +256,11 @@ ModelBaseClass.prototype.fromObject = function (obj) { /** * Checks is property changed based on current property and initial value * - * @param {String} attr - property name + * @param {String} propertyName - property name * @return Boolean */ -ModelBaseClass.prototype.propertyChanged = function propertyChanged(attr) { - return this.__data[attr] !== this.__dataWas[attr]; +ModelBaseClass.prototype.propertyChanged = function propertyChanged(propertyName) { + return this.__data[propertyName] !== this.__dataWas[propertyName]; }; /** @@ -276,7 +276,7 @@ ModelBaseClass.prototype.reset = function () { delete obj[k]; } if (obj.propertyChanged(k)) { - obj[k] = obj[k + '_was']; + obj[k] = obj[k + '$was']; } }); }; @@ -285,19 +285,9 @@ ModelBaseClass.prototype.inspect = function () { return util.inspect(this.__data, false, 4, true); }; -/** - * Check whether `s` is not undefined - * @param {Mixed} s - * @return {Boolean} s is undefined - */ -function isdef(s) { - var undef; - return s !== undef; -} - ModelBaseClass.mixin = function(anotherClass, options) { return jutil.mixin(this, anotherClass, options); -} +}; jutil.mixin(ModelBaseClass, Hookable); -jutil.mixin(ModelBaseClass, validations.Validatable); \ No newline at end of file +jutil.mixin(ModelBaseClass, validations.Validatable); diff --git a/lib/scope.js b/lib/scope.js index ddefdedd..50d4b481 100644 --- a/lib/scope.js +++ b/lib/scope.js @@ -3,19 +3,6 @@ */ exports.defineScope = defineScope; -/** - * Scope mixin for ./model.js - */ -var DataAccessObject = require('./dao.js'); - -/** - * Define scope - * TODO: describe behavior and usage examples - */ -DataAccessObject.scope = function (name, params) { - defineScope(this, this, name, params); -}; - function defineScope(cls, targetClass, name, params, methods) { // collect meta info about scope diff --git a/lib/sql.js b/lib/sql.js index a4d32dd1..281212c5 100644 --- a/lib/sql.js +++ b/lib/sql.js @@ -1,3 +1,6 @@ +var util = require('util'); +var Connector = require('./connector'); + module.exports = BaseSQL; /** @@ -5,8 +8,11 @@ module.exports = BaseSQL; * @constructor */ function BaseSQL() { + Connector.apply(this, [].slice.call(arguments)); } +util.inherits(BaseSQL, Connector); + /** * Set the relational property to indicate the backend is a relational DB * @type {boolean} @@ -28,18 +34,6 @@ BaseSQL.prototype.queryOne = function (sql, callback) { }); }; -/** - * Look up the data source by model name - * @param {String} model The model name - * @returns {DataSource} The data source - */ -BaseSQL.prototype.getDataSource = function(model) { - var m = this._models[model]; - if(!m) { - console.trace('Model not found: ' + model); - } - return m.model.dataSource; -} /** * Get the table name for a given model @@ -96,24 +90,6 @@ BaseSQL.prototype.propertyName = function (model, column) { return null; }; -/** - * Get the id property name - * @param {String} model The model name - * @returns {String} The id property name - */ -BaseSQL.prototype.idName = function (model) { - return this.getDataSource(model).idName(model); -}; - -/** - * Get the id property names - * @param {String} model The model name - * @returns {[String]} The id property names - */ -BaseSQL.prototype.idNames = function (model) { - return this.getDataSource(model).idNames(model); -}; - /** * Get the id column name * @param {String} model The model name @@ -137,20 +113,6 @@ BaseSQL.prototype.idColumnEscaped = function (model) { return this.escapeName(this.getDataSource(model).idColumnName(model)); }; -/** - * Get the id index (sequence number, starting from 1) - * @param {String} model The model name - * @param {String} prop The property name - * @returns {Number} The id index, undefined if the property is not part of the primary key - */ -BaseSQL.prototype.id = function (model, prop) { - var p = this._models[model].properties[prop]; - if(!p) { - console.trace('Property not found: ' + model +'.' + prop); - } - return p.id; -}; - /** * Escape the name for the underlying database * @param {String} name The name @@ -178,25 +140,6 @@ BaseSQL.prototype.columnEscaped = function (model, property) { return this.escapeName(this.column(model, property)); }; -/** - * Hook to be called by DataSource for defining a model - * @param {Object} descr The description of a model - */ -BaseSQL.prototype.define = function (descr) { - if (!descr.settings) descr.settings = {}; - this._models[descr.model.modelName] = descr; -}; - -/** - * Hook to be called by DataSource for defining a model property - * @param {String} model The model name - * @param {String} prop The property name - * @param {Object} params The object for property metadata - */ -BaseSQL.prototype.defineProperty = function (model, prop, params) { - this._models[model].properties[prop] = params; -}; - /** * Save the model instance into the backend store * @param {String} model The model name diff --git a/test/common_test.js b/test/common_test.js index 6087743c..35d1ec72 100644 --- a/test/common_test.js +++ b/test/common_test.js @@ -579,11 +579,11 @@ function testOrm(dataSource) { }); it('should return type of property', function (test) { - test.equal(Post.whatTypeName('title'), 'String'); - test.equal(Post.whatTypeName('content'), 'Text'); + test.equal(Post.getPropertyType('title'), 'String'); + test.equal(Post.getPropertyType('content'), 'Text'); var p = new Post; - test.equal(p.whatTypeName('title'), 'String'); - test.equal(p.whatTypeName('content'), 'Text'); + test.equal(p.getPropertyType('title'), 'String'); + test.equal(p.getPropertyType('content'), 'Text'); test.done(); }); diff --git a/test/loopback-dl.test.js b/test/loopback-dl.test.js index 9dba1254..e095a0cb 100644 --- a/test/loopback-dl.test.js +++ b/test/loopback-dl.test.js @@ -413,10 +413,10 @@ describe('Load models from json', function () { var models = loadSchemasSync(path.join(__dirname, 'test1-schemas.json')); - models.should.have.property('Anonymous'); - models.Anonymous.should.have.property('modelName', 'Anonymous'); + models.should.have.property('AnonymousModel_0'); + models.AnonymousModel_0.should.have.property('modelName', 'AnonymousModel_0'); - var m1 = new models.Anonymous({title: 'Test'}); + var m1 = new models.AnonymousModel_0({title: 'Test'}); m1.should.have.property('title', 'Test'); m1.should.have.property('author', 'Raymond'); diff --git a/test/manipulation.test.js b/test/manipulation.test.js index 260b0d74..0e9563ae 100644 --- a/test/manipulation.test.js +++ b/test/manipulation.test.js @@ -241,7 +241,7 @@ describe('manipulation', function() { person.name.should.equal(hw); person.propertyChanged('name').should.be.false; person.name = 'Goodbye, Lenin'; - person.name_was.should.equal(hw); + person.name$was.should.equal(hw); person.propertyChanged('name').should.be.true; (person.createdAt >= now).should.be.true; person.isNewRecord().should.be.true; diff --git a/test/model-definition.test.js b/test/model-definition.test.js new file mode 100644 index 00000000..e907f1d9 --- /dev/null +++ b/test/model-definition.test.js @@ -0,0 +1,83 @@ +// This test written in mocha+should.js +var should = require('./init.js'); +var assert = require('assert'); + +var jdb = require('../'); +var ModelBuilder = jdb.ModelBuilder; +var DataSource = jdb.DataSource; + +var ModelDefinition = require('../lib/model-definition'); + +describe('ModelDefinition class', function () { + + it('should be able to define plain models', function (done) { + var modelBuilder = new ModelBuilder(); + + var User = new ModelDefinition(modelBuilder, 'User', { + name: String, + bio: ModelBuilder.Text, + approved: Boolean, + joinedAt: Date, + age: Number + }); + + // console.log(User.toJSON()); + + done(); + + + }); + + + it('should be able to define nesting models', function (done) { + var modelBuilder = new ModelBuilder(); + + var User = new ModelDefinition(modelBuilder, 'User', { + name: String, + bio: ModelBuilder.Text, + approved: Boolean, + joinedAt: Date, + age: Number, + address: { + street: String, + city: String, + zipCode: String, + state: String + } + }); + + // console.log(JSON.stringify(User.toJSON(), null, ' ')); + + done(); + + + }); + + + it('should be able to define referencing models', function (done) { + var modelBuilder = new ModelBuilder(); + + var Address = modelBuilder.define('Address', { + street: String, + city: String, + zipCode: String, + state: String + }); + var User = new ModelDefinition(modelBuilder, 'User', { + name: String, + bio: ModelBuilder.Text, + approved: Boolean, + joinedAt: Date, + age: Number, + address: Address + + }); + + // console.log(JSON.stringify(User.toJSON(), null, ' ')); + + done(); + + + }); +}); +