2013-04-10 17:55:13 +00:00
|
|
|
/**
|
|
|
|
* Expose `Model`.
|
|
|
|
*/
|
|
|
|
|
|
|
|
module.exports = Model;
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Module dependencies.
|
|
|
|
*/
|
|
|
|
|
|
|
|
var AsteroidModule = require('asteroid-module')
|
|
|
|
, 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(options) {
|
|
|
|
AsteroidModule.apply(this, arguments);
|
|
|
|
|
|
|
|
// throw an error if args are not supplied
|
|
|
|
// assert(typeof options === 'object', 'Model requires an options object');
|
|
|
|
|
|
|
|
this.options = options;
|
|
|
|
|
|
|
|
debug('created with options', options);
|
|
|
|
|
|
|
|
var dependencies = this.dependencies;
|
2013-04-18 00:43:00 +00:00
|
|
|
var dataSource = dependencies['data-source'];
|
|
|
|
var schema = this.schema = dataSource.schema;
|
2013-04-10 17:55:13 +00:00
|
|
|
|
|
|
|
assert(Array.isArray(options.properties), 'the ' + options._name + ' model requires an options.properties array');
|
|
|
|
|
|
|
|
// define schema
|
|
|
|
this.schema = schema.define(options.namespace || options._name, this.buildSchemaDefinition(options.properties));
|
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Inherit from `AsteroidModule`.
|
|
|
|
*/
|
|
|
|
|
|
|
|
inherits(Model, AsteroidModule);
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Dependencies.
|
|
|
|
*/
|
|
|
|
|
|
|
|
Model.dependencies = {
|
2013-04-18 00:43:00 +00:00
|
|
|
'data-source': 'data-source'
|
2013-04-10 17:55:13 +00:00
|
|
|
};
|
|
|
|
|
2013-04-19 16:51:06 +00:00
|
|
|
/**
|
|
|
|
* Options.
|
|
|
|
*/
|
|
|
|
|
|
|
|
Model.options = {
|
|
|
|
'name': {type: 'string'},
|
|
|
|
'properties': {type: 'array'}
|
|
|
|
}
|
|
|
|
|
2013-04-10 17:55:13 +00:00
|
|
|
/**
|
|
|
|
* Build a jugglingdb compatibile schema definition from property array.
|
|
|
|
*/
|
|
|
|
|
|
|
|
Model.prototype.buildSchemaDefinition = function (properties) {
|
|
|
|
return properties.reduce(function (prev, cur) {
|
|
|
|
prev[cur.name] = types[cur.type];
|
|
|
|
return prev;
|
|
|
|
}, {});
|
|
|
|
}
|
|
|
|
|
|
|
|
var types = [String, Number, Date, Array, Boolean].reduce(function (prev, cur) {
|
|
|
|
prev[cur.name.toLowerCase()] = cur
|
|
|
|
return prev;
|
|
|
|
}, {});
|