loopback/node_modules/model/lib/model.js

121 lines
2.6 KiB
JavaScript

/**
* Expose `Model`.
*/
module.exports = Model;
/**
* Module dependencies.
*/
var EventEmitter = require('events').EventEmitter
, debug = require('debug')('model')
, util = require('util')
, inherits = util.inherits
, assert = require('assert');
/**
* Create a new `Model` with the given `options`.
*
* @param {Object} options
* @return {Model}
*/
function Model(data) {
EventEmitter.call(this);
var ModelCtor = this.constructor;
var schema = ModelCtor.schema;
// get properties that match the schema
var matchedProperties = schema.getMatchedProperties(data);
// set properties that match the schema
Object.keys(matchedProperties).forEach(function (property) {
this[property] = matchedProperties[property];
}.bind(this));
}
/**
* Inherit from `EventEmitter`.
*/
inherits(Model, EventEmitter);
/**
* Create a new Model class from the given options.
*
* @param options {Object}
* @return {Model}
*/
Model.extend = function (options) {
var Super = this;
// the new constructor
function Model() {
Super.apply(this, arguments);
}
Model.options = options;
assert(options.name, 'must provide a name when extending from model');
// model namespace
Model.namespace = options.name;
// define the remote namespace
Model.remoteNamespace = options.plural || pluralize(Model.namespace);
// inherit all static methods
Object.keys(Super).forEach(function (key) {
if(typeof Super[key] === 'function') {
MyModel[key] = Super[key];
}
});
// inherit all other things
inherits(MyModel, Super);
return Model;
}
/**
* Construct a model instance for remote use.
*/
Model.sharedCtor = function (data, fn) {
var ModelCtor = this;
fn(null, new ModelCtor(data));
}
/**
* Define the data the model represents using the data definition language.
*/
Model.defineSchema = function (schema) {
throw new Error('not implemented');
}
/**
* Set the data source for the model. Must provide a name of an existing data source.
* If the namespace is not provided the plural model name (eg. colors) will be used.
*
* **Note:** If you do not set a data source or a map (or both) the default data source
* will be used (an in memory database).
*/
Model.dataSource = function (dataSourceName, namespace) {
namespace = namespace || this.namespace;
throw new Error('not implemented');
}
/**
* Define a mapping between the data source representation of your data and your app's representation.
*/
Model.defineMap = function (mapping) {
// see: https://github.com/strongloop/asteroid/tree/master/node_modules/model#mymodeldefinemapmap
throw new Error('not implemented');
}