Merge branch 'release/1.3.6' into production

This commit is contained in:
Raymond Feng 2014-03-04 10:41:40 -08:00
commit b58601b3cd
8 changed files with 118 additions and 30 deletions

View File

@ -51,7 +51,7 @@ Post.belongsTo(User, {as: 'author', foreignKey: 'userId'});
User.hasAndBelongsToMany('groups'); User.hasAndBelongsToMany('groups');
var user2 = new User({name: 'Smith'}); var user2 = new User({name: 'Smith', age: 14});
user2.save(function (err) { user2.save(function (err) {
console.log(user2); console.log(user2);
var post = user2.posts.build({title: 'Hello world'}); var post = user2.posts.build({title: 'Hello world'});
@ -64,7 +64,7 @@ Post.findOne({where: {published: false}, order: 'date DESC'}, function (err, dat
console.log(data); console.log(data);
}); });
User.create({name: 'Jeff'}, function (err, data) { User.create({name: 'Jeff', age: 12}, function (err, data) {
if (err) { if (err) {
console.log(err); console.log(err);
return; return;
@ -78,7 +78,7 @@ User.create({name: 'Ray'}, function (err, data) {
console.log(data); console.log(data);
}); });
User.scope('minors', {age: {le: 16}}); User.scope('minors', {where: {age: {lte: 16}}, include: 'posts'});
User.minors(function (err, kids) { User.minors(function (err, kids) {
console.log('Kids: ', kids); console.log('Kids: ', kids);
}); });

View File

@ -7,11 +7,18 @@ var jutil = require('./jutil');
var utils = require('./utils'); var utils = require('./utils');
var ModelBaseClass = require('./model.js'); var ModelBaseClass = require('./model.js');
var DataAccessObject = require('./dao.js'); var DataAccessObject = require('./dao.js');
var defineScope = require('./scope.js').defineScope;
var EventEmitter = require('events').EventEmitter; var EventEmitter = require('events').EventEmitter;
var util = require('util'); var util = require('util');
var assert = require('assert'); var assert = require('assert');
var async = require('async'); var async = require('async');
if (process.env.DEBUG === 'loopback') {
// For back-compatibility
process.env.DEBUG = 'loopback:*';
}
var debug = require('debug')('loopback:datasource');
/** /**
* Export public API * Export public API
*/ */
@ -238,11 +245,10 @@ DataSource.prototype.setup = function (name, settings) {
// just save everything we get // just save everything we get
this.settings = settings || {}; this.settings = settings || {};
// Check the debug env settings this.settings.debug = this.settings.debug || debug.enabled;
var debugEnv = process.env.DEBUG || process.env.NODE_DEBUG || '';
var debugModules = debugEnv.split(/[\s,]+/); if(this.settings.debug) {
if (debugModules.indexOf('loopback') !== -1) { debug('Settings: %j', this.settings);
this.settings.debug = true;
} }
// Disconnected by default // Disconnected by default
@ -346,6 +352,20 @@ DataSource.relationTypes = ['belongsTo', 'hasMany', 'hasAndBelongsToMany'];
function isModelDataSourceAttached(model) { function isModelDataSourceAttached(model) {
return model && (!model.settings.unresolved) && (model.dataSource instanceof DataSource); return model && (!model.settings.unresolved) && (model.dataSource instanceof DataSource);
} }
/*!
* Define scopes for the model class from the scopes object
* @param modelClass
* @param scopes
*/
DataSource.prototype.defineScopes = function (modelClass, scopes) {
if(scopes) {
for(var s in scopes) {
defineScope(modelClass, modelClass, s, scopes[s]);
}
}
};
/*! /*!
* Define relations for the model class from the relations object * Define relations for the model class from the relations object
* @param modelClass * @param modelClass
@ -451,6 +471,9 @@ DataSource.prototype.setupDataAccess = function (modelClass, settings) {
var relations = settings.relationships || settings.relations; var relations = settings.relationships || settings.relations;
this.defineRelations(modelClass, relations); this.defineRelations(modelClass, relations);
var scopes = settings.scopes || {};
this.defineScopes(modelClass, scopes);
}; };
/** /**
@ -655,7 +678,7 @@ DataSource.prototype.defineProperty = function (model, prop, params) {
this.modelBuilder.defineProperty(model, prop, params); this.modelBuilder.defineProperty(model, prop, params);
var resolvedProp = this.getModelDefinition(model).properties[prop]; var resolvedProp = this.getModelDefinition(model).properties[prop];
if (this.connector.defineProperty) { if (this.connector && this.connector.defineProperty) {
this.connector.defineProperty(model, prop, resolvedProp); this.connector.defineProperty(model, prop, resolvedProp);
} }
}; };
@ -722,7 +745,7 @@ DataSource.prototype.discoverModelDefinitions = function (options, cb) {
if (this.connector.discoverModelDefinitions) { if (this.connector.discoverModelDefinitions) {
this.connector.discoverModelDefinitions(options, cb); this.connector.discoverModelDefinitions(options, cb);
} else if (cb) { } else if (cb) {
cb(); process.nextTick(cb);
} }
}; };
@ -767,7 +790,7 @@ DataSource.prototype.discoverModelProperties = function (modelName, options, cb)
if (this.connector.discoverModelProperties) { if (this.connector.discoverModelProperties) {
this.connector.discoverModelProperties(modelName, options, cb); this.connector.discoverModelProperties(modelName, options, cb);
} else if (cb) { } else if (cb) {
cb(); process.nextTick(cb);
} }
}; };
@ -811,7 +834,7 @@ DataSource.prototype.discoverPrimaryKeys = function (modelName, options, cb) {
if (this.connector.discoverPrimaryKeys) { if (this.connector.discoverPrimaryKeys) {
this.connector.discoverPrimaryKeys(modelName, options, cb); this.connector.discoverPrimaryKeys(modelName, options, cb);
} else if (cb) { } else if (cb) {
cb(); process.nextTick(cb);
} }
}; };
@ -858,7 +881,7 @@ DataSource.prototype.discoverForeignKeys = function (modelName, options, cb) {
if (this.connector.discoverForeignKeys) { if (this.connector.discoverForeignKeys) {
this.connector.discoverForeignKeys(modelName, options, cb); this.connector.discoverForeignKeys(modelName, options, cb);
} else if (cb) { } else if (cb) {
cb(); process.nextTick(cb);
} }
}; };
@ -875,7 +898,7 @@ DataSource.prototype.discoverForeignKeysSync = function (modelName, options) {
return this.connector.discoverForeignKeysSync(modelName, options); return this.connector.discoverForeignKeysSync(modelName, options);
} }
return null; return null;
} };
/** /**
* Retrieves a description of the foreign key columns that reference the given table's primary key columns (the foreign keys exported by a table). * Retrieves a description of the foreign key columns that reference the given table's primary key columns (the foreign keys exported by a table).
@ -906,7 +929,7 @@ DataSource.prototype.discoverExportedForeignKeys = function (modelName, options,
if (this.connector.discoverExportedForeignKeys) { if (this.connector.discoverExportedForeignKeys) {
this.connector.discoverExportedForeignKeys(modelName, options, cb); this.connector.discoverExportedForeignKeys(modelName, options, cb);
} else if (cb) { } else if (cb) {
cb(); process.nextTick(cb);
} }
}; };
@ -971,7 +994,7 @@ DataSource.prototype.discoverSchema = function (modelName, options, cb) {
return; return;
} }
}); });
} };
/** /**
* Discover schema from a given modelName/view * Discover schema from a given modelName/view
@ -1028,7 +1051,7 @@ DataSource.prototype.discoverSchemas = function (modelName, options, cb) {
}); });
if (self.settings.debug) { if (self.settings.debug) {
console.log('Primary keys: ', pks); debug('Primary keys: ', pks);
} }
var schema = { var schema = {
@ -1075,7 +1098,7 @@ DataSource.prototype.discoverSchemas = function (modelName, options, cb) {
var schemaKey = columns[0].owner + '.' + modelName; var schemaKey = columns[0].owner + '.' + modelName;
if (!options.visited.hasOwnProperty(schemaKey)) { if (!options.visited.hasOwnProperty(schemaKey)) {
if (self.settings.debug) { if (self.settings.debug) {
console.log('Adding schema for ' + schemaKey); debug('Adding schema for ' + schemaKey);
} }
options.visited[schemaKey] = schema; options.visited[schemaKey] = schema;
} }
@ -1100,7 +1123,7 @@ DataSource.prototype.discoverSchemas = function (modelName, options, cb) {
}); });
if (self.settings.debug) { if (self.settings.debug) {
console.log('Foreign keys: ', fks); debug('Foreign keys: ', fks);
} }
schema.options.relations = {}; schema.options.relations = {};
@ -1125,7 +1148,7 @@ DataSource.prototype.discoverSchemas = function (modelName, options, cb) {
var moreTasks = []; var moreTasks = [];
for (var t in otherTables) { for (var t in otherTables) {
if (self.settings.debug) { if (self.settings.debug) {
console.log('Discovering related schema for ' + schemaKey); debug('Discovering related schema for ' + schemaKey);
} }
var newOptions = {}; var newOptions = {};
for (var key in options) { for (var key in options) {
@ -1173,7 +1196,7 @@ DataSource.prototype.discoverSchemasSync = function (modelName, options) {
}); });
if (self.settings.debug) { if (self.settings.debug) {
console.log('Primary keys: ', pks); debug('Primary keys: ', pks);
} }
var schema = { var schema = {
@ -1220,7 +1243,7 @@ DataSource.prototype.discoverSchemasSync = function (modelName, options) {
var schemaKey = columns[0].owner + '.' + modelName; var schemaKey = columns[0].owner + '.' + modelName;
if (!options.visited.hasOwnProperty(schemaKey)) { if (!options.visited.hasOwnProperty(schemaKey)) {
if (self.settings.debug) { if (self.settings.debug) {
console.log('Adding schema for ' + schemaKey); debug('Adding schema for ' + schemaKey);
} }
options.visited[schemaKey] = schema; options.visited[schemaKey] = schema;
} }
@ -1246,7 +1269,7 @@ DataSource.prototype.discoverSchemasSync = function (modelName, options) {
}); });
if (self.settings.debug) { if (self.settings.debug) {
console.log('Foreign keys: ', fks); debug('Foreign keys: ', fks);
} }
schema.options.relations = {}; schema.options.relations = {};
@ -1271,7 +1294,7 @@ DataSource.prototype.discoverSchemasSync = function (modelName, options) {
var moreTasks = []; var moreTasks = [];
for (var t in otherTables) { for (var t in otherTables) {
if (self.settings.debug) { if (self.settings.debug) {
console.log('Discovering related schema for ' + schemaKey); debug('Discovering related schema for ' + schemaKey);
} }
var newOptions = {}; var newOptions = {};
for (var key in options) { for (var key in options) {
@ -1377,6 +1400,7 @@ DataSource.prototype.isActual = function (models, cb) {
* @private used by connectors * @private used by connectors
*/ */
DataSource.prototype.log = function (sql, t) { DataSource.prototype.log = function (sql, t) {
debug(sql, t);
this.emit('log', sql, t); this.emit('log', sql, t);
}; };
@ -1384,13 +1408,16 @@ DataSource.prototype.log = function (sql, t) {
* Freeze dataSource. Behavior depends on connector * Freeze dataSource. Behavior depends on connector
*/ */
DataSource.prototype.freeze = function freeze() { DataSource.prototype.freeze = function freeze() {
if(!this.connector) {
throw new Error('The connector has not been initialized.');
}
if (this.connector.freezeDataSource) { if (this.connector.freezeDataSource) {
this.connector.freezeDataSource(); this.connector.freezeDataSource();
} }
if (this.connector.freezeSchema) { if (this.connector.freezeSchema) {
this.connector.freezeSchema(); this.connector.freezeSchema();
} }
} };
/** /**
* Return table name for specified `modelName` * Return table name for specified `modelName`

View File

@ -1,4 +1,5 @@
var util = require('util'); var util = require('util');
var Any = require('./types').Types.Any;
module.exports = List; module.exports = List;
@ -32,6 +33,10 @@ function List(items, itemType, parent) {
itemType = itemType[0]; itemType = itemType[0];
} }
if(itemType === Array) {
itemType = Any;
}
Object.defineProperty(arr, 'itemType', { Object.defineProperty(arr, 'itemType', {
writable: true, writable: true,
enumerable: false, enumerable: false,

View File

@ -277,6 +277,15 @@ Relation.belongsTo = function (anotherClass, params) {
} }
}; };
// Set the remoting metadata so that it can be accessed as /api/<model>/<id>/<belongsToRelationName>
// For example, /api/orders/1/customer
var fn = this.prototype[methodName];
fn.shared = true;
fn.http = {verb: 'get', path: '/' + methodName};
fn.accepts = {arg: 'refresh', type: 'boolean', http: {source: 'query'}};
fn.description = 'Fetches belongsTo relation ' + methodName;
fn.returns = {arg: methodName, type: 'object', root: true};
}; };
/** /**

View File

@ -103,7 +103,7 @@ function defineScope(cls, targetClass, name, params, methods) {
fn.shared = true; fn.shared = true;
fn.http = {verb: 'get', path: '/' + name}; fn.http = {verb: 'get', path: '/' + name};
fn.accepts = {arg: 'where', type: 'object'}; fn.accepts = {arg: 'filter', type: 'object'};
fn.description = 'Fetches ' + name; fn.description = 'Fetches ' + name;
fn.returns = {arg: name, type: 'array', root: true}; fn.returns = {arg: name, type: 'array', root: true};
@ -188,6 +188,18 @@ function defineScope(cls, targetClass, name, params, methods) {
base.order = update.order; base.order = update.order;
} }
if(update.limit !== undefined) {
base.limit = update.limit;
}
if(update.skip !== undefined) {
base.skip = update.skip;
}
if(update.offset !== undefined) {
base.offset = update.offset;
}
if(update.fields !== undefined) {
base.fields = update.fields;
}
return base; return base;
} }

View File

@ -1,6 +1,6 @@
{ {
"name": "loopback-datasource-juggler", "name": "loopback-datasource-juggler",
"version": "1.3.5", "version": "1.3.6",
"description": "LoopBack DataSoure Juggler", "description": "LoopBack DataSoure Juggler",
"keywords": [ "keywords": [
"StrongLoop", "StrongLoop",
@ -30,7 +30,8 @@
"async": "~0.2.10", "async": "~0.2.10",
"inflection": "~1.3.5", "inflection": "~1.3.5",
"traverse": "~0.6.6", "traverse": "~0.6.6",
"qs": "~0.6.6" "qs": "~0.6.6",
"debug": "~0.7.4"
}, },
"license": { "license": {
"name": "Dual MIT/StrongLoop", "name": "Dual MIT/StrongLoop",

View File

@ -13,6 +13,7 @@ describe('datatypes', function () {
num: Number, num: Number,
bool: Boolean, bool: Boolean,
list: {type: [String]}, list: {type: [String]},
arr: Array
}); });
db.automigrate(function () { db.automigrate(function () {
Model.destroyAll(done); Model.destroyAll(done);
@ -23,25 +24,30 @@ describe('datatypes', function () {
var d = new Date, id; var d = new Date, id;
Model.create({ Model.create({
str: 'hello', date: d, num: '3', bool: 1, list: ['test'] str: 'hello', date: d, num: '3', bool: 1, list: ['test'], arr: [1, 'str']
}, function (err, m) { }, function (err, m) {
should.not.exist(err); should.not.exist(err);
should.exist(m && m.id); should.exist(m && m.id);
m.str.should.be.a('string'); m.str.should.be.a('string');
m.num.should.be.a('number'); m.num.should.be.a('number');
m.bool.should.be.a('boolean'); m.bool.should.be.a('boolean');
m.list[0].should.be.equal('test');
m.arr[0].should.be.equal(1);
m.arr[1].should.be.equal('str');
id = m.id; id = m.id;
testFind(testAll); testFind(testAll);
}); });
function testFind(next) { function testFind(next) {
debugger;
Model.findById(id, function (err, m) { Model.findById(id, function (err, m) {
should.not.exist(err); should.not.exist(err);
should.exist(m); should.exist(m);
m.str.should.be.a('string'); m.str.should.be.a('string');
m.num.should.be.a('number'); m.num.should.be.a('number');
m.bool.should.be.a('boolean'); m.bool.should.be.a('boolean');
m.list[0].should.be.equal('test');
m.arr[0].should.be.equal(1);
m.arr[1].should.be.equal('str');
m.date.should.be.an.instanceOf(Date); m.date.should.be.an.instanceOf(Date);
m.date.toString().should.equal(d.toString(), 'Time must match'); m.date.toString().should.equal(d.toString(), 'Time must match');
next(); next();

View File

@ -1,6 +1,7 @@
// This test written in mocha+should.js // This test written in mocha+should.js
var should = require('./init.js'); var should = require('./init.js');
var assert = require('assert'); var assert = require('assert');
var async = require('async');
var jdb = require('../'); var jdb = require('../');
var ModelBuilder = jdb.ModelBuilder; var ModelBuilder = jdb.ModelBuilder;
@ -796,6 +797,33 @@ describe('Load models with relations', function () {
}); });
describe('Model with scopes', function () {
it('should create scopes', function (done) {
var ds = new DataSource('memory');
var User = ds.define('User', {name: String, vip: Boolean, age: Number},
{scopes: {vips: {where: {vip: true}}, top5: {limit: 5, order: 'age'}}});
var users = [];
for (var i = 0; i < 10; i++) {
users.push({name: 'User' + i, vip: i % 3 === 0, age: 20 + i * 2});
}
async.each(users, function (user, callback) {
User.create(user, callback);
}, function (err) {
User.vips(function (err, vips) {
if(err) {
return done(err);
}
assert.equal(vips.length, 4);
User.top5(function (err, top5) {
assert.equal(top5.length, 5);
done(err);
});
});
});
});
});
describe('DataAccessObject', function () { describe('DataAccessObject', function () {
var ds, model, where; var ds, model, where;