loopback-datasource-juggler/lib/model-builder.js

564 lines
17 KiB
JavaScript
Raw Normal View History

2013-08-13 16:37:09 +00:00
/*!
2013-05-17 17:54:14 +00:00
* Module dependencies
*/
var i8n = require('inflection');
2013-08-09 22:16:32 +00:00
var DefaultModelBaseClass = require('./model.js');
2013-05-17 17:54:14 +00:00
var List = require('./list.js');
var EventEmitter = require('events').EventEmitter;
var util = require('util');
2013-08-07 21:51:32 +00:00
// Set up types
require('./types')(ModelBuilder);
var introspect = require('./introspection')(ModelBuilder);
2013-05-17 17:54:14 +00:00
/**
* Export public API
*/
2013-08-13 16:37:09 +00:00
exports.ModelBuilder = exports.Schema = ModelBuilder;
2013-08-13 16:37:09 +00:00
/*!
2013-05-17 17:54:14 +00:00
* Helpers
*/
var slice = Array.prototype.slice;
/**
2013-08-13 16:37:09 +00:00
* ModelBuilder - A builder to define data models
*
* @constructor
2013-05-17 17:54:14 +00:00
*/
2013-05-24 05:20:20 +00:00
function ModelBuilder() {
2013-05-17 17:54:14 +00:00
// create blank models pool
2013-08-13 16:37:09 +00:00
/**
* @property {Object} models Model constructors
*/
2013-05-17 17:54:14 +00:00
this.models = {};
2013-08-13 16:37:09 +00:00
/**
* @property {Object} definitions Definitions of the models
*/
2013-05-17 17:54:14 +00:00
this.definitions = {};
2013-08-09 22:16:32 +00:00
}
2013-05-17 17:54:14 +00:00
2013-05-24 05:20:20 +00:00
util.inherits(ModelBuilder, EventEmitter);
2013-05-17 17:54:14 +00:00
/**
2013-08-13 16:37:09 +00:00
* Define a model class
2013-05-17 17:54:14 +00:00
*
* @param {String} className
* @param {Object} properties - hash of class properties in format
* `{property: Type, property2: Type2, ...}`
* or
* `{property: {type: Type}, property2: {type: Type2}, ...}`
* @param {Object} settings - other configuration of class
* @return newly created class
*
* @example simple case
* ```
* var User = dataSource.define('User', {
2013-05-17 17:54:14 +00:00
* email: String,
* password: String,
* birthDate: Date,
* activated: Boolean
* });
* ```
* @example more advanced case
* ```
* var User = dataSource.define('User', {
2013-05-17 17:54:14 +00:00
* email: { type: String, limit: 150, index: true },
* password: { type: String, limit: 50 },
* birthDate: Date,
* registrationDate: {type: Date, default: function () { return new Date }},
* activated: { type: Boolean, default: false }
* });
* ```
*/
2013-07-01 23:49:43 +00:00
ModelBuilder.prototype.define = function defineClass(className, properties, settings, parent) {
var dataSource = this;
2013-05-17 17:54:14 +00:00
var args = slice.call(arguments);
2013-05-31 17:27:52 +00:00
var pluralName = settings && settings.plural;
2013-08-09 22:16:32 +00:00
var ModelBaseClass = parent || DefaultModelBaseClass;
2013-05-17 17:54:14 +00:00
2013-08-09 22:16:32 +00:00
if (!className) {
throw new Error('Class name required');
}
if (args.length === 1) {
properties = {};
args.push(properties);
}
if (args.length === 2) {
settings = {};
args.push(settings);
}
2013-05-17 17:54:14 +00:00
properties = properties || {};
settings = settings || {};
// Set the strict mode to be false by default
if(settings.strict === undefined || settings.strict === null) {
settings.strict = false;
}
2013-07-11 21:24:47 +00:00
this.buildSchema(className, properties);
2013-06-21 21:04:24 +00:00
2013-05-17 17:54:14 +00:00
// every class can receive hash of data as optional param
var ModelClass = function ModelConstructor(data, dataSource) {
2013-07-11 21:24:47 +00:00
if(!(this instanceof ModelConstructor)) {
return new ModelConstructor(data, dataSource);
2013-07-11 21:24:47 +00:00
}
2013-07-01 23:49:43 +00:00
ModelBaseClass.apply(this, arguments);
if(!this.dataSource) {
hiddenProperty(this, 'dataSource', dataSource || this.constructor.dataSource);
}
2013-05-17 17:54:14 +00:00
};
2013-07-02 21:59:24 +00:00
2013-07-16 01:22:49 +00:00
// mix in EventEmitter (dont inherit from)
2013-07-02 21:59:24 +00:00
var events = new EventEmitter();
ModelClass.on = events.on.bind(events);
ModelClass.once = events.once.bind(events);
ModelClass.emit = events.emit.bind(events);
2013-07-16 01:22:49 +00:00
ModelClass.setMaxListeners = events.setMaxListeners.bind(events);
2013-05-17 17:54:14 +00:00
hiddenProperty(ModelClass, 'dataSource', dataSource);
2013-07-23 19:16:12 +00:00
hiddenProperty(ModelClass, 'schema', dataSource); // For backward compatibility
2013-05-17 17:54:14 +00:00
hiddenProperty(ModelClass, 'modelName', className);
2013-05-31 17:27:52 +00:00
hiddenProperty(ModelClass, 'pluralModelName', pluralName || i8n.pluralize(className));
2013-05-17 17:54:14 +00:00
hiddenProperty(ModelClass, 'relations', {});
2013-07-16 01:22:49 +00:00
util.inherits(ModelClass, ModelBaseClass);
2013-05-17 17:54:14 +00:00
2013-07-16 01:22:49 +00:00
// inherit ModelBaseClass static methods
2013-05-17 17:54:14 +00:00
for (var i in ModelBaseClass) {
ModelClass[i] = ModelBaseClass[i];
}
2013-07-15 17:44:34 +00:00
2013-05-17 17:54:14 +00:00
ModelClass.getter = {};
ModelClass.setter = {};
standartize(properties, settings);
// store class in model pool
this.models[className] = ModelClass;
this.definitions[className] = {
properties: properties,
settings: settings
};
// expose properties on the ModelClass
ModelClass.properties = properties;
ModelClass.settings = settings;
2013-05-17 17:54:14 +00:00
var idInjection = settings.idInjection;
2013-05-23 17:46:01 +00:00
if(idInjection !== false) {
idInjection = true;
}
for(var p in properties) {
if(properties[p].id) {
idInjection = false;
ModelClass.prototype.__defineGetter__('id', function () {
return this.__data[p];
});
break;
}
}
// Add the id property
2013-05-23 17:46:01 +00:00
if (idInjection) {
2013-07-28 20:17:12 +00:00
ModelClass.prototype.__defineGetter__('id', function () {
return this.__data.id;
});
// Set up the id property
2013-07-28 20:17:12 +00:00
properties.id = properties.id || { type: Number, id: 1, generated: true };
if (!properties.id.id) {
2013-05-23 17:46:01 +00:00
properties.id.id = 1;
}
}
2013-05-17 17:54:14 +00:00
ModelClass.forEachProperty = function (cb) {
Object.keys(properties).forEach(cb);
};
ModelClass.attachTo = function (dataSource) {
2013-06-21 21:15:24 +00:00
dataSource.attach(this);
2013-08-09 22:16:32 +00:00
};
2013-07-01 23:49:43 +00:00
ModelClass.extend = function (className, p, s) {
p = p || {};
s = s || {};
Object.keys(properties).forEach(function (key) {
// dont inherit the id property
if(key !== 'id' && typeof p[key] === 'undefined') {
p[key] = properties[key];
}
});
Object.keys(settings).forEach(function (key) {
if(typeof s[key] === 'undefined') {
s[key] = settings[key];
}
});
var c = dataSource.define(className, p, s, ModelClass);
if(typeof c.setup === 'function') {
c.setup.call(c);
}
return c;
2013-08-09 22:16:32 +00:00
};
2013-05-17 17:54:14 +00:00
ModelClass.registerProperty = function (attr) {
2013-07-28 20:17:12 +00:00
var prop = properties[attr];
var DataType = prop.type;
2013-05-17 17:54:14 +00:00
if(!DataType) {
2013-06-21 21:15:24 +00:00
throw new Error('Invalid type for property ' + attr);
2013-05-17 17:54:14 +00:00
}
if (Array.isArray(DataType) || DataType === Array) {
2013-05-17 17:54:14 +00:00
DataType = List;
} else if (DataType.name === 'Date') {
var OrigDate = Date;
DataType = function Date(arg) {
return new OrigDate(arg);
};
} else if(typeof DataType === 'string') {
DataType = dataSource.getSchemaType(DataType);
2013-05-17 17:54:14 +00:00
}
2013-07-28 20:17:12 +00:00
if(prop.required) {
var requiredOptions = typeof prop.required === 'object' ? prop.required : undefined;
ModelClass.validatesPresenceOf(attr, requiredOptions);
}
2013-05-17 17:54:14 +00:00
Object.defineProperty(ModelClass.prototype, attr, {
get: function () {
if (ModelClass.getter[attr]) {
return ModelClass.getter[attr].call(this);
} else {
2013-05-28 20:50:59 +00:00
return this.__data && this.__data[attr];
2013-05-17 17:54:14 +00:00
}
},
set: function (value) {
if (ModelClass.setter[attr]) {
ModelClass.setter[attr].call(this, value);
} else {
2013-05-28 20:50:59 +00:00
if (!this.__data) {
this.__data = {};
}
2013-05-17 17:54:14 +00:00
if (value === null || value === undefined) {
this.__data[attr] = value;
} else {
2013-07-12 19:36:14 +00:00
if(DataType === List) {
this.__data[attr] = DataType(value, properties[attr].type, this.__data);
} else {
2013-07-25 14:48:31 +00:00
// Assume the type constructor handles Constructor() call
// If not, we should call new DataType(value).valueOf();
2013-07-12 19:36:14 +00:00
this.__data[attr] = DataType(value);
}
2013-05-17 17:54:14 +00:00
}
}
},
configurable: true,
enumerable: true
});
ModelClass.prototype.__defineGetter__(attr + '_was', function () {
2013-05-28 20:50:59 +00:00
return this.__dataWas && this.__dataWas[attr];
2013-05-17 17:54:14 +00:00
});
// 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, {
2013-05-17 17:54:14 +00:00
get: function () {
2013-05-28 20:50:59 +00:00
return this.__data && this.__data[attr];
2013-05-17 17:54:14 +00:00
},
set: function (value) {
2013-05-28 20:50:59 +00:00
if (!this.__data) {
this.__data = {};
}
2013-05-17 17:54:14 +00:00
this.__data[attr] = value;
},
configurable: true,
enumerable: false
});
};
ModelClass.forEachProperty(ModelClass.registerProperty);
return ModelClass;
};
function standartize(properties, settings) {
Object.keys(properties).forEach(function (key) {
var v = properties[key];
if (typeof v === 'function' || Array.isArray(v)) {
2013-05-17 17:54:14 +00:00
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`
*
* @param {String} model - name of model
2013-08-13 16:37:09 +00:00
* @param {String} prop - name of property
2013-05-17 17:54:14 +00:00
* @param {Object} params - property settings
*/
2013-05-24 05:20:20 +00:00
ModelBuilder.prototype.defineProperty = function (model, prop, params) {
2013-05-17 17:54:14 +00:00
this.definitions[model].properties[prop] = params;
this.models[model].registerProperty(prop);
};
/**
* Extend existing model with bunch of properties
*
* @param {String} model - name of model
* @param {Object} props - hash of properties
*
* Example:
*
* // Instead of doing this:
*
* // amend the content model with competition attributes
* db.defineProperty('Content', 'competitionType', { type: String });
* db.defineProperty('Content', 'expiryDate', { type: Date, index: true });
* db.defineProperty('Content', 'isExpired', { type: Boolean, index: true });
*
* // dataSource.extend allows to
2013-05-17 17:54:14 +00:00
* // extend the content model with competition attributes
* db.extendModel('Content', {
* competitionType: String,
* expiryDate: { type: Date, index: true },
* isExpired: { type: Boolean, index: true }
* });
*/
2013-05-24 05:20:20 +00:00
ModelBuilder.prototype.extendModel = function (model, props) {
2013-05-17 17:54:14 +00:00
var t = this;
standartize(props, {});
Object.keys(props).forEach(function (propName) {
var definition = props[propName];
t.defineProperty(model, propName, definition);
});
};
2013-05-24 05:20:20 +00:00
ModelBuilder.prototype.copyModel = function copyModel(Master) {
var dataSource = this;
2013-05-17 17:54:14 +00:00
var className = Master.modelName;
var md = Master.dataSource.definitions[className];
2013-05-17 17:54:14 +00:00
var Slave = function SlaveModel() {
Master.apply(this, [].slice.call(arguments));
this.dataSource = dataSource;
2013-05-17 17:54:14 +00:00
};
util.inherits(Slave, Master);
Slave.__proto__ = Master;
hiddenProperty(Slave, 'dataSource', dataSource);
2013-05-17 17:54:14 +00:00
hiddenProperty(Slave, 'modelName', className);
hiddenProperty(Slave, 'relations', Master.relations);
if (!(className in dataSource.models)) {
2013-05-17 17:54:14 +00:00
// store class in model pool
dataSource.models[className] = Slave;
dataSource.definitions[className] = {
2013-05-17 17:54:14 +00:00
properties: md.properties,
settings: md.settings
};
}
return Slave;
};
2013-08-13 16:37:09 +00:00
/*!
2013-05-17 17:54:14 +00:00
* Define hidden property
*/
function hiddenProperty(where, property, value) {
Object.defineProperty(where, property, {
2013-07-02 21:59:24 +00:00
writable: true,
2013-05-17 17:54:14 +00:00
enumerable: false,
2013-05-24 00:29:03 +00:00
configurable: true,
2013-05-17 17:54:14 +00:00
value: value
});
}
2013-08-13 16:37:09 +00:00
/*!
2013-05-17 17:54:14 +00:00
* 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
});
}
2013-05-24 05:20:20 +00:00
/**
* Resolve the type string to be a function, for example, 'String' to String
2013-08-13 16:37:09 +00:00
* @param {String} type The type string, such as 'number', 'Number', 'boolean', or 'String'. It's case insensitive
2013-05-24 05:20:20 +00:00
* @returns {Function} if the type is resolved
*/
2013-07-11 21:24:47 +00:00
ModelBuilder.prototype.getSchemaType = function(type) {
2013-05-24 05:20:20 +00:00
if (!type) {
return type;
}
if (Array.isArray(type) && type.length > 0) {
// For array types, the first item should be the type string
2013-07-11 21:24:47 +00:00
var itemType = this.getSchemaType(type[0]);
2013-05-24 05:20:20 +00:00
if (typeof itemType === 'function') {
return [itemType];
}
else return itemType; // Not resolved, return the type string
}
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) {
2013-07-11 21:24:47 +00:00
return this.getSchemaType(type.type);
2013-05-24 05:20:20 +00:00
} else {
2013-07-11 21:24:47 +00:00
if(!this.anonymousTypesCount) {
this.anonymousTypesCount = 0;
2013-07-11 21:24:47 +00:00
}
this.anonymousTypesCount++;
2013-07-11 21:24:47 +00:00
return this.define('AnonymousType' + this.anonymousTypesCount, type, {idInjection: false});
/*
2013-06-02 06:03:25 +00:00
console.error(type);
2013-05-24 05:20:20 +00:00
throw new Error('Missing type property');
2013-07-11 21:24:47 +00:00
*/
2013-05-24 05:20:20 +00:00
}
2013-06-21 21:15:24 +00:00
} else if('function' === typeof type ) {
return type;
2013-05-24 05:20:20 +00:00
}
2013-06-21 21:15:24 +00:00
return type;
2013-08-09 22:16:32 +00:00
};
2013-05-24 05:20:20 +00:00
/**
* Build a dataSource
2013-08-13 16:37:09 +00:00
* @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
2013-05-24 05:20:20 +00:00
* @returns {*}
*/
2013-07-11 21:24:47 +00:00
ModelBuilder.prototype.buildSchema = function(name, properties, associations) {
2013-05-24 05:20:20 +00:00
for (var p in properties) {
// console.log(name + "." + p + ": " + properties[p]);
2013-07-11 21:24:47 +00:00
var type = this.getSchemaType(properties[p]);
2013-05-24 05:20:20 +00:00
if (typeof type === 'string') {
// console.log('Association: ' + type);
2013-06-21 21:04:24 +00:00
if (Array.isArray(associations)) {
associations.push({
source: name,
target: type,
relation: Array.isArray(properties[p]) ? 'hasMany' : 'belongsTo',
as: p
});
delete properties[p];
}
2013-05-24 05:20:20 +00:00
} else {
2013-05-28 22:40:16 +00:00
var typeDef = {
type: type
};
2013-06-21 21:04:24 +00:00
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];
}
2013-05-28 22:40:16 +00:00
}
properties[p] = typeDef;
2013-05-24 05:20:20 +00:00
}
}
return properties;
2013-08-09 22:16:32 +00:00
};
2013-05-24 05:20:20 +00:00
/**
* Build models from dataSource definitions
2013-08-13 16:37:09 +00:00
*
* `schemas` can be one of the following:
*
* 1. An array of named dataSource definition JSON objects
* 2. A dataSource definition JSON object
2013-05-24 05:20:20 +00:00
* 3. A list of property definitions (anonymous)
2013-08-13 16:37:09 +00:00
*
* @param {*} schemas The schemas
2013-05-24 05:20:20 +00:00
* @returns {Object} A map of model constructors keyed by model name
*/
ModelBuilder.prototype.buildModels = function (schemas) {
2013-05-24 05:20:20 +00:00
var models = {};
if (Array.isArray(schemas)) {
// An array already
} else if (schemas.properties && schemas.name) {
// Only one item
schemas = [schemas];
} else {
// Anonymous dataSource
2013-05-24 05:20:20 +00:00
schemas = [
{
name: 'Anonymous',
properties: schemas
}
];
}
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);
models[name] = model;
2013-05-24 05:20:20 +00:00
}
// Connect the models based on the associations
for (var i = 0; i < associations.length; i++) {
var association = associations[i];
var sourceModel = models[association.source];
var targetModel = models[association.target];
2013-05-24 05:20:20 +00:00
if (sourceModel && targetModel) {
if(typeof sourceModel[association.relation] === 'function') {
sourceModel[association.relation](targetModel, {as: association.as});
}
}
}
return models;
2013-08-09 22:16:32 +00:00
};
2013-05-24 05:20:20 +00:00
2013-08-07 21:51:32 +00:00
/**
* Introspect the json document to build a corresponding model
2013-08-13 16:37:09 +00:00
* @param {String} name The model name
* @param {Object} json The json object
* @param [Object} options The options
2013-08-07 21:51:32 +00:00
* @returns {}
*/
ModelBuilder.prototype.buildModelFromInstance = function(name, json, options) {
// Introspect the JSON document to generate a schema
var schema = introspect(json);
// Create a model for the generated schema
return this.define(name, schema, options);
2013-08-13 16:37:09 +00:00
};
2013-08-07 21:51:32 +00:00
2013-05-24 05:20:20 +00:00