loopback/node_modules/model/lib/model.js

82 lines
1.7 KiB
JavaScript

/**
* 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;
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 schema
this.schema = schema.define(options.namespace || options._name, this.buildSchemaDefinition(options.properties));
}
/**
* Inherit from `AsteroidModule`.
*/
inherits(Model, AsteroidModule);
/**
* Dependencies.
*/
Model.dependencies = {
'data-source': 'data-source'
};
/**
* Options.
*/
Model.options = {
'name': {type: 'string'},
'properties': {type: 'array'}
}
/**
* 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;
}, {});