loopback/node_modules/model/lib/model-configuration.js

80 lines
1.8 KiB
JavaScript
Raw Normal View History

2013-05-01 19:11:43 +00:00
/**
* Expose `ModelConfiguration`.
*/
module.exports = ModelConfiguration;
/**
* Module dependencies.
*/
var AsteroidModule = require('asteroid-module')
, Model = require('asteroid/lib/model')
, debug = require('debug')('model-configuration')
, util = require('util')
, inherits = util.inherits
, assert = require('assert');
/**
* Create a new `ModelConfiguration` with the given `options`.
*
* @param {Object} options
* @return {Model}
*/
function ModelConfiguration(options) {
AsteroidModule.apply(this, arguments);
this.options = options;
var dependencies = this.dependencies;
var dataSource = dependencies['data-source'];
var schema = this.schema = dataSource.schema;
assert(Array.isArray(options.properties), 'the ' + options._name + ' model requires an options.properties array');
// define model
var ModelCtor = this.ModelCtor = this.BaseModel.extend(options);
assert(dataSource.name, 'cannot map a model to a datasource without a name');
// define provided mappings
if(options.maps) {
options.maps.forEach(function (config) {
assert(config.dataSource, 'Model config.options.maps requires a `dataSource` when defining maps');
assert(config.map, 'Model config.options.maps requires a `map` when defining maps');
ModelCtor.defineMap(dataSource.name, config);
});
}
}
/**
* Inherit from `AsteroidModule`.
*/
inherits(ModelConfiguration, AsteroidModule);
/**
* The model to extend (should be overridden in sub classes).
*/
ModelConfiguration.prototype.BaseModel = Model;
/**
* Dependencies.
*/
ModelConfiguration.dependencies = {
'data-source': 'data-source'
};
/**
* Options.
*/
ModelConfiguration.options = {
'name': {type: 'string'},
'properties': {type: 'array'},
'maps': {type: 'array'}
}