Run `eslint --fix` with config from master
This commit is contained in:
parent
fd1afdf6e6
commit
a5187765f6
|
@ -10,36 +10,36 @@ var introspectType = require('../lib/introspection')(ModelBuilder);
|
||||||
var ds = new DataSource('memory');
|
var ds = new DataSource('memory');
|
||||||
|
|
||||||
// Create a open model that doesn't require a schema
|
// Create a open model that doesn't require a schema
|
||||||
var Application = ds.createModel('Schemaless', {}, {strict: false});
|
var Application = ds.createModel('Schemaless', {}, { strict: false });
|
||||||
|
|
||||||
var application = {
|
var application = {
|
||||||
owner: 'rfeng',
|
owner: 'rfeng',
|
||||||
name: 'MyApp1',
|
name: 'MyApp1',
|
||||||
description: 'My first app',
|
description: 'My first app',
|
||||||
pushSettings: [
|
pushSettings: [
|
||||||
{ "platform": "apns",
|
{ 'platform': 'apns',
|
||||||
"apns": {
|
'apns': {
|
||||||
"pushOptions": {
|
'pushOptions': {
|
||||||
"gateway": "gateway.sandbox.push.apple.com",
|
'gateway': 'gateway.sandbox.push.apple.com',
|
||||||
"cert": "credentials/apns_cert_dev.pem",
|
'cert': 'credentials/apns_cert_dev.pem',
|
||||||
"key": "credentials/apns_key_dev.pem"
|
'key': 'credentials/apns_key_dev.pem',
|
||||||
},
|
},
|
||||||
|
|
||||||
"feedbackOptions": {
|
'feedbackOptions': {
|
||||||
"gateway": "feedback.sandbox.push.apple.com",
|
'gateway': 'feedback.sandbox.push.apple.com',
|
||||||
"cert": "credentials/apns_cert_dev.pem",
|
'cert': 'credentials/apns_cert_dev.pem',
|
||||||
"key": "credentials/apns_key_dev.pem",
|
'key': 'credentials/apns_key_dev.pem',
|
||||||
"batchFeedback": true,
|
'batchFeedback': true,
|
||||||
"interval": 300
|
'interval': 300,
|
||||||
}
|
},
|
||||||
}}
|
}},
|
||||||
]}
|
] };
|
||||||
|
|
||||||
console.log(new Application(application).toObject());
|
console.log(new Application(application).toObject());
|
||||||
|
|
||||||
Application.create(application, function (err, app1) {
|
Application.create(application, function(err, app1) {
|
||||||
console.log('Created: ', app1.toObject());
|
console.log('Created: ', app1.toObject());
|
||||||
Application.findById(app1.id, function (err, app2) {
|
Application.findById(app1.id, function(err, app2) {
|
||||||
console.log('Found: ', app2.toObject());
|
console.log('Found: ', app2.toObject());
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
@ -55,30 +55,30 @@ var user = {
|
||||||
city: 'San Jose',
|
city: 'San Jose',
|
||||||
state: 'CA',
|
state: 'CA',
|
||||||
zipcode: '95131',
|
zipcode: '95131',
|
||||||
country: 'US'
|
country: 'US',
|
||||||
},
|
},
|
||||||
friends: ['John', 'Mary'],
|
friends: ['John', 'Mary'],
|
||||||
emails: [
|
emails: [
|
||||||
{label: 'work', id: 'x@sample.com'},
|
{ label: 'work', id: 'x@sample.com' },
|
||||||
{label: 'home', id: 'x@home.com'}
|
{ label: 'home', id: 'x@home.com' },
|
||||||
],
|
],
|
||||||
tags: []
|
tags: [],
|
||||||
};
|
};
|
||||||
|
|
||||||
// Introspect the JSON document to generate a schema
|
// Introspect the JSON document to generate a schema
|
||||||
var schema = introspectType(user);
|
var schema = introspectType(user);
|
||||||
|
|
||||||
// Create a model for the generated schema
|
// Create a model for the generated schema
|
||||||
var User = ds.createModel('User', schema, {idInjection: true});
|
var User = ds.createModel('User', schema, { idInjection: true });
|
||||||
|
|
||||||
// Use the model for CRUD
|
// Use the model for CRUD
|
||||||
var obj = new User(user);
|
var obj = new User(user);
|
||||||
|
|
||||||
console.log(obj.toObject());
|
console.log(obj.toObject());
|
||||||
|
|
||||||
User.create(user, function (err, u1) {
|
User.create(user, function(err, u1) {
|
||||||
console.log('Created: ', u1.toObject());
|
console.log('Created: ', u1.toObject());
|
||||||
User.findById(u1.id, function (err, u2) {
|
User.findById(u1.id, function(err, u2) {
|
||||||
console.log('Found: ', u2.toObject());
|
console.log('Found: ', u2.toObject());
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
|
@ -9,11 +9,11 @@ var modelBuilder = new ModelBuilder();
|
||||||
var Post = modelBuilder.define('Post', {
|
var Post = modelBuilder.define('Post', {
|
||||||
title: { type: String, length: 255 },
|
title: { type: String, length: 255 },
|
||||||
content: { type: ModelBuilder.Text },
|
content: { type: ModelBuilder.Text },
|
||||||
date: { type: Date, default: function () {
|
date: { type: Date, default: function() {
|
||||||
return new Date();
|
return new Date();
|
||||||
} },
|
} },
|
||||||
timestamp: { type: Number, default: Date.now },
|
timestamp: { type: Number, default: Date.now },
|
||||||
published: { type: Boolean, default: false, index: true }
|
published: { type: Boolean, default: false, index: true },
|
||||||
});
|
});
|
||||||
|
|
||||||
// simpler way to describe model
|
// simpler way to describe model
|
||||||
|
@ -22,24 +22,24 @@ var User = modelBuilder.define('User', {
|
||||||
bio: ModelBuilder.Text,
|
bio: ModelBuilder.Text,
|
||||||
approved: Boolean,
|
approved: Boolean,
|
||||||
joinedAt: Date,
|
joinedAt: Date,
|
||||||
age: Number
|
age: Number,
|
||||||
});
|
});
|
||||||
|
|
||||||
var Group = modelBuilder.define('Group', {group: String});
|
var Group = modelBuilder.define('Group', { group: String });
|
||||||
|
|
||||||
// define any custom method
|
// define any custom method
|
||||||
User.prototype.getNameAndAge = function () {
|
User.prototype.getNameAndAge = function() {
|
||||||
return this.name + ', ' + this.age;
|
return this.name + ', ' + this.age;
|
||||||
};
|
};
|
||||||
|
|
||||||
var user = new User({name: 'Joe'});
|
var user = new User({ name: 'Joe' });
|
||||||
console.log(user);
|
console.log(user);
|
||||||
|
|
||||||
console.log(modelBuilder.models);
|
console.log(modelBuilder.models);
|
||||||
console.log(modelBuilder.definitions);
|
console.log(modelBuilder.definitions);
|
||||||
|
|
||||||
User.mixin(Group);
|
User.mixin(Group);
|
||||||
var user = new User({name: 'Ray', group: 'Admin'});
|
var user = new User({ name: 'Ray', group: 'Admin' });
|
||||||
console.log(user);
|
console.log(user);
|
||||||
|
|
||||||
|
|
||||||
|
|
|
@ -11,11 +11,11 @@ var ds = new DataSource('memory');
|
||||||
var Post = ds.define('Post', {
|
var Post = ds.define('Post', {
|
||||||
title: { type: String, length: 255 },
|
title: { type: String, length: 255 },
|
||||||
content: { type: DataSource.Text },
|
content: { type: DataSource.Text },
|
||||||
date: { type: Date, default: function () {
|
date: { type: Date, default: function() {
|
||||||
return new Date;
|
return new Date;
|
||||||
} },
|
} },
|
||||||
timestamp: { type: Number, default: Date.now },
|
timestamp: { type: Number, default: Date.now },
|
||||||
published: { type: Boolean, default: false, index: true }
|
published: { type: Boolean, default: false, index: true },
|
||||||
});
|
});
|
||||||
|
|
||||||
// simplier way to describe model
|
// simplier way to describe model
|
||||||
|
@ -24,31 +24,31 @@ var User = ds.define('User', {
|
||||||
bio: DataSource.Text,
|
bio: DataSource.Text,
|
||||||
approved: Boolean,
|
approved: Boolean,
|
||||||
joinedAt: Date,
|
joinedAt: Date,
|
||||||
age: Number
|
age: Number,
|
||||||
});
|
});
|
||||||
|
|
||||||
var Group = ds.define('Group', {name: String});
|
var Group = ds.define('Group', { name: String });
|
||||||
|
|
||||||
// define any custom method
|
// define any custom method
|
||||||
User.prototype.getNameAndAge = function () {
|
User.prototype.getNameAndAge = function() {
|
||||||
return this.name + ', ' + this.age;
|
return this.name + ', ' + this.age;
|
||||||
};
|
};
|
||||||
|
|
||||||
var user = new User({name: 'Joe'});
|
var user = new User({ name: 'Joe' });
|
||||||
console.log(user);
|
console.log(user);
|
||||||
|
|
||||||
// console.log(ds.models);
|
// console.log(ds.models);
|
||||||
// console.log(ds.definitions);
|
// console.log(ds.definitions);
|
||||||
|
|
||||||
// setup relationships
|
// setup relationships
|
||||||
User.hasMany(Post, {as: 'posts', foreignKey: 'userId'});
|
User.hasMany(Post, { as: 'posts', foreignKey: 'userId' });
|
||||||
|
|
||||||
// creates instance methods:
|
// creates instance methods:
|
||||||
// user.posts(conds)
|
// user.posts(conds)
|
||||||
// user.posts.build(data) // like new Post({userId: user.id});
|
// user.posts.build(data) // like new Post({userId: user.id});
|
||||||
// user.posts.create(data) // build and save
|
// user.posts.create(data) // build and save
|
||||||
|
|
||||||
Post.belongsTo(User, {as: 'author', foreignKey: 'userId'});
|
Post.belongsTo(User, { as: 'author', foreignKey: 'userId' });
|
||||||
// creates instance methods:
|
// creates instance methods:
|
||||||
// post.author(callback) -- getter when called with function
|
// post.author(callback) -- getter when called with function
|
||||||
// post.author() -- sync getter when called without params
|
// post.author() -- sync getter when called without params
|
||||||
|
@ -56,46 +56,46 @@ Post.belongsTo(User, {as: 'author', foreignKey: 'userId'});
|
||||||
|
|
||||||
User.hasAndBelongsToMany('groups');
|
User.hasAndBelongsToMany('groups');
|
||||||
|
|
||||||
var user2 = new User({name: 'Smith', age: 14});
|
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' });
|
||||||
post.save(function (err, data) {
|
post.save(function(err, data) {
|
||||||
console.log(err ? err : data);
|
console.log(err ? err : data);
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
Post.findOne({where: {published: false}, order: 'date DESC'}, function (err, data) {
|
Post.findOne({ where: { published: false }, order: 'date DESC' }, function(err, data) {
|
||||||
console.log(data);
|
console.log(data);
|
||||||
});
|
});
|
||||||
|
|
||||||
User.create({name: 'Jeff', age: 12}, function (err, data) {
|
User.create({ name: 'Jeff', age: 12 }, function(err, data) {
|
||||||
if (err) {
|
if (err) {
|
||||||
console.log(err);
|
console.log(err);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
console.log(data);
|
console.log(data);
|
||||||
var post = data.posts.build({title: 'My Post'});
|
var post = data.posts.build({ title: 'My Post' });
|
||||||
console.log(post);
|
console.log(post);
|
||||||
});
|
});
|
||||||
|
|
||||||
User.create({name: 'Ray'}, function (err, data) {
|
User.create({ name: 'Ray' }, function(err, data) {
|
||||||
console.log(data);
|
console.log(data);
|
||||||
});
|
});
|
||||||
|
|
||||||
User.scope('minors', {where: {age: {lte: 16}}, include: 'posts'});
|
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);
|
||||||
});
|
});
|
||||||
|
|
||||||
var Article = ds.define('Article', {title: String});
|
var Article = ds.define('Article', { title: String });
|
||||||
var Tag = ds.define('Tag', {name: String});
|
var Tag = ds.define('Tag', { name: String });
|
||||||
Article.hasAndBelongsToMany('tags');
|
Article.hasAndBelongsToMany('tags');
|
||||||
|
|
||||||
Article.create(function (e, article) {
|
Article.create(function(e, article) {
|
||||||
article.tags.create({name: 'popular'}, function (err, data) {
|
article.tags.create({ name: 'popular' }, function(err, data) {
|
||||||
Article.findOne(function (e, article) {
|
Article.findOne(function(e, article) {
|
||||||
article.tags(function (e, tags) {
|
article.tags(function(e, tags) {
|
||||||
console.log(tags);
|
console.log(tags);
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
@ -106,17 +106,17 @@ Article.create(function (e, article) {
|
||||||
var modelBuilder = new ModelBuilder();
|
var modelBuilder = new ModelBuilder();
|
||||||
|
|
||||||
Color = modelBuilder.define('Color', {
|
Color = modelBuilder.define('Color', {
|
||||||
name: String
|
name: String,
|
||||||
});
|
});
|
||||||
|
|
||||||
// attach
|
// attach
|
||||||
ds.attach(Color);
|
ds.attach(Color);
|
||||||
|
|
||||||
Color.create({name: 'red'});
|
Color.create({ name: 'red' });
|
||||||
Color.create({name: 'green'});
|
Color.create({ name: 'green' });
|
||||||
Color.create({name: 'blue'});
|
Color.create({ name: 'blue' });
|
||||||
|
|
||||||
Color.all(function (err, colors) {
|
Color.all(function(err, colors) {
|
||||||
console.log(colors);
|
console.log(colors);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
|
|
@ -8,54 +8,54 @@ var jdb = require('../index');
|
||||||
var User, Post, Passport, City, Street, Building;
|
var User, Post, Passport, City, Street, Building;
|
||||||
var nbSchemaRequests = 0;
|
var nbSchemaRequests = 0;
|
||||||
|
|
||||||
setup(function () {
|
setup(function() {
|
||||||
|
|
||||||
Passport.find({include: 'owner'}, function (err, passports) {
|
Passport.find({ include: 'owner' }, function(err, passports) {
|
||||||
console.log('passports.owner', passports);
|
console.log('passports.owner', passports);
|
||||||
});
|
});
|
||||||
|
|
||||||
User.find({include: 'posts'}, function (err, users) {
|
User.find({ include: 'posts' }, function(err, users) {
|
||||||
console.log('users.posts', users);
|
console.log('users.posts', users);
|
||||||
});
|
});
|
||||||
|
|
||||||
Passport.find({include: {owner: 'posts'}}, function (err, passports) {
|
Passport.find({ include: { owner: 'posts' }}, function(err, passports) {
|
||||||
console.log('passports.owner.posts', passports);
|
console.log('passports.owner.posts', passports);
|
||||||
});
|
});
|
||||||
|
|
||||||
Passport.find({
|
Passport.find({
|
||||||
include: {owner: {posts: 'author'}}
|
include: { owner: { posts: 'author' }},
|
||||||
}, function (err, passports) {
|
}, function(err, passports) {
|
||||||
console.log('passports.owner.posts.author', passports);
|
console.log('passports.owner.posts.author', passports);
|
||||||
});
|
});
|
||||||
|
|
||||||
User.find({include: ['posts', 'passports']}, function (err, users) {
|
User.find({ include: ['posts', 'passports'] }, function(err, users) {
|
||||||
console.log('users.passports && users.posts', users);
|
console.log('users.passports && users.posts', users);
|
||||||
});
|
});
|
||||||
|
|
||||||
});
|
});
|
||||||
|
|
||||||
function setup(done) {
|
function setup(done) {
|
||||||
var db = new jdb.DataSource({connector: 'memory'});
|
var db = new jdb.DataSource({ connector: 'memory' });
|
||||||
City = db.define('City');
|
City = db.define('City');
|
||||||
Street = db.define('Street');
|
Street = db.define('Street');
|
||||||
Building = db.define('Building');
|
Building = db.define('Building');
|
||||||
User = db.define('User', {
|
User = db.define('User', {
|
||||||
name: String,
|
name: String,
|
||||||
age: Number
|
age: Number,
|
||||||
});
|
});
|
||||||
Passport = db.define('Passport', {
|
Passport = db.define('Passport', {
|
||||||
number: String
|
number: String,
|
||||||
});
|
});
|
||||||
Post = db.define('Post', {
|
Post = db.define('Post', {
|
||||||
title: String
|
title: String,
|
||||||
});
|
});
|
||||||
|
|
||||||
Passport.belongsTo('owner', {model: User});
|
Passport.belongsTo('owner', { model: User });
|
||||||
User.hasMany('passports', {foreignKey: 'ownerId'});
|
User.hasMany('passports', { foreignKey: 'ownerId' });
|
||||||
User.hasMany('posts', {foreignKey: 'userId'});
|
User.hasMany('posts', { foreignKey: 'userId' });
|
||||||
Post.belongsTo('author', {model: User, foreignKey: 'userId'});
|
Post.belongsTo('author', { model: User, foreignKey: 'userId' });
|
||||||
|
|
||||||
db.automigrate(function () {
|
db.automigrate(function() {
|
||||||
var createdUsers = [];
|
var createdUsers = [];
|
||||||
var createdPassports = [];
|
var createdPassports = [];
|
||||||
var createdPosts = [];
|
var createdPosts = [];
|
||||||
|
@ -64,13 +64,13 @@ function setup(done) {
|
||||||
clearAndCreate(
|
clearAndCreate(
|
||||||
User,
|
User,
|
||||||
[
|
[
|
||||||
{name: 'User A', age: 21},
|
{ name: 'User A', age: 21 },
|
||||||
{name: 'User B', age: 22},
|
{ name: 'User B', age: 22 },
|
||||||
{name: 'User C', age: 23},
|
{ name: 'User C', age: 23 },
|
||||||
{name: 'User D', age: 24},
|
{ name: 'User D', age: 24 },
|
||||||
{name: 'User E', age: 25}
|
{ name: 'User E', age: 25 },
|
||||||
],
|
],
|
||||||
function (items) {
|
function(items) {
|
||||||
createdUsers = items;
|
createdUsers = items;
|
||||||
createPassports();
|
createPassports();
|
||||||
}
|
}
|
||||||
|
@ -81,11 +81,11 @@ function setup(done) {
|
||||||
clearAndCreate(
|
clearAndCreate(
|
||||||
Passport,
|
Passport,
|
||||||
[
|
[
|
||||||
{number: '1', ownerId: createdUsers[0].id},
|
{ number: '1', ownerId: createdUsers[0].id },
|
||||||
{number: '2', ownerId: createdUsers[1].id},
|
{ number: '2', ownerId: createdUsers[1].id },
|
||||||
{number: '3'}
|
{ number: '3' },
|
||||||
],
|
],
|
||||||
function (items) {
|
function(items) {
|
||||||
createdPassports = items;
|
createdPassports = items;
|
||||||
createPosts();
|
createPosts();
|
||||||
}
|
}
|
||||||
|
@ -96,13 +96,13 @@ function setup(done) {
|
||||||
clearAndCreate(
|
clearAndCreate(
|
||||||
Post,
|
Post,
|
||||||
[
|
[
|
||||||
{title: 'Post A', userId: createdUsers[0].id},
|
{ title: 'Post A', userId: createdUsers[0].id },
|
||||||
{title: 'Post B', userId: createdUsers[0].id},
|
{ title: 'Post B', userId: createdUsers[0].id },
|
||||||
{title: 'Post C', userId: createdUsers[0].id},
|
{ title: 'Post C', userId: createdUsers[0].id },
|
||||||
{title: 'Post D', userId: createdUsers[1].id},
|
{ title: 'Post D', userId: createdUsers[1].id },
|
||||||
{title: 'Post E'}
|
{ title: 'Post E' },
|
||||||
],
|
],
|
||||||
function (items) {
|
function(items) {
|
||||||
createdPosts = items;
|
createdPosts = items;
|
||||||
done();
|
done();
|
||||||
}
|
}
|
||||||
|
@ -114,7 +114,7 @@ function setup(done) {
|
||||||
|
|
||||||
function clearAndCreate(model, data, callback) {
|
function clearAndCreate(model, data, callback) {
|
||||||
var createdItems = [];
|
var createdItems = [];
|
||||||
model.destroyAll(function () {
|
model.destroyAll(function() {
|
||||||
nextItem(null, null);
|
nextItem(null, null);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
|
|
@ -18,21 +18,21 @@ var User = modelBuilder.define('User', {
|
||||||
city: String,
|
city: String,
|
||||||
state: String,
|
state: String,
|
||||||
zipCode: String,
|
zipCode: String,
|
||||||
country: String
|
country: String,
|
||||||
},
|
},
|
||||||
emails: [
|
emails: [
|
||||||
{
|
{
|
||||||
label: String,
|
label: String,
|
||||||
email: String
|
email: String,
|
||||||
}
|
},
|
||||||
],
|
],
|
||||||
friends: [String]
|
friends: [String],
|
||||||
});
|
});
|
||||||
|
|
||||||
var user = new User({name: 'Joe', age: 20, address: {street: '123 Main St', 'city': 'San Jose', state: 'CA'},
|
var user = new User({ name: 'Joe', age: 20, address: { street: '123 Main St', 'city': 'San Jose', state: 'CA' },
|
||||||
emails: [
|
emails: [
|
||||||
{label: 'work', email: 'xyz@sample.com'}
|
{ label: 'work', email: 'xyz@sample.com' },
|
||||||
],
|
],
|
||||||
friends: ['John', 'Mary']});
|
friends: ['John', 'Mary'] });
|
||||||
console.log(user);
|
console.log(user);
|
||||||
console.log(user.toObject());
|
console.log(user.toObject());
|
||||||
|
|
|
@ -9,55 +9,55 @@ var ds = new DataSource('memory');
|
||||||
var Order = ds.createModel('Order', {
|
var Order = ds.createModel('Order', {
|
||||||
items: [String],
|
items: [String],
|
||||||
orderDate: Date,
|
orderDate: Date,
|
||||||
qty: Number
|
qty: Number,
|
||||||
});
|
});
|
||||||
|
|
||||||
var Customer = ds.createModel('Customer', {
|
var Customer = ds.createModel('Customer', {
|
||||||
name: String
|
name: String,
|
||||||
});
|
});
|
||||||
|
|
||||||
Order.belongsTo(Customer);
|
Order.belongsTo(Customer);
|
||||||
|
|
||||||
var order1, order2, order3;
|
var order1, order2, order3;
|
||||||
|
|
||||||
Customer.create({name: 'John'}, function (err, customer) {
|
Customer.create({ name: 'John' }, function(err, customer) {
|
||||||
Order.create({customerId: customer.id, orderDate: new Date(), items: ['Book']}, function (err, order) {
|
Order.create({ customerId: customer.id, orderDate: new Date(), items: ['Book'] }, function(err, order) {
|
||||||
order1 = order;
|
order1 = order;
|
||||||
order.customer(console.log);
|
order.customer(console.log);
|
||||||
order.customer(true, console.log);
|
order.customer(true, console.log);
|
||||||
|
|
||||||
Customer.create({name: 'Mary'}, function (err, customer2) {
|
Customer.create({ name: 'Mary' }, function(err, customer2) {
|
||||||
order.customer(customer2);
|
order.customer(customer2);
|
||||||
order.customer(console.log);
|
order.customer(console.log);
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
Order.create({orderDate: new Date(), items: ['Phone']}, function (err, order) {
|
Order.create({ orderDate: new Date(), items: ['Phone'] }, function(err, order) {
|
||||||
|
|
||||||
order.customer.create({name: 'Smith'}, function(err, customer2) {
|
order.customer.create({ name: 'Smith' }, function(err, customer2) {
|
||||||
console.log(order, customer2);
|
console.log(order, customer2);
|
||||||
order.save(function(err, order) {
|
order.save(function(err, order) {
|
||||||
order2 = order;
|
order2 = order;
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
var customer3 = order.customer.build({name: 'Tom'});
|
var customer3 = order.customer.build({ name: 'Tom' });
|
||||||
console.log('Customer 3', customer3);
|
console.log('Customer 3', customer3);
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
Customer.hasMany(Order, {as: 'orders', foreignKey: 'customerId'});
|
Customer.hasMany(Order, { as: 'orders', foreignKey: 'customerId' });
|
||||||
|
|
||||||
Customer.create({name: 'Ray'}, function (err, customer) {
|
Customer.create({ name: 'Ray' }, function(err, customer) {
|
||||||
Order.create({customerId: customer.id, qty: 3, orderDate: new Date()}, function (err, order) {
|
Order.create({ customerId: customer.id, qty: 3, orderDate: new Date() }, function(err, order) {
|
||||||
order3 = order;
|
order3 = order;
|
||||||
customer.orders(console.log);
|
customer.orders(console.log);
|
||||||
customer.orders.create({orderDate: new Date(), qty: 4}, function (err, order) {
|
customer.orders.create({ orderDate: new Date(), qty: 4 }, function(err, order) {
|
||||||
console.log(order);
|
console.log(order);
|
||||||
Customer.include([customer], 'orders', function (err, results) {
|
Customer.include([customer], 'orders', function(err, results) {
|
||||||
console.log('Results: ', results);
|
console.log('Results: ', results);
|
||||||
});
|
});
|
||||||
customer.orders({where: {qty: 4}}, function(err, results) {
|
customer.orders({ where: { qty: 4 }}, function(err, results) {
|
||||||
console.log('customer.orders', results);
|
console.log('customer.orders', results);
|
||||||
});
|
});
|
||||||
customer.orders.findById(order3.id, console.log);
|
customer.orders.findById(order3.id, console.log);
|
||||||
|
@ -67,43 +67,43 @@ Customer.create({name: 'Ray'}, function (err, customer) {
|
||||||
});
|
});
|
||||||
|
|
||||||
var Physician = ds.createModel('Physician', {
|
var Physician = ds.createModel('Physician', {
|
||||||
name: String
|
name: String,
|
||||||
});
|
});
|
||||||
|
|
||||||
var Patient = ds.createModel('Patient', {
|
var Patient = ds.createModel('Patient', {
|
||||||
name: String
|
name: String,
|
||||||
});
|
});
|
||||||
|
|
||||||
var Appointment = ds.createModel('Appointment', {
|
var Appointment = ds.createModel('Appointment', {
|
||||||
physicianId: Number,
|
physicianId: Number,
|
||||||
patientId: Number,
|
patientId: Number,
|
||||||
appointmentDate: Date
|
appointmentDate: Date,
|
||||||
});
|
});
|
||||||
|
|
||||||
Appointment.belongsTo(Patient);
|
Appointment.belongsTo(Patient);
|
||||||
Appointment.belongsTo(Physician);
|
Appointment.belongsTo(Physician);
|
||||||
|
|
||||||
Physician.hasMany(Patient, {through: Appointment});
|
Physician.hasMany(Patient, { through: Appointment });
|
||||||
Patient.hasMany(Physician, {through: Appointment});
|
Patient.hasMany(Physician, { through: Appointment });
|
||||||
|
|
||||||
Physician.create({name: 'Dr John'}, function (err, physician1) {
|
Physician.create({ name: 'Dr John' }, function(err, physician1) {
|
||||||
Physician.create({name: 'Dr Smith'}, function (err, physician2) {
|
Physician.create({ name: 'Dr Smith' }, function(err, physician2) {
|
||||||
Patient.create({name: 'Mary'}, function (err, patient1) {
|
Patient.create({ name: 'Mary' }, function(err, patient1) {
|
||||||
Patient.create({name: 'Ben'}, function (err, patient2) {
|
Patient.create({ name: 'Ben' }, function(err, patient2) {
|
||||||
Appointment.create({appointmentDate: new Date(), physicianId: physician1.id, patientId: patient1.id},
|
Appointment.create({ appointmentDate: new Date(), physicianId: physician1.id, patientId: patient1.id },
|
||||||
function (err, appt1) {
|
function(err, appt1) {
|
||||||
Appointment.create({appointmentDate: new Date(), physicianId: physician1.id, patientId: patient2.id},
|
Appointment.create({ appointmentDate: new Date(), physicianId: physician1.id, patientId: patient2.id },
|
||||||
function (err, appt2) {
|
function(err, appt2) {
|
||||||
physician1.patients(console.log);
|
physician1.patients(console.log);
|
||||||
physician1.patients({where: {name: 'Mary'}}, console.log);
|
physician1.patients({ where: { name: 'Mary' }}, console.log);
|
||||||
patient1.physicians(console.log);
|
patient1.physicians(console.log);
|
||||||
|
|
||||||
// Build an appointment?
|
// Build an appointment?
|
||||||
var patient3 = patient1.physicians.build({name: 'Dr X'});
|
var patient3 = patient1.physicians.build({ name: 'Dr X' });
|
||||||
console.log('Physician 3: ', patient3, patient3.constructor.modelName);
|
console.log('Physician 3: ', patient3, patient3.constructor.modelName);
|
||||||
|
|
||||||
// Create a physician?
|
// Create a physician?
|
||||||
patient1.physicians.create({name: 'Dr X'}, function(err, patient4) {
|
patient1.physicians.create({ name: 'Dr X' }, function(err, patient4) {
|
||||||
console.log('Physician 4: ', patient4, patient4.constructor.modelName);
|
console.log('Physician 4: ', patient4, patient4.constructor.modelName);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
@ -116,32 +116,32 @@ Physician.create({name: 'Dr John'}, function (err, physician1) {
|
||||||
});
|
});
|
||||||
|
|
||||||
var Assembly = ds.createModel('Assembly', {
|
var Assembly = ds.createModel('Assembly', {
|
||||||
name: String
|
name: String,
|
||||||
});
|
});
|
||||||
|
|
||||||
var Part = ds.createModel('Part', {
|
var Part = ds.createModel('Part', {
|
||||||
partNumber: String
|
partNumber: String,
|
||||||
});
|
});
|
||||||
|
|
||||||
Assembly.hasAndBelongsToMany(Part);
|
Assembly.hasAndBelongsToMany(Part);
|
||||||
Part.hasAndBelongsToMany(Assembly);
|
Part.hasAndBelongsToMany(Assembly);
|
||||||
|
|
||||||
Assembly.create({name: 'car'}, function (err, assembly) {
|
Assembly.create({ name: 'car' }, function(err, assembly) {
|
||||||
Part.create({partNumber: 'engine'}, function (err, part) {
|
Part.create({ partNumber: 'engine' }, function(err, part) {
|
||||||
assembly.parts.add(part, function (err) {
|
assembly.parts.add(part, function(err) {
|
||||||
assembly.parts(function(err, parts) {
|
assembly.parts(function(err, parts) {
|
||||||
console.log('Parts: ', parts);
|
console.log('Parts: ', parts);
|
||||||
});
|
});
|
||||||
|
|
||||||
// Build an part?
|
// Build an part?
|
||||||
var part3 = assembly.parts.build({partNumber: 'door'});
|
var part3 = assembly.parts.build({ partNumber: 'door' });
|
||||||
console.log('Part3: ', part3, part3.constructor.modelName);
|
console.log('Part3: ', part3, part3.constructor.modelName);
|
||||||
|
|
||||||
// Create a part?
|
// Create a part?
|
||||||
assembly.parts.create({partNumber: 'door'}, function(err, part4) {
|
assembly.parts.create({ partNumber: 'door' }, function(err, part4) {
|
||||||
console.log('Part4: ', part4, part4.constructor.modelName);
|
console.log('Part4: ', part4, part4.constructor.modelName);
|
||||||
|
|
||||||
Assembly.find({include: 'parts'}, function(err, assemblies) {
|
Assembly.find({ include: 'parts' }, function(err, assemblies) {
|
||||||
console.log('Assemblies: ', assemblies);
|
console.log('Assemblies: ', assemblies);
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
4
index.js
4
index.js
|
@ -10,12 +10,12 @@ exports.GeoPoint = require('./lib/geo.js').GeoPoint;
|
||||||
exports.ValidationError = require('./lib/validations.js').ValidationError;
|
exports.ValidationError = require('./lib/validations.js').ValidationError;
|
||||||
|
|
||||||
Object.defineProperty(exports, 'version', {
|
Object.defineProperty(exports, 'version', {
|
||||||
get: function() {return require('./package.json').version;}
|
get: function() { return require('./package.json').version; },
|
||||||
});
|
});
|
||||||
|
|
||||||
var commonTest = './test/common_test';
|
var commonTest = './test/common_test';
|
||||||
Object.defineProperty(exports, 'test', {
|
Object.defineProperty(exports, 'test', {
|
||||||
get: function() {return require(commonTest);}
|
get: function() { return require(commonTest); },
|
||||||
});
|
});
|
||||||
|
|
||||||
exports.Transaction = require('loopback-connector').Transaction;
|
exports.Transaction = require('loopback-connector').Transaction;
|
||||||
|
|
|
@ -49,7 +49,7 @@ Memory.prototype.getTypes = function() {
|
||||||
return ['db', 'nosql', 'memory'];
|
return ['db', 'nosql', 'memory'];
|
||||||
};
|
};
|
||||||
|
|
||||||
Memory.prototype.connect = function (callback) {
|
Memory.prototype.connect = function(callback) {
|
||||||
if (this.isTransaction) {
|
if (this.isTransaction) {
|
||||||
this.onTransactionExec = callback;
|
this.onTransactionExec = callback;
|
||||||
} else {
|
} else {
|
||||||
|
@ -58,17 +58,17 @@ Memory.prototype.connect = function (callback) {
|
||||||
};
|
};
|
||||||
|
|
||||||
function serialize(obj) {
|
function serialize(obj) {
|
||||||
if(obj === null || obj === undefined) {
|
if (obj === null || obj === undefined) {
|
||||||
return obj;
|
return obj;
|
||||||
}
|
}
|
||||||
return JSON.stringify(obj);
|
return JSON.stringify(obj);
|
||||||
}
|
}
|
||||||
|
|
||||||
function deserialize(dbObj) {
|
function deserialize(dbObj) {
|
||||||
if(dbObj === null || dbObj === undefined) {
|
if (dbObj === null || dbObj === undefined) {
|
||||||
return dbObj;
|
return dbObj;
|
||||||
}
|
}
|
||||||
if(typeof dbObj === 'string') {
|
if (typeof dbObj === 'string') {
|
||||||
return JSON.parse(dbObj);
|
return JSON.parse(dbObj);
|
||||||
} else {
|
} else {
|
||||||
return dbObj;
|
return dbObj;
|
||||||
|
@ -81,12 +81,12 @@ Memory.prototype.getCollection = function(model) {
|
||||||
model = modelClass.settings.memory.collection || model;
|
model = modelClass.settings.memory.collection || model;
|
||||||
}
|
}
|
||||||
return model;
|
return model;
|
||||||
}
|
};
|
||||||
|
|
||||||
Memory.prototype.initCollection = function(model) {
|
Memory.prototype.initCollection = function(model) {
|
||||||
this.collection(model, {});
|
this.collection(model, {});
|
||||||
this.collectionSeq(model, 1);
|
this.collectionSeq(model, 1);
|
||||||
}
|
};
|
||||||
|
|
||||||
Memory.prototype.collection = function(model, val) {
|
Memory.prototype.collection = function(model, val) {
|
||||||
model = this.getCollection(model);
|
model = this.getCollection(model);
|
||||||
|
@ -106,14 +106,14 @@ Memory.prototype.loadFromFile = function(callback) {
|
||||||
var localStorage = hasLocalStorage && this.settings.localStorage;
|
var localStorage = hasLocalStorage && this.settings.localStorage;
|
||||||
|
|
||||||
if (self.settings.file) {
|
if (self.settings.file) {
|
||||||
fs.readFile(self.settings.file, {encoding: 'utf8', flag: 'r'}, function (err, data) {
|
fs.readFile(self.settings.file, { encoding: 'utf8', flag: 'r' }, function(err, data) {
|
||||||
if (err && err.code !== 'ENOENT') {
|
if (err && err.code !== 'ENOENT') {
|
||||||
callback && callback(err);
|
callback && callback(err);
|
||||||
} else {
|
} else {
|
||||||
parseAndLoad(data);
|
parseAndLoad(data);
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
} else if(localStorage) {
|
} else if (localStorage) {
|
||||||
var data = window.localStorage.getItem(localStorage);
|
var data = window.localStorage.getItem(localStorage);
|
||||||
data = data || '{}';
|
data = data || '{}';
|
||||||
parseAndLoad(data);
|
parseAndLoad(data);
|
||||||
|
@ -125,14 +125,14 @@ Memory.prototype.loadFromFile = function(callback) {
|
||||||
if (data) {
|
if (data) {
|
||||||
try {
|
try {
|
||||||
data = JSON.parse(data.toString());
|
data = JSON.parse(data.toString());
|
||||||
} catch(e) {
|
} catch (e) {
|
||||||
return callback(e);
|
return callback(e);
|
||||||
}
|
}
|
||||||
|
|
||||||
self.ids = data.ids || {};
|
self.ids = data.ids || {};
|
||||||
self.cache = data.models || {};
|
self.cache = data.models || {};
|
||||||
} else {
|
} else {
|
||||||
if(!self.cache) {
|
if (!self.cache) {
|
||||||
self.ids = {};
|
self.ids = {};
|
||||||
self.cache = {};
|
self.cache = {};
|
||||||
}
|
}
|
||||||
|
@ -145,22 +145,22 @@ Memory.prototype.loadFromFile = function(callback) {
|
||||||
* Flush the cache into the json file if necessary
|
* Flush the cache into the json file if necessary
|
||||||
* @param {Function} callback
|
* @param {Function} callback
|
||||||
*/
|
*/
|
||||||
Memory.prototype.saveToFile = function (result, callback) {
|
Memory.prototype.saveToFile = function(result, callback) {
|
||||||
var self = this;
|
var self = this;
|
||||||
var file = this.settings.file;
|
var file = this.settings.file;
|
||||||
var hasLocalStorage = typeof window !== 'undefined' && window.localStorage;
|
var hasLocalStorage = typeof window !== 'undefined' && window.localStorage;
|
||||||
var localStorage = hasLocalStorage && this.settings.localStorage;
|
var localStorage = hasLocalStorage && this.settings.localStorage;
|
||||||
if (file) {
|
if (file) {
|
||||||
if(!self.writeQueue) {
|
if (!self.writeQueue) {
|
||||||
// Create a queue for writes
|
// Create a queue for writes
|
||||||
self.writeQueue = async.queue(function (task, cb) {
|
self.writeQueue = async.queue(function(task, cb) {
|
||||||
// Flush out the models/ids
|
// Flush out the models/ids
|
||||||
var data = JSON.stringify({
|
var data = JSON.stringify({
|
||||||
ids: self.ids,
|
ids: self.ids,
|
||||||
models: self.cache
|
models: self.cache,
|
||||||
}, null, ' ');
|
}, null, ' ');
|
||||||
|
|
||||||
fs.writeFile(self.settings.file, data, function (err) {
|
fs.writeFile(self.settings.file, data, function(err) {
|
||||||
cb(err);
|
cb(err);
|
||||||
task.callback && task.callback(err, task.data);
|
task.callback && task.callback(err, task.data);
|
||||||
});
|
});
|
||||||
|
@ -169,20 +169,20 @@ Memory.prototype.saveToFile = function (result, callback) {
|
||||||
// Enqueue the write
|
// Enqueue the write
|
||||||
self.writeQueue.push({
|
self.writeQueue.push({
|
||||||
data: result,
|
data: result,
|
||||||
callback: callback
|
callback: callback,
|
||||||
});
|
});
|
||||||
} else if (localStorage) {
|
} else if (localStorage) {
|
||||||
// Flush out the models/ids
|
// Flush out the models/ids
|
||||||
var data = JSON.stringify({
|
var data = JSON.stringify({
|
||||||
ids: self.ids,
|
ids: self.ids,
|
||||||
models: self.cache
|
models: self.cache,
|
||||||
}, null, ' ');
|
}, null, ' ');
|
||||||
window.localStorage.setItem(localStorage, data);
|
window.localStorage.setItem(localStorage, data);
|
||||||
process.nextTick(function () {
|
process.nextTick(function() {
|
||||||
callback && callback(null, result);
|
callback && callback(null, result);
|
||||||
});
|
});
|
||||||
} else {
|
} else {
|
||||||
process.nextTick(function () {
|
process.nextTick(function() {
|
||||||
callback && callback(null, result);
|
callback && callback(null, result);
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
@ -191,7 +191,7 @@ Memory.prototype.saveToFile = function (result, callback) {
|
||||||
Memory.prototype.define = function defineModel(definition) {
|
Memory.prototype.define = function defineModel(definition) {
|
||||||
this.constructor.super_.prototype.define.apply(this, [].slice.call(arguments));
|
this.constructor.super_.prototype.define.apply(this, [].slice.call(arguments));
|
||||||
var m = definition.model.modelName;
|
var m = definition.model.modelName;
|
||||||
if(!this.collection(m)) this.initCollection(m);
|
if (!this.collection(m)) this.initCollection(m);
|
||||||
};
|
};
|
||||||
|
|
||||||
Memory.prototype._createSync = function(model, data, fn) {
|
Memory.prototype._createSync = function(model, data, fn) {
|
||||||
|
@ -235,15 +235,15 @@ Memory.prototype.create = function create(model, data, options, callback) {
|
||||||
});
|
});
|
||||||
};
|
};
|
||||||
|
|
||||||
Memory.prototype.updateOrCreate = function (model, data, options, callback) {
|
Memory.prototype.updateOrCreate = function(model, data, options, callback) {
|
||||||
var self = this;
|
var self = this;
|
||||||
this.exists(model, self.getIdValue(model, data), options, function (err, exists) {
|
this.exists(model, self.getIdValue(model, data), options, function(err, exists) {
|
||||||
if (exists) {
|
if (exists) {
|
||||||
self.save(model, data, options, function(err, data) {
|
self.save(model, data, options, function(err, data) {
|
||||||
callback(err, data, { isNewInstance: false });
|
callback(err, data, { isNewInstance: false });
|
||||||
});
|
});
|
||||||
} else {
|
} else {
|
||||||
self.create(model, data, options, function (err, id) {
|
self.create(model, data, options, function(err, id) {
|
||||||
self.setIdValue(model, data, id);
|
self.setIdValue(model, data, id);
|
||||||
callback(err, data, { isNewInstance: true });
|
callback(err, data, { isNewInstance: true });
|
||||||
});
|
});
|
||||||
|
@ -256,7 +256,7 @@ Memory.prototype.findOrCreate = function(model, filter, data, callback) {
|
||||||
var nodes = self._findAllSkippingIncludes(model, filter);
|
var nodes = self._findAllSkippingIncludes(model, filter);
|
||||||
var found = nodes[0];
|
var found = nodes[0];
|
||||||
|
|
||||||
if(!found) {
|
if (!found) {
|
||||||
// Calling _createSync to update the collection in a sync way and to guarantee to create it in the same turn of even loop
|
// Calling _createSync to update the collection in a sync way and to guarantee to create it in the same turn of even loop
|
||||||
return self._createSync(model, data, function(err, id) {
|
return self._createSync(model, data, function(err, id) {
|
||||||
if (err) return callback(err);
|
if (err) return callback(err);
|
||||||
|
@ -272,7 +272,7 @@ Memory.prototype.findOrCreate = function(model, filter, data, callback) {
|
||||||
callback(null, found, false);
|
callback(null, found, false);
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
self._models[model].model.include(nodes[0], filter.include, {}, function(err, nodes) {
|
self._models[model].model.include(nodes[0], filter.include, {}, function(err, nodes) {
|
||||||
process.nextTick(function() {
|
process.nextTick(function() {
|
||||||
if (err) return callback(err);
|
if (err) return callback(err);
|
||||||
|
@ -297,13 +297,13 @@ Memory.prototype.save = function save(model, data, options, callback) {
|
||||||
};
|
};
|
||||||
|
|
||||||
Memory.prototype.exists = function exists(model, id, options, callback) {
|
Memory.prototype.exists = function exists(model, id, options, callback) {
|
||||||
process.nextTick(function () {
|
process.nextTick(function() {
|
||||||
callback(null, this.collection(model) && this.collection(model).hasOwnProperty(id));
|
callback(null, this.collection(model) && this.collection(model).hasOwnProperty(id));
|
||||||
}.bind(this));
|
}.bind(this));
|
||||||
};
|
};
|
||||||
|
|
||||||
Memory.prototype.find = function find(model, id, options, callback) {
|
Memory.prototype.find = function find(model, id, options, callback) {
|
||||||
process.nextTick(function () {
|
process.nextTick(function() {
|
||||||
callback(null, id in this.collection(model) && this.fromDb(model, this.collection(model)[id]));
|
callback(null, id in this.collection(model) && this.fromDb(model, this.collection(model)[id]));
|
||||||
}.bind(this));
|
}.bind(this));
|
||||||
};
|
};
|
||||||
|
@ -314,7 +314,7 @@ Memory.prototype.destroy = function destroy(model, id, options, callback) {
|
||||||
this.saveToFile({ count: exists ? 1 : 0 }, callback);
|
this.saveToFile({ count: exists ? 1 : 0 }, callback);
|
||||||
};
|
};
|
||||||
|
|
||||||
Memory.prototype.fromDb = function (model, data) {
|
Memory.prototype.fromDb = function(model, data) {
|
||||||
if (!data) return null;
|
if (!data) return null;
|
||||||
data = deserialize(data);
|
data = deserialize(data);
|
||||||
var props = this._models[model].properties;
|
var props = this._models[model].properties;
|
||||||
|
@ -357,7 +357,7 @@ function getValue(obj, path) {
|
||||||
}
|
}
|
||||||
|
|
||||||
Memory.prototype._findAllSkippingIncludes = function(model, filter) {
|
Memory.prototype._findAllSkippingIncludes = function(model, filter) {
|
||||||
var nodes = Object.keys(this.collection(model)).map(function (key) {
|
var nodes = Object.keys(this.collection(model)).map(function(key) {
|
||||||
return this.fromDb(model, this.collection(model)[key]);
|
return this.fromDb(model, this.collection(model)[key]);
|
||||||
}.bind(this));
|
}.bind(this));
|
||||||
|
|
||||||
|
@ -371,17 +371,17 @@ Memory.prototype._findAllSkippingIncludes = function(model, filter) {
|
||||||
// do we need some sorting?
|
// do we need some sorting?
|
||||||
if (filter.order) {
|
if (filter.order) {
|
||||||
var orders = filter.order;
|
var orders = filter.order;
|
||||||
if (typeof filter.order === "string") {
|
if (typeof filter.order === 'string') {
|
||||||
orders = [filter.order];
|
orders = [filter.order];
|
||||||
}
|
}
|
||||||
orders.forEach(function (key, i) {
|
orders.forEach(function(key, i) {
|
||||||
var reverse = 1;
|
var reverse = 1;
|
||||||
var m = key.match(/\s+(A|DE)SC$/i);
|
var m = key.match(/\s+(A|DE)SC$/i);
|
||||||
if (m) {
|
if (m) {
|
||||||
key = key.replace(/\s+(A|DE)SC/i, '');
|
key = key.replace(/\s+(A|DE)SC/i, '');
|
||||||
if (m[1].toLowerCase() === 'de') reverse = -1;
|
if (m[1].toLowerCase() === 'de') reverse = -1;
|
||||||
}
|
}
|
||||||
orders[i] = {"key": key, "reverse": reverse};
|
orders[i] = { 'key': key, 'reverse': reverse };
|
||||||
});
|
});
|
||||||
nodes = nodes.sort(sorting.bind(orders));
|
nodes = nodes.sort(sorting.bind(orders));
|
||||||
}
|
}
|
||||||
|
@ -408,7 +408,7 @@ Memory.prototype._findAllSkippingIncludes = function(model, filter) {
|
||||||
nodes = nodes.slice(skip, skip + limit);
|
nodes = nodes.slice(skip, skip + limit);
|
||||||
}
|
}
|
||||||
return nodes;
|
return nodes;
|
||||||
|
|
||||||
function sorting(a, b) {
|
function sorting(a, b) {
|
||||||
var undefinedA, undefinedB;
|
var undefinedA, undefinedB;
|
||||||
|
|
||||||
|
@ -448,18 +448,18 @@ function applyFilter(filter) {
|
||||||
return where;
|
return where;
|
||||||
}
|
}
|
||||||
var keys = Object.keys(where);
|
var keys = Object.keys(where);
|
||||||
return function (obj) {
|
return function(obj) {
|
||||||
return keys.every(function(key) {
|
return keys.every(function(key) {
|
||||||
if(key === 'and' || key === 'or') {
|
if (key === 'and' || key === 'or') {
|
||||||
if(Array.isArray(where[key])) {
|
if (Array.isArray(where[key])) {
|
||||||
if(key === 'and') {
|
if (key === 'and') {
|
||||||
return where[key].every(function(cond) {
|
return where[key].every(function(cond) {
|
||||||
return applyFilter({where: cond})(obj);
|
return applyFilter({ where: cond })(obj);
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
if(key === 'or') {
|
if (key === 'or') {
|
||||||
return where[key].some(function(cond) {
|
return where[key].some(function(cond) {
|
||||||
return applyFilter({where: cond})(obj);
|
return applyFilter({ where: cond })(obj);
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -475,8 +475,8 @@ function applyFilter(filter) {
|
||||||
if (matcher.neq !== undefined && value.length <= 0) {
|
if (matcher.neq !== undefined && value.length <= 0) {
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
return value.some(function (v, i) {
|
return value.some(function(v, i) {
|
||||||
var filter = {where: {}};
|
var filter = { where: {}};
|
||||||
filter.where[i] = matcher;
|
filter.where[i] = matcher;
|
||||||
return applyFilter(filter)(value);
|
return applyFilter(filter)(value);
|
||||||
});
|
});
|
||||||
|
@ -492,15 +492,15 @@ function applyFilter(filter) {
|
||||||
var dotIndex = key.indexOf('.');
|
var dotIndex = key.indexOf('.');
|
||||||
var subValue = obj[key.substring(0, dotIndex)];
|
var subValue = obj[key.substring(0, dotIndex)];
|
||||||
if (dotIndex !== -1 && Array.isArray(subValue)) {
|
if (dotIndex !== -1 && Array.isArray(subValue)) {
|
||||||
var subFilter = {where: {}};
|
var subFilter = { where: {}};
|
||||||
var subKey = key.substring(dotIndex+1);
|
var subKey = key.substring(dotIndex + 1);
|
||||||
subFilter.where[subKey] = where[key];
|
subFilter.where[subKey] = where[key];
|
||||||
return subValue.some(applyFilter(subFilter));
|
return subValue.some(applyFilter(subFilter));
|
||||||
}
|
}
|
||||||
|
|
||||||
return false;
|
return false;
|
||||||
});
|
});
|
||||||
}
|
};
|
||||||
|
|
||||||
function toRegExp(pattern) {
|
function toRegExp(pattern) {
|
||||||
if (pattern instanceof RegExp) {
|
if (pattern instanceof RegExp) {
|
||||||
|
@ -509,7 +509,7 @@ function applyFilter(filter) {
|
||||||
var regex = '';
|
var regex = '';
|
||||||
// Escaping user input to be treated as a literal string within a regular expression
|
// Escaping user input to be treated as a literal string within a regular expression
|
||||||
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions#Writing_a_Regular_Expression_Pattern
|
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions#Writing_a_Regular_Expression_Pattern
|
||||||
pattern = pattern.replace(/([.*+?^=!:${}()|\[\]\/\\])/g, "\\$1");
|
pattern = pattern.replace(/([.*+?^=!:${}()|\[\]\/\\])/g, '\\$1');
|
||||||
for (var i = 0, n = pattern.length; i < n; i++) {
|
for (var i = 0, n = pattern.length; i < n; i++) {
|
||||||
var char = pattern.charAt(i);
|
var char = pattern.charAt(i);
|
||||||
if (char === '\\') {
|
if (char === '\\') {
|
||||||
|
@ -567,9 +567,9 @@ function applyFilter(filter) {
|
||||||
return compare(example.neq, value) !== 0;
|
return compare(example.neq, value) !== 0;
|
||||||
}
|
}
|
||||||
|
|
||||||
if ('between' in example ) {
|
if ('between' in example) {
|
||||||
return ( testInEquality({gte:example.between[0]}, value) &&
|
return (testInEquality({ gte:example.between[0] }, value) &&
|
||||||
testInEquality({lte:example.between[1]}, value) );
|
testInEquality({ lte:example.between[1] }, value));
|
||||||
}
|
}
|
||||||
|
|
||||||
if (example.like || example.nlike) {
|
if (example.like || example.nlike) {
|
||||||
|
@ -604,7 +604,7 @@ function applyFilter(filter) {
|
||||||
* @private
|
* @private
|
||||||
*/
|
*/
|
||||||
function compare(val1, val2) {
|
function compare(val1, val2) {
|
||||||
if(val1 == null || val2 == null) {
|
if (val1 == null || val2 == null) {
|
||||||
// Either val1 or val2 is null or undefined
|
// Either val1 or val2 is null or undefined
|
||||||
return val1 == val2 ? 0 : NaN;
|
return val1 == val2 ? 0 : NaN;
|
||||||
}
|
}
|
||||||
|
@ -647,8 +647,8 @@ Memory.prototype.destroyAll = function destroyAll(model, where, options, callbac
|
||||||
var filter = null;
|
var filter = null;
|
||||||
var count = 0;
|
var count = 0;
|
||||||
if (where) {
|
if (where) {
|
||||||
filter = applyFilter({where: where});
|
filter = applyFilter({ where: where });
|
||||||
Object.keys(cache).forEach(function (id) {
|
Object.keys(cache).forEach(function(id) {
|
||||||
if (!filter || filter(this.fromDb(model, cache[id]))) {
|
if (!filter || filter(this.fromDb(model, cache[id]))) {
|
||||||
count++;
|
count++;
|
||||||
delete cache[id];
|
delete cache[id];
|
||||||
|
@ -665,13 +665,13 @@ Memory.prototype.count = function count(model, where, options, callback) {
|
||||||
var cache = this.collection(model);
|
var cache = this.collection(model);
|
||||||
var data = Object.keys(cache);
|
var data = Object.keys(cache);
|
||||||
if (where) {
|
if (where) {
|
||||||
var filter = {where: where};
|
var filter = { where: where };
|
||||||
data = data.map(function (id) {
|
data = data.map(function(id) {
|
||||||
return this.fromDb(model, cache[id]);
|
return this.fromDb(model, cache[id]);
|
||||||
}.bind(this));
|
}.bind(this));
|
||||||
data = data.filter(applyFilter(filter));
|
data = data.filter(applyFilter(filter));
|
||||||
}
|
}
|
||||||
process.nextTick(function () {
|
process.nextTick(function() {
|
||||||
callback(null, data.length);
|
callback(null, data.length);
|
||||||
});
|
});
|
||||||
};
|
};
|
||||||
|
@ -682,11 +682,11 @@ Memory.prototype.update =
|
||||||
var cache = this.collection(model);
|
var cache = this.collection(model);
|
||||||
var filter = null;
|
var filter = null;
|
||||||
where = where || {};
|
where = where || {};
|
||||||
filter = applyFilter({where: where});
|
filter = applyFilter({ where: where });
|
||||||
|
|
||||||
var ids = Object.keys(cache);
|
var ids = Object.keys(cache);
|
||||||
var count = 0;
|
var count = 0;
|
||||||
async.each(ids, function (id, done) {
|
async.each(ids, function(id, done) {
|
||||||
var inst = self.fromDb(model, cache[id]);
|
var inst = self.fromDb(model, cache[id]);
|
||||||
if (!filter || filter(inst)) {
|
if (!filter || filter(inst)) {
|
||||||
count++;
|
count++;
|
||||||
|
@ -697,9 +697,9 @@ Memory.prototype.update =
|
||||||
} else {
|
} else {
|
||||||
process.nextTick(done);
|
process.nextTick(done);
|
||||||
}
|
}
|
||||||
}, function (err) {
|
}, function(err) {
|
||||||
if (err) return cb(err);
|
if (err) return cb(err);
|
||||||
self.saveToFile({count: count}, cb);
|
self.saveToFile({ count: count }, cb);
|
||||||
});
|
});
|
||||||
};
|
};
|
||||||
|
|
||||||
|
@ -745,16 +745,16 @@ Memory.prototype.replaceById = function(model, id, data, options, cb) {
|
||||||
}
|
}
|
||||||
|
|
||||||
var newModelData = {};
|
var newModelData = {};
|
||||||
for(var key in data) {
|
for (var key in data) {
|
||||||
var val = data[key];
|
var val = data[key];
|
||||||
if(typeof val === 'function') {
|
if (typeof val === 'function') {
|
||||||
continue; // Skip methods
|
continue; // Skip methods
|
||||||
}
|
}
|
||||||
newModelData[key] = val;
|
newModelData[key] = val;
|
||||||
}
|
}
|
||||||
|
|
||||||
this.collection(model)[id] = serialize(newModelData);
|
this.collection(model)[id] = serialize(newModelData);
|
||||||
this.saveToFile(newModelData, function (err) {
|
this.saveToFile(newModelData, function(err) {
|
||||||
cb(err, self.fromDb(model, newModelData));
|
cb(err, self.fromDb(model, newModelData));
|
||||||
});
|
});
|
||||||
};
|
};
|
||||||
|
@ -763,13 +763,13 @@ Memory.prototype.replaceOrCreate = function(model, data, options, callback) {
|
||||||
var self = this;
|
var self = this;
|
||||||
var idName = self.idNames(model)[0];
|
var idName = self.idNames(model)[0];
|
||||||
var idValue = self.getIdValue(model, data);
|
var idValue = self.getIdValue(model, data);
|
||||||
var filter = {where: {}};
|
var filter = { where: {}};
|
||||||
filter.where[idName] = idValue;
|
filter.where[idName] = idValue;
|
||||||
var nodes = self._findAllSkippingIncludes(model, filter);
|
var nodes = self._findAllSkippingIncludes(model, filter);
|
||||||
var found = nodes[0];
|
var found = nodes[0];
|
||||||
|
|
||||||
if (!found) {
|
if (!found) {
|
||||||
// Calling _createSync to update the collection in a sync way and
|
// Calling _createSync to update the collection in a sync way and
|
||||||
// to guarantee to create it in the same turn of even loop
|
// to guarantee to create it in the same turn of even loop
|
||||||
return self._createSync(model, data, function(err, id) {
|
return self._createSync(model, data, function(err, id) {
|
||||||
if (err) return process.nextTick(function() { cb(err); });
|
if (err) return process.nextTick(function() { cb(err); });
|
||||||
|
@ -782,24 +782,24 @@ Memory.prototype.replaceOrCreate = function(model, data, options, callback) {
|
||||||
var id = self.getIdValue(model, data);
|
var id = self.getIdValue(model, data);
|
||||||
self.collection(model)[id] = serialize(data);
|
self.collection(model)[id] = serialize(data);
|
||||||
self.saveToFile(data, function(err) {
|
self.saveToFile(data, function(err) {
|
||||||
callback(err, self.fromDb(model, data), {isNewInstance: false});
|
callback(err, self.fromDb(model, data), { isNewInstance: false });
|
||||||
});
|
});
|
||||||
};
|
};
|
||||||
|
|
||||||
Memory.prototype.transaction = function () {
|
Memory.prototype.transaction = function() {
|
||||||
return new Memory(this);
|
return new Memory(this);
|
||||||
};
|
};
|
||||||
|
|
||||||
Memory.prototype.exec = function (callback) {
|
Memory.prototype.exec = function(callback) {
|
||||||
this.onTransactionExec();
|
this.onTransactionExec();
|
||||||
setTimeout(callback, 50);
|
setTimeout(callback, 50);
|
||||||
};
|
};
|
||||||
|
|
||||||
Memory.prototype.buildNearFilter = function (filter) {
|
Memory.prototype.buildNearFilter = function(filter) {
|
||||||
// noop
|
// noop
|
||||||
}
|
};
|
||||||
|
|
||||||
Memory.prototype.automigrate = function (models, cb) {
|
Memory.prototype.automigrate = function(models, cb) {
|
||||||
var self = this;
|
var self = this;
|
||||||
|
|
||||||
if ((!cb) && ('function' === typeof models)) {
|
if ((!cb) && ('function' === typeof models)) {
|
||||||
|
@ -831,7 +831,7 @@ Memory.prototype.automigrate = function (models, cb) {
|
||||||
self.initCollection(m);
|
self.initCollection(m);
|
||||||
});
|
});
|
||||||
if (cb) process.nextTick(cb);
|
if (cb) process.nextTick(cb);
|
||||||
}
|
};
|
||||||
|
|
||||||
function merge(base, update) {
|
function merge(base, update) {
|
||||||
if (!base) {
|
if (!base) {
|
||||||
|
@ -839,9 +839,9 @@ function merge(base, update) {
|
||||||
}
|
}
|
||||||
// We cannot use Object.keys(update) if the update is an instance of the model
|
// We cannot use Object.keys(update) if the update is an instance of the model
|
||||||
// class as the properties are defined at the ModelClass.prototype level
|
// class as the properties are defined at the ModelClass.prototype level
|
||||||
for(var key in update) {
|
for (var key in update) {
|
||||||
var val = update[key];
|
var val = update[key];
|
||||||
if(typeof val === 'function') {
|
if (typeof val === 'function') {
|
||||||
continue; // Skip methods
|
continue; // Skip methods
|
||||||
}
|
}
|
||||||
base[key] = val;
|
base[key] = val;
|
||||||
|
|
|
@ -47,7 +47,7 @@ Transient.prototype.getTypes = function() {
|
||||||
return ['db', 'nosql', 'transient'];
|
return ['db', 'nosql', 'transient'];
|
||||||
};
|
};
|
||||||
|
|
||||||
Transient.prototype.connect = function (callback) {
|
Transient.prototype.connect = function(callback) {
|
||||||
if (this.isTransaction) {
|
if (this.isTransaction) {
|
||||||
this.onTransactionExec = callback;
|
this.onTransactionExec = callback;
|
||||||
} else {
|
} else {
|
||||||
|
@ -63,26 +63,26 @@ Transient.prototype.generateId = function(model, data, idName) {
|
||||||
if (idType === Number) {
|
if (idType === Number) {
|
||||||
return Math.floor(Math.random() * 10000); // max. 4 digits
|
return Math.floor(Math.random() * 10000); // max. 4 digits
|
||||||
} else {
|
} else {
|
||||||
return crypto.randomBytes(Math.ceil(24/2))
|
return crypto.randomBytes(Math.ceil(24 / 2))
|
||||||
.toString('hex') // convert to hexadecimal format
|
.toString('hex') // convert to hexadecimal format
|
||||||
.slice(0, 24); // return required number of characters
|
.slice(0, 24); // return required number of characters
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
Transient.prototype.exists = function exists(model, id, callback) {
|
Transient.prototype.exists = function exists(model, id, callback) {
|
||||||
process.nextTick(function () { callback(null, false); }.bind(this));
|
process.nextTick(function() { callback(null, false); }.bind(this));
|
||||||
};
|
};
|
||||||
|
|
||||||
Transient.prototype.find = function find(model, id, callback) {
|
Transient.prototype.find = function find(model, id, callback) {
|
||||||
process.nextTick(function () { callback(null, null); }.bind(this));
|
process.nextTick(function() { callback(null, null); }.bind(this));
|
||||||
};
|
};
|
||||||
|
|
||||||
Transient.prototype.all = function all(model, filter, callback) {
|
Transient.prototype.all = function all(model, filter, callback) {
|
||||||
process.nextTick(function () { callback(null, []); });
|
process.nextTick(function() { callback(null, []); });
|
||||||
};
|
};
|
||||||
|
|
||||||
Transient.prototype.count = function count(model, callback, where) {
|
Transient.prototype.count = function count(model, callback, where) {
|
||||||
process.nextTick(function () { callback(null, 0); });
|
process.nextTick(function() { callback(null, 0); });
|
||||||
};
|
};
|
||||||
|
|
||||||
Transient.prototype.create = function create(model, data, callback) {
|
Transient.prototype.create = function create(model, data, callback) {
|
||||||
|
@ -103,8 +103,8 @@ Transient.prototype.save = function save(model, data, callback) {
|
||||||
Transient.prototype.update =
|
Transient.prototype.update =
|
||||||
Transient.prototype.updateAll = function updateAll(model, where, data, cb) {
|
Transient.prototype.updateAll = function updateAll(model, where, data, cb) {
|
||||||
var count = 0;
|
var count = 0;
|
||||||
this.flush('update', {count: count}, cb);
|
this.flush('update', { count: count }, cb);
|
||||||
};
|
};
|
||||||
|
|
||||||
Transient.prototype.updateAttributes = function updateAttributes(model, id, data, cb) {
|
Transient.prototype.updateAttributes = function updateAttributes(model, id, data, cb) {
|
||||||
if (!id) {
|
if (!id) {
|
||||||
|
@ -136,15 +136,15 @@ Transient.prototype.destroyAll = function destroyAll(model, where, callback) {
|
||||||
* Flush the cache - noop.
|
* Flush the cache - noop.
|
||||||
* @param {Function} callback
|
* @param {Function} callback
|
||||||
*/
|
*/
|
||||||
Transient.prototype.flush = function (action, result, callback) {
|
Transient.prototype.flush = function(action, result, callback) {
|
||||||
process.nextTick(function () { callback && callback(null, result); });
|
process.nextTick(function() { callback && callback(null, result); });
|
||||||
};
|
};
|
||||||
|
|
||||||
Transient.prototype.transaction = function () {
|
Transient.prototype.transaction = function() {
|
||||||
return new Transient(this);
|
return new Transient(this);
|
||||||
};
|
};
|
||||||
|
|
||||||
Transient.prototype.exec = function (callback) {
|
Transient.prototype.exec = function(callback) {
|
||||||
this.onTransactionExec();
|
this.onTransactionExec();
|
||||||
setTimeout(callback, 50);
|
setTimeout(callback, 50);
|
||||||
};
|
};
|
||||||
|
|
318
lib/dao.js
318
lib/dao.js
File diff suppressed because it is too large
Load Diff
|
@ -120,11 +120,11 @@ function DataSource(name, settings, modelBuilder) {
|
||||||
|
|
||||||
// DataAccessObject - connector defined or supply the default
|
// DataAccessObject - connector defined or supply the default
|
||||||
var dao = (connector && connector.DataAccessObject) || this.constructor.DataAccessObject;
|
var dao = (connector && connector.DataAccessObject) || this.constructor.DataAccessObject;
|
||||||
this.DataAccessObject = function () {
|
this.DataAccessObject = function() {
|
||||||
};
|
};
|
||||||
|
|
||||||
// define DataAccessObject methods
|
// define DataAccessObject methods
|
||||||
Object.keys(dao).forEach(function (name) {
|
Object.keys(dao).forEach(function(name) {
|
||||||
var fn = dao[name];
|
var fn = dao[name];
|
||||||
this.DataAccessObject[name] = fn;
|
this.DataAccessObject[name] = fn;
|
||||||
|
|
||||||
|
@ -135,13 +135,13 @@ function DataSource(name, settings, modelBuilder) {
|
||||||
http: fn.http,
|
http: fn.http,
|
||||||
remoteEnabled: fn.shared ? true : false,
|
remoteEnabled: fn.shared ? true : false,
|
||||||
scope: this.DataAccessObject,
|
scope: this.DataAccessObject,
|
||||||
fnName: name
|
fnName: name,
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
}.bind(this));
|
}.bind(this));
|
||||||
|
|
||||||
// define DataAccessObject.prototype methods
|
// define DataAccessObject.prototype methods
|
||||||
Object.keys(dao.prototype).forEach(function (name) {
|
Object.keys(dao.prototype).forEach(function(name) {
|
||||||
var fn = dao.prototype[name];
|
var fn = dao.prototype[name];
|
||||||
this.DataAccessObject.prototype[name] = fn;
|
this.DataAccessObject.prototype[name] = fn;
|
||||||
if (typeof fn === 'function') {
|
if (typeof fn === 'function') {
|
||||||
|
@ -152,7 +152,7 @@ function DataSource(name, settings, modelBuilder) {
|
||||||
http: fn.http,
|
http: fn.http,
|
||||||
remoteEnabled: fn.shared ? true : false,
|
remoteEnabled: fn.shared ? true : false,
|
||||||
scope: this.DataAccessObject.prototype,
|
scope: this.DataAccessObject.prototype,
|
||||||
fnName: name
|
fnName: name,
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
}.bind(this));
|
}.bind(this));
|
||||||
|
@ -168,7 +168,7 @@ DataSource.DataAccessObject = DataAccessObject;
|
||||||
* Set up the connector instance for backward compatibility with JugglingDB schema/adapter
|
* Set up the connector instance for backward compatibility with JugglingDB schema/adapter
|
||||||
* @private
|
* @private
|
||||||
*/
|
*/
|
||||||
DataSource.prototype._setupConnector = function () {
|
DataSource.prototype._setupConnector = function() {
|
||||||
this.connector = this.connector || this.adapter; // The legacy JugglingDB adapter will set up `adapter` property
|
this.connector = this.connector || this.adapter; // The legacy JugglingDB adapter will set up `adapter` property
|
||||||
this.adapter = this.connector; // Keep the adapter as an alias to connector
|
this.adapter = this.connector; // Keep the adapter as an alias to connector
|
||||||
if (this.connector) {
|
if (this.connector) {
|
||||||
|
@ -177,14 +177,14 @@ DataSource.prototype._setupConnector = function () {
|
||||||
this.connector.dataSource = this;
|
this.connector.dataSource = this;
|
||||||
}
|
}
|
||||||
var dataSource = this;
|
var dataSource = this;
|
||||||
this.connector.log = function (query, start) {
|
this.connector.log = function(query, start) {
|
||||||
dataSource.log(query, start);
|
dataSource.log(query, start);
|
||||||
};
|
};
|
||||||
|
|
||||||
this.connector.logger = function (query) {
|
this.connector.logger = function(query) {
|
||||||
var t1 = Date.now();
|
var t1 = Date.now();
|
||||||
var log = this.log;
|
var log = this.log;
|
||||||
return function (q) {
|
return function(q) {
|
||||||
log(q || query, t1);
|
log(q || query, t1);
|
||||||
};
|
};
|
||||||
};
|
};
|
||||||
|
@ -233,7 +233,7 @@ function tryModules(names, loader) {
|
||||||
* @returns {*}
|
* @returns {*}
|
||||||
* @private
|
* @private
|
||||||
*/
|
*/
|
||||||
DataSource._resolveConnector = function (name, loader) {
|
DataSource._resolveConnector = function(name, loader) {
|
||||||
var names = connectorModuleNames(name);
|
var names = connectorModuleNames(name);
|
||||||
var connector = tryModules(names, loader);
|
var connector = tryModules(names, loader);
|
||||||
var error = null;
|
var error = null;
|
||||||
|
@ -244,7 +244,7 @@ DataSource._resolveConnector = function (name, loader) {
|
||||||
}
|
}
|
||||||
return {
|
return {
|
||||||
connector: connector,
|
connector: connector,
|
||||||
error: error
|
error: error,
|
||||||
};
|
};
|
||||||
};
|
};
|
||||||
|
|
||||||
|
@ -255,7 +255,7 @@ DataSource._resolveConnector = function (name, loader) {
|
||||||
* @returns {*}
|
* @returns {*}
|
||||||
* @private
|
* @private
|
||||||
*/
|
*/
|
||||||
DataSource.prototype.setup = function (name, settings) {
|
DataSource.prototype.setup = function(name, settings) {
|
||||||
var dataSource = this;
|
var dataSource = this;
|
||||||
var connector;
|
var connector;
|
||||||
|
|
||||||
|
@ -341,7 +341,7 @@ DataSource.prototype.setup = function (name, settings) {
|
||||||
this.connector = new connector(this.settings);
|
this.connector = new connector(this.settings);
|
||||||
postInit();
|
postInit();
|
||||||
}
|
}
|
||||||
} catch(err) {
|
} catch (err) {
|
||||||
if (err.message) {
|
if (err.message) {
|
||||||
err.message = 'Cannot initialize connector ' +
|
err.message = 'Cannot initialize connector ' +
|
||||||
JSON.stringify(connector.name || name) + ': ' +
|
JSON.stringify(connector.name || name) + ': ' +
|
||||||
|
@ -351,17 +351,17 @@ DataSource.prototype.setup = function (name, settings) {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
dataSource.connect = function (cb) {
|
dataSource.connect = function(cb) {
|
||||||
var dataSource = this;
|
var dataSource = this;
|
||||||
if (dataSource.connected || dataSource.connecting) {
|
if (dataSource.connected || dataSource.connecting) {
|
||||||
process.nextTick(function () {
|
process.nextTick(function() {
|
||||||
cb && cb();
|
cb && cb();
|
||||||
});
|
});
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
dataSource.connecting = true;
|
dataSource.connecting = true;
|
||||||
if (dataSource.connector.connect) {
|
if (dataSource.connector.connect) {
|
||||||
dataSource.connector.connect(function (err, result) {
|
dataSource.connector.connect(function(err, result) {
|
||||||
if (!err) {
|
if (!err) {
|
||||||
dataSource.connected = true;
|
dataSource.connected = true;
|
||||||
dataSource.connecting = false;
|
dataSource.connecting = false;
|
||||||
|
@ -374,7 +374,7 @@ DataSource.prototype.setup = function (name, settings) {
|
||||||
cb && cb(err, result);
|
cb && cb(err, result);
|
||||||
});
|
});
|
||||||
} else {
|
} else {
|
||||||
process.nextTick(function () {
|
process.nextTick(function() {
|
||||||
dataSource.connected = true;
|
dataSource.connected = true;
|
||||||
dataSource.connecting = false;
|
dataSource.connecting = false;
|
||||||
dataSource.emit('connected');
|
dataSource.emit('connected');
|
||||||
|
@ -402,7 +402,7 @@ function isModelDataSourceAttached(model) {
|
||||||
* @param modelClass
|
* @param modelClass
|
||||||
* @param scopes
|
* @param scopes
|
||||||
*/
|
*/
|
||||||
DataSource.prototype.defineScopes = function (modelClass, scopes) {
|
DataSource.prototype.defineScopes = function(modelClass, scopes) {
|
||||||
if (scopes) {
|
if (scopes) {
|
||||||
for (var s in scopes) {
|
for (var s in scopes) {
|
||||||
defineScope(modelClass, modelClass, s, scopes[s], {}, scopes[s].options);
|
defineScope(modelClass, modelClass, s, scopes[s], {}, scopes[s].options);
|
||||||
|
@ -415,13 +415,13 @@ DataSource.prototype.defineScopes = function (modelClass, scopes) {
|
||||||
* @param modelClass
|
* @param modelClass
|
||||||
* @param relations
|
* @param relations
|
||||||
*/
|
*/
|
||||||
DataSource.prototype.defineRelations = function (modelClass, relations) {
|
DataSource.prototype.defineRelations = function(modelClass, relations) {
|
||||||
var self = this;
|
var self = this;
|
||||||
|
|
||||||
// Create a function for the closure in the loop
|
// Create a function for the closure in the loop
|
||||||
var createListener = function (name, relation, targetModel, throughModel) {
|
var createListener = function(name, relation, targetModel, throughModel) {
|
||||||
if (!isModelDataSourceAttached(targetModel)) {
|
if (!isModelDataSourceAttached(targetModel)) {
|
||||||
targetModel.once('dataAccessConfigured', function (model) {
|
targetModel.once('dataAccessConfigured', function(model) {
|
||||||
// Check if the through model doesn't exist or resolved
|
// Check if the through model doesn't exist or resolved
|
||||||
if (!throughModel || isModelDataSourceAttached(throughModel)) {
|
if (!throughModel || isModelDataSourceAttached(throughModel)) {
|
||||||
// The target model is resolved
|
// The target model is resolved
|
||||||
|
@ -438,7 +438,7 @@ DataSource.prototype.defineRelations = function (modelClass, relations) {
|
||||||
}
|
}
|
||||||
if (throughModel && !isModelDataSourceAttached(throughModel)) {
|
if (throughModel && !isModelDataSourceAttached(throughModel)) {
|
||||||
// Set up a listener to the through model
|
// Set up a listener to the through model
|
||||||
throughModel.once('dataAccessConfigured', function (model) {
|
throughModel.once('dataAccessConfigured', function(model) {
|
||||||
if (isModelDataSourceAttached(targetModel)) {
|
if (isModelDataSourceAttached(targetModel)) {
|
||||||
// The target model is resolved
|
// The target model is resolved
|
||||||
var params = traverse(relation).clone();
|
var params = traverse(relation).clone();
|
||||||
|
@ -453,9 +453,9 @@ DataSource.prototype.defineRelations = function (modelClass, relations) {
|
||||||
|
|
||||||
// Set up the relations
|
// Set up the relations
|
||||||
if (relations) {
|
if (relations) {
|
||||||
Object.keys(relations).forEach(function (rn) {
|
Object.keys(relations).forEach(function(rn) {
|
||||||
var r = relations[rn];
|
var r = relations[rn];
|
||||||
assert(DataSource.relationTypes.indexOf(r.type) !== -1, "Invalid relation type: " + r.type);
|
assert(DataSource.relationTypes.indexOf(r.type) !== -1, 'Invalid relation type: ' + r.type);
|
||||||
var targetModel, polymorphicName;
|
var targetModel, polymorphicName;
|
||||||
|
|
||||||
if (r.polymorphic && r.type !== 'belongsTo' && !r.model) {
|
if (r.polymorphic && r.type !== 'belongsTo' && !r.model) {
|
||||||
|
@ -503,7 +503,7 @@ DataSource.prototype.defineRelations = function (modelClass, relations) {
|
||||||
* @param {Model} modelClass The model class
|
* @param {Model} modelClass The model class
|
||||||
* @param {Object} settings The settings object
|
* @param {Object} settings The settings object
|
||||||
*/
|
*/
|
||||||
DataSource.prototype.setupDataAccess = function (modelClass, settings) {
|
DataSource.prototype.setupDataAccess = function(modelClass, settings) {
|
||||||
if (this.connector) {
|
if (this.connector) {
|
||||||
// Check if the id property should be generated
|
// Check if the id property should be generated
|
||||||
var idName = modelClass.definition.idName();
|
var idName = modelClass.definition.idName();
|
||||||
|
@ -515,7 +515,7 @@ DataSource.prototype.setupDataAccess = function (modelClass, settings) {
|
||||||
modelClass.definition.rawProperties[idName].type = idType;
|
modelClass.definition.rawProperties[idName].type = idType;
|
||||||
modelClass.definition.properties[idName].type = idType;
|
modelClass.definition.properties[idName].type = idType;
|
||||||
if (settings.forceId) {
|
if (settings.forceId) {
|
||||||
modelClass.validatesAbsenceOf(idName, {if: 'isNewRecord'});
|
modelClass.validatesAbsenceOf(idName, { if: 'isNewRecord' });
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
if (this.connector.define) {
|
if (this.connector.define) {
|
||||||
|
@ -523,7 +523,7 @@ DataSource.prototype.setupDataAccess = function (modelClass, settings) {
|
||||||
this.connector.define({
|
this.connector.define({
|
||||||
model: modelClass,
|
model: modelClass,
|
||||||
properties: modelClass.definition.properties,
|
properties: modelClass.definition.properties,
|
||||||
settings: settings
|
settings: settings,
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -642,15 +642,15 @@ DataSource.prototype.createModel = DataSource.prototype.define = function define
|
||||||
* @private
|
* @private
|
||||||
*/
|
*/
|
||||||
|
|
||||||
DataSource.prototype.mixin = function (ModelCtor) {
|
DataSource.prototype.mixin = function(ModelCtor) {
|
||||||
var ops = this.operations();
|
var ops = this.operations();
|
||||||
var DAO = this.DataAccessObject;
|
var DAO = this.DataAccessObject;
|
||||||
|
|
||||||
// mixin DAO
|
// mixin DAO
|
||||||
jutil.mixin(ModelCtor, DAO, {proxyFunctions: true, override: true});
|
jutil.mixin(ModelCtor, DAO, { proxyFunctions: true, override: true });
|
||||||
|
|
||||||
// decorate operations as alias functions
|
// decorate operations as alias functions
|
||||||
Object.keys(ops).forEach(function (name) {
|
Object.keys(ops).forEach(function(name) {
|
||||||
var op = ops[name];
|
var op = ops[name];
|
||||||
var scope;
|
var scope;
|
||||||
|
|
||||||
|
@ -660,15 +660,15 @@ DataSource.prototype.mixin = function (ModelCtor) {
|
||||||
// op.scope[op.fnName].apply(self, arguments);
|
// op.scope[op.fnName].apply(self, arguments);
|
||||||
// }
|
// }
|
||||||
Object.keys(op)
|
Object.keys(op)
|
||||||
.filter(function (key) {
|
.filter(function(key) {
|
||||||
// filter out the following keys
|
// filter out the following keys
|
||||||
return ~[
|
return ~[
|
||||||
'scope',
|
'scope',
|
||||||
'fnName',
|
'fnName',
|
||||||
'prototype'
|
'prototype',
|
||||||
].indexOf(key);
|
].indexOf(key);
|
||||||
})
|
})
|
||||||
.forEach(function (key) {
|
.forEach(function(key) {
|
||||||
if (typeof op[key] !== 'undefined') {
|
if (typeof op[key] !== 'undefined') {
|
||||||
op.scope[op.fnName][key] = op[key];
|
op.scope[op.fnName][key] = op[key];
|
||||||
}
|
}
|
||||||
|
@ -680,14 +680,14 @@ DataSource.prototype.mixin = function (ModelCtor) {
|
||||||
/**
|
/**
|
||||||
* See ModelBuilder.getModel
|
* See ModelBuilder.getModel
|
||||||
*/
|
*/
|
||||||
DataSource.prototype.getModel = function (name, forceCreate) {
|
DataSource.prototype.getModel = function(name, forceCreate) {
|
||||||
return this.modelBuilder.getModel(name, forceCreate);
|
return this.modelBuilder.getModel(name, forceCreate);
|
||||||
};
|
};
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* See ModelBuilder.getModelDefinition
|
* See ModelBuilder.getModelDefinition
|
||||||
*/
|
*/
|
||||||
DataSource.prototype.getModelDefinition = function (name) {
|
DataSource.prototype.getModelDefinition = function(name) {
|
||||||
return this.modelBuilder.getModelDefinition(name);
|
return this.modelBuilder.getModelDefinition(name);
|
||||||
};
|
};
|
||||||
|
|
||||||
|
@ -696,7 +696,7 @@ DataSource.prototype.getModelDefinition = function (name) {
|
||||||
* @returns {String[]} The data source type, such as ['db', 'nosql', 'mongodb'],
|
* @returns {String[]} The data source type, such as ['db', 'nosql', 'mongodb'],
|
||||||
* ['rest'], or ['db', 'rdbms', 'mysql']
|
* ['rest'], or ['db', 'rdbms', 'mysql']
|
||||||
*/
|
*/
|
||||||
DataSource.prototype.getTypes = function () {
|
DataSource.prototype.getTypes = function() {
|
||||||
var getTypes = this.connector && this.connector.getTypes;
|
var getTypes = this.connector && this.connector.getTypes;
|
||||||
var types = getTypes && getTypes() || [];
|
var types = getTypes && getTypes() || [];
|
||||||
if (typeof types === 'string') {
|
if (typeof types === 'string') {
|
||||||
|
@ -710,7 +710,7 @@ DataSource.prototype.getTypes = function () {
|
||||||
* @param {String} types Type name or an array of type names. Can also be array of Strings.
|
* @param {String} types Type name or an array of type names. Can also be array of Strings.
|
||||||
* @returns {Boolean} true if all types are supported by the data source
|
* @returns {Boolean} true if all types are supported by the data source
|
||||||
*/
|
*/
|
||||||
DataSource.prototype.supportTypes = function (types) {
|
DataSource.prototype.supportTypes = function(types) {
|
||||||
var supportedTypes = this.getTypes();
|
var supportedTypes = this.getTypes();
|
||||||
if (Array.isArray(types)) {
|
if (Array.isArray(types)) {
|
||||||
// Check each of the types
|
// Check each of the types
|
||||||
|
@ -733,7 +733,7 @@ DataSource.prototype.supportTypes = function (types) {
|
||||||
* @param {Function} modelClass The model constructor
|
* @param {Function} modelClass The model constructor
|
||||||
*/
|
*/
|
||||||
|
|
||||||
DataSource.prototype.attach = function (modelClass) {
|
DataSource.prototype.attach = function(modelClass) {
|
||||||
if (modelClass.dataSource === this) {
|
if (modelClass.dataSource === this) {
|
||||||
// Already attached to the data source
|
// Already attached to the data source
|
||||||
return modelClass;
|
return modelClass;
|
||||||
|
@ -762,7 +762,7 @@ DataSource.prototype.attach = function (modelClass) {
|
||||||
* @param {String} prop Name of property
|
* @param {String} prop Name of property
|
||||||
* @param {Object} params Property settings
|
* @param {Object} params Property settings
|
||||||
*/
|
*/
|
||||||
DataSource.prototype.defineProperty = function (model, prop, params) {
|
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];
|
||||||
|
@ -782,7 +782,7 @@ DataSource.prototype.defineProperty = function (model, prop, params) {
|
||||||
*
|
*
|
||||||
|
|
||||||
*/
|
*/
|
||||||
DataSource.prototype.automigrate = function (models, cb) {
|
DataSource.prototype.automigrate = function(models, cb) {
|
||||||
this.freeze();
|
this.freeze();
|
||||||
|
|
||||||
if ((!cb) && ('function' === typeof models)) {
|
if ((!cb) && ('function' === typeof models)) {
|
||||||
|
@ -813,13 +813,13 @@ DataSource.prototype.automigrate = function (models, cb) {
|
||||||
return cb.promise;
|
return cb.promise;
|
||||||
}
|
}
|
||||||
|
|
||||||
var invalidModels = models.filter(function (m) {
|
var invalidModels = models.filter(function(m) {
|
||||||
return !(m in attachedModels);
|
return !(m in attachedModels);
|
||||||
});
|
});
|
||||||
|
|
||||||
if (invalidModels.length) {
|
if (invalidModels.length) {
|
||||||
process.nextTick(function () {
|
process.nextTick(function() {
|
||||||
cb(new Error('Cannot migrate models not attached to this datasource: ' +
|
cb(new Error('Cannot migrate models not attached to this datasource: ' +
|
||||||
invalidModels.join(' ')));
|
invalidModels.join(' ')));
|
||||||
});
|
});
|
||||||
return cb.promise;
|
return cb.promise;
|
||||||
|
@ -837,7 +837,7 @@ DataSource.prototype.automigrate = function (models, cb) {
|
||||||
* @param {String} model Model to migrate. If not present, apply to all models. Can also be an array of Strings.
|
* @param {String} model Model to migrate. If not present, apply to all models. Can also be an array of Strings.
|
||||||
* @param {Function} [cb] The callback function
|
* @param {Function} [cb] The callback function
|
||||||
*/
|
*/
|
||||||
DataSource.prototype.autoupdate = function (models, cb) {
|
DataSource.prototype.autoupdate = function(models, cb) {
|
||||||
this.freeze();
|
this.freeze();
|
||||||
|
|
||||||
if ((!cb) && ('function' === typeof models)) {
|
if ((!cb) && ('function' === typeof models)) {
|
||||||
|
@ -868,12 +868,12 @@ DataSource.prototype.autoupdate = function (models, cb) {
|
||||||
return cb.promise;
|
return cb.promise;
|
||||||
}
|
}
|
||||||
|
|
||||||
var invalidModels = models.filter(function (m) {
|
var invalidModels = models.filter(function(m) {
|
||||||
return !(m in attachedModels);
|
return !(m in attachedModels);
|
||||||
});
|
});
|
||||||
|
|
||||||
if (invalidModels.length) {
|
if (invalidModels.length) {
|
||||||
process.nextTick(function () {
|
process.nextTick(function() {
|
||||||
cb(new Error('Cannot migrate models not attached to this datasource: ' +
|
cb(new Error('Cannot migrate models not attached to this datasource: ' +
|
||||||
invalidModels.join(' ')));
|
invalidModels.join(' ')));
|
||||||
});
|
});
|
||||||
|
@ -898,7 +898,7 @@ DataSource.prototype.autoupdate = function (models, cb) {
|
||||||
* @property {Number} offset Starting index
|
* @property {Number} offset Starting index
|
||||||
*
|
*
|
||||||
*/
|
*/
|
||||||
DataSource.prototype.discoverModelDefinitions = function (options, cb) {
|
DataSource.prototype.discoverModelDefinitions = function(options, cb) {
|
||||||
this.freeze();
|
this.freeze();
|
||||||
|
|
||||||
if (cb === undefined && typeof options === 'function') {
|
if (cb === undefined && typeof options === 'function') {
|
||||||
|
@ -925,7 +925,7 @@ DataSource.prototype.discoverModelDefinitions = function (options, cb) {
|
||||||
* @property {Number} offset Starting index
|
* @property {Number} offset Starting index
|
||||||
* @returns {*}
|
* @returns {*}
|
||||||
*/
|
*/
|
||||||
DataSource.prototype.discoverModelDefinitionsSync = function (options) {
|
DataSource.prototype.discoverModelDefinitionsSync = function(options) {
|
||||||
this.freeze();
|
this.freeze();
|
||||||
if (this.connector.discoverModelDefinitionsSync) {
|
if (this.connector.discoverModelDefinitionsSync) {
|
||||||
return this.connector.discoverModelDefinitionsSync(options);
|
return this.connector.discoverModelDefinitionsSync(options);
|
||||||
|
@ -955,7 +955,7 @@ DataSource.prototype.discoverModelDefinitionsSync = function (options) {
|
||||||
* @param {Function} cb Callback function. Optional
|
* @param {Function} cb Callback function. Optional
|
||||||
*
|
*
|
||||||
*/
|
*/
|
||||||
DataSource.prototype.discoverModelProperties = function (modelName, options, cb) {
|
DataSource.prototype.discoverModelProperties = function(modelName, options, cb) {
|
||||||
this.freeze();
|
this.freeze();
|
||||||
|
|
||||||
if (cb === undefined && typeof options === 'function') {
|
if (cb === undefined && typeof options === 'function') {
|
||||||
|
@ -970,7 +970,7 @@ DataSource.prototype.discoverModelProperties = function (modelName, options, cb)
|
||||||
} else if (cb) {
|
} else if (cb) {
|
||||||
process.nextTick(cb);
|
process.nextTick(cb);
|
||||||
}
|
}
|
||||||
return cb.promise;
|
return cb.promise;
|
||||||
};
|
};
|
||||||
|
|
||||||
/**
|
/**
|
||||||
|
@ -979,7 +979,7 @@ DataSource.prototype.discoverModelProperties = function (modelName, options, cb)
|
||||||
* @param {Object} options The options
|
* @param {Object} options The options
|
||||||
* @returns {*}
|
* @returns {*}
|
||||||
*/
|
*/
|
||||||
DataSource.prototype.discoverModelPropertiesSync = function (modelName, options) {
|
DataSource.prototype.discoverModelPropertiesSync = function(modelName, options) {
|
||||||
this.freeze();
|
this.freeze();
|
||||||
if (this.connector.discoverModelPropertiesSync) {
|
if (this.connector.discoverModelPropertiesSync) {
|
||||||
return this.connector.discoverModelPropertiesSync(modelName, options);
|
return this.connector.discoverModelPropertiesSync(modelName, options);
|
||||||
|
@ -1004,7 +1004,7 @@ DataSource.prototype.discoverModelPropertiesSync = function (modelName, options)
|
||||||
* @property {String} owner|schema The database owner or schema
|
* @property {String} owner|schema The database owner or schema
|
||||||
* @param {Function} [cb] The callback function
|
* @param {Function} [cb] The callback function
|
||||||
*/
|
*/
|
||||||
DataSource.prototype.discoverPrimaryKeys = function (modelName, options, cb) {
|
DataSource.prototype.discoverPrimaryKeys = function(modelName, options, cb) {
|
||||||
this.freeze();
|
this.freeze();
|
||||||
|
|
||||||
if (cb === undefined && typeof options === 'function') {
|
if (cb === undefined && typeof options === 'function') {
|
||||||
|
@ -1029,7 +1029,7 @@ DataSource.prototype.discoverPrimaryKeys = function (modelName, options, cb) {
|
||||||
* @property {String} owner|schema The database owner orschema
|
* @property {String} owner|schema The database owner orschema
|
||||||
* @returns {*}
|
* @returns {*}
|
||||||
*/
|
*/
|
||||||
DataSource.prototype.discoverPrimaryKeysSync = function (modelName, options) {
|
DataSource.prototype.discoverPrimaryKeysSync = function(modelName, options) {
|
||||||
this.freeze();
|
this.freeze();
|
||||||
if (this.connector.discoverPrimaryKeysSync) {
|
if (this.connector.discoverPrimaryKeysSync) {
|
||||||
return this.connector.discoverPrimaryKeysSync(modelName, options);
|
return this.connector.discoverPrimaryKeysSync(modelName, options);
|
||||||
|
@ -1060,7 +1060,7 @@ DataSource.prototype.discoverPrimaryKeysSync = function (modelName, options) {
|
||||||
* @param {Function} [cb] The callback function
|
* @param {Function} [cb] The callback function
|
||||||
*
|
*
|
||||||
*/
|
*/
|
||||||
DataSource.prototype.discoverForeignKeys = function (modelName, options, cb) {
|
DataSource.prototype.discoverForeignKeys = function(modelName, options, cb) {
|
||||||
this.freeze();
|
this.freeze();
|
||||||
|
|
||||||
if (cb === undefined && typeof options === 'function') {
|
if (cb === undefined && typeof options === 'function') {
|
||||||
|
@ -1085,7 +1085,7 @@ DataSource.prototype.discoverForeignKeys = function (modelName, options, cb) {
|
||||||
* @param {Object} options The options
|
* @param {Object} options The options
|
||||||
* @returns {*}
|
* @returns {*}
|
||||||
*/
|
*/
|
||||||
DataSource.prototype.discoverForeignKeysSync = function (modelName, options) {
|
DataSource.prototype.discoverForeignKeysSync = function(modelName, options) {
|
||||||
this.freeze();
|
this.freeze();
|
||||||
if (this.connector.discoverForeignKeysSync) {
|
if (this.connector.discoverForeignKeysSync) {
|
||||||
return this.connector.discoverForeignKeysSync(modelName, options);
|
return this.connector.discoverForeignKeysSync(modelName, options);
|
||||||
|
@ -1116,7 +1116,7 @@ DataSource.prototype.discoverForeignKeysSync = function (modelName, options) {
|
||||||
* @property {String} owner|schema The database owner or schema
|
* @property {String} owner|schema The database owner or schema
|
||||||
* @param {Function} [cb] The callback function
|
* @param {Function} [cb] The callback function
|
||||||
*/
|
*/
|
||||||
DataSource.prototype.discoverExportedForeignKeys = function (modelName, options, cb) {
|
DataSource.prototype.discoverExportedForeignKeys = function(modelName, options, cb) {
|
||||||
this.freeze();
|
this.freeze();
|
||||||
|
|
||||||
if (cb === undefined && typeof options === 'function') {
|
if (cb === undefined && typeof options === 'function') {
|
||||||
|
@ -1140,7 +1140,7 @@ DataSource.prototype.discoverExportedForeignKeys = function (modelName, options,
|
||||||
* @param {Object} options The options
|
* @param {Object} options The options
|
||||||
* @returns {*}
|
* @returns {*}
|
||||||
*/
|
*/
|
||||||
DataSource.prototype.discoverExportedForeignKeysSync = function (modelName, options) {
|
DataSource.prototype.discoverExportedForeignKeysSync = function(modelName, options) {
|
||||||
this.freeze();
|
this.freeze();
|
||||||
if (this.connector.discoverExportedForeignKeysSync) {
|
if (this.connector.discoverExportedForeignKeysSync) {
|
||||||
return this.connector.discoverExportedForeignKeysSync(modelName, options);
|
return this.connector.discoverExportedForeignKeysSync(modelName, options);
|
||||||
|
@ -1226,7 +1226,7 @@ function fromDBName(dbName, camelCase) {
|
||||||
* @param {Object} [options] The options
|
* @param {Object} [options] The options
|
||||||
* @param {Function} [cb] The callback function
|
* @param {Function} [cb] The callback function
|
||||||
*/
|
*/
|
||||||
DataSource.prototype.discoverSchema = function (modelName, options, cb) {
|
DataSource.prototype.discoverSchema = function(modelName, options, cb) {
|
||||||
options = options || {};
|
options = options || {};
|
||||||
|
|
||||||
if (!cb && 'function' === typeof options) {
|
if (!cb && 'function' === typeof options) {
|
||||||
|
@ -1238,7 +1238,7 @@ DataSource.prototype.discoverSchema = function (modelName, options, cb) {
|
||||||
|
|
||||||
cb = cb || utils.createPromiseCallback();
|
cb = cb || utils.createPromiseCallback();
|
||||||
|
|
||||||
this.discoverSchemas(modelName, options, function (err, schemas) {
|
this.discoverSchemas(modelName, options, function(err, schemas) {
|
||||||
if (err) {
|
if (err) {
|
||||||
cb && cb(err, schemas);
|
cb && cb(err, schemas);
|
||||||
return;
|
return;
|
||||||
|
@ -1262,7 +1262,7 @@ DataSource.prototype.discoverSchema = function (modelName, options, cb) {
|
||||||
* @property {Boolean} views True if views are included; false otherwise.
|
* @property {Boolean} views True if views are included; false otherwise.
|
||||||
* @param {Function} [cb] The callback function
|
* @param {Function} [cb] The callback function
|
||||||
*/
|
*/
|
||||||
DataSource.prototype.discoverSchemas = function (modelName, options, cb) {
|
DataSource.prototype.discoverSchemas = function(modelName, options, cb) {
|
||||||
options = options || {};
|
options = options || {};
|
||||||
|
|
||||||
if (!cb && 'function' === typeof options) {
|
if (!cb && 'function' === typeof options) {
|
||||||
|
@ -1310,7 +1310,7 @@ DataSource.prototype.discoverSchemas = function (modelName, options, cb) {
|
||||||
tasks.push(this.discoverForeignKeys.bind(this, modelName, options));
|
tasks.push(this.discoverForeignKeys.bind(this, modelName, options));
|
||||||
}
|
}
|
||||||
|
|
||||||
async.parallel(tasks, function (err, results) {
|
async.parallel(tasks, function(err, results) {
|
||||||
|
|
||||||
if (err) {
|
if (err) {
|
||||||
cb(err);
|
cb(err);
|
||||||
|
@ -1326,7 +1326,7 @@ DataSource.prototype.discoverSchemas = function (modelName, options, cb) {
|
||||||
// Handle primary keys
|
// Handle primary keys
|
||||||
var primaryKeys = results[1] || [];
|
var primaryKeys = results[1] || [];
|
||||||
var pks = {};
|
var pks = {};
|
||||||
primaryKeys.forEach(function (pk) {
|
primaryKeys.forEach(function(pk) {
|
||||||
pks[pk.columnName] = pk.keySeq;
|
pks[pk.columnName] = pk.keySeq;
|
||||||
});
|
});
|
||||||
|
|
||||||
|
@ -1337,17 +1337,17 @@ DataSource.prototype.discoverSchemas = function (modelName, options, cb) {
|
||||||
var schema = {
|
var schema = {
|
||||||
name: nameMapper('table', modelName),
|
name: nameMapper('table', modelName),
|
||||||
options: {
|
options: {
|
||||||
idInjection: false // DO NOT add id property
|
idInjection: false, // DO NOT add id property
|
||||||
},
|
},
|
||||||
properties: {}
|
properties: {},
|
||||||
};
|
};
|
||||||
|
|
||||||
schema.options[dbType] = {
|
schema.options[dbType] = {
|
||||||
schema: columns[0].owner,
|
schema: columns[0].owner,
|
||||||
table: modelName
|
table: modelName,
|
||||||
};
|
};
|
||||||
|
|
||||||
columns.forEach(function (item) {
|
columns.forEach(function(item) {
|
||||||
var i = item;
|
var i = item;
|
||||||
|
|
||||||
var propName = nameMapper('column', item.columnName);
|
var propName = nameMapper('column', item.columnName);
|
||||||
|
@ -1357,7 +1357,7 @@ DataSource.prototype.discoverSchemas = function (modelName, options, cb) {
|
||||||
|| item.nullable === 0 || item.nullable === false),
|
|| item.nullable === 0 || item.nullable === false),
|
||||||
length: item.dataLength,
|
length: item.dataLength,
|
||||||
precision: item.dataPrecision,
|
precision: item.dataPrecision,
|
||||||
scale: item.dataScale
|
scale: item.dataScale,
|
||||||
};
|
};
|
||||||
|
|
||||||
if (pks[item.columnName]) {
|
if (pks[item.columnName]) {
|
||||||
|
@ -1369,7 +1369,7 @@ DataSource.prototype.discoverSchemas = function (modelName, options, cb) {
|
||||||
dataLength: i.dataLength,
|
dataLength: i.dataLength,
|
||||||
dataPrecision: item.dataPrecision,
|
dataPrecision: item.dataPrecision,
|
||||||
dataScale: item.dataScale,
|
dataScale: item.dataScale,
|
||||||
nullable: i.nullable
|
nullable: i.nullable,
|
||||||
};
|
};
|
||||||
});
|
});
|
||||||
|
|
||||||
|
@ -1388,12 +1388,12 @@ DataSource.prototype.discoverSchemas = function (modelName, options, cb) {
|
||||||
// Handle foreign keys
|
// Handle foreign keys
|
||||||
var fks = {};
|
var fks = {};
|
||||||
var foreignKeys = results[2] || [];
|
var foreignKeys = results[2] || [];
|
||||||
foreignKeys.forEach(function (fk) {
|
foreignKeys.forEach(function(fk) {
|
||||||
var fkInfo = {
|
var fkInfo = {
|
||||||
keySeq: fk.keySeq,
|
keySeq: fk.keySeq,
|
||||||
owner: fk.pkOwner,
|
owner: fk.pkOwner,
|
||||||
tableName: fk.pkTableName,
|
tableName: fk.pkTableName,
|
||||||
columnName: fk.pkColumnName
|
columnName: fk.pkColumnName,
|
||||||
};
|
};
|
||||||
if (fks[fk.fkName]) {
|
if (fks[fk.fkName]) {
|
||||||
fks[fk.fkName].push(fkInfo);
|
fks[fk.fkName].push(fkInfo);
|
||||||
|
@ -1407,17 +1407,17 @@ DataSource.prototype.discoverSchemas = function (modelName, options, cb) {
|
||||||
}
|
}
|
||||||
|
|
||||||
schema.options.relations = {};
|
schema.options.relations = {};
|
||||||
foreignKeys.forEach(function (fk) {
|
foreignKeys.forEach(function(fk) {
|
||||||
var propName = nameMapper('column', fk.pkTableName);
|
var propName = nameMapper('column', fk.pkTableName);
|
||||||
schema.options.relations[propName] = {
|
schema.options.relations[propName] = {
|
||||||
model: nameMapper('table', fk.pkTableName),
|
model: nameMapper('table', fk.pkTableName),
|
||||||
type: 'belongsTo',
|
type: 'belongsTo',
|
||||||
foreignKey: nameMapper('column', fk.fkColumnName)
|
foreignKey: nameMapper('column', fk.fkColumnName),
|
||||||
};
|
};
|
||||||
|
|
||||||
var key = fk.pkOwner + '.' + fk.pkTableName;
|
var key = fk.pkOwner + '.' + fk.pkTableName;
|
||||||
if (!options.visited.hasOwnProperty(key) && !otherTables.hasOwnProperty(key)) {
|
if (!options.visited.hasOwnProperty(key) && !otherTables.hasOwnProperty(key)) {
|
||||||
otherTables[key] = {owner: fk.pkOwner, tableName: fk.pkTableName};
|
otherTables[key] = { owner: fk.pkOwner, tableName: fk.pkTableName };
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
@ -1438,7 +1438,7 @@ DataSource.prototype.discoverSchemas = function (modelName, options, cb) {
|
||||||
|
|
||||||
moreTasks.push(DataSource.prototype.discoverSchemas.bind(self, otherTables[t].tableName, newOptions));
|
moreTasks.push(DataSource.prototype.discoverSchemas.bind(self, otherTables[t].tableName, newOptions));
|
||||||
}
|
}
|
||||||
async.parallel(moreTasks, function (err, results) {
|
async.parallel(moreTasks, function(err, results) {
|
||||||
var result = results && results[0];
|
var result = results && results[0];
|
||||||
cb(err, result);
|
cb(err, result);
|
||||||
});
|
});
|
||||||
|
@ -1457,7 +1457,7 @@ DataSource.prototype.discoverSchemas = function (modelName, options, cb) {
|
||||||
* @property {Boolean} all True if all owners are included; false otherwise.
|
* @property {Boolean} all True if all owners are included; false otherwise.
|
||||||
* @property {Boolean} views True if views are included; false otherwise.
|
* @property {Boolean} views True if views are included; false otherwise.
|
||||||
*/
|
*/
|
||||||
DataSource.prototype.discoverSchemasSync = function (modelName, options) {
|
DataSource.prototype.discoverSchemasSync = function(modelName, options) {
|
||||||
var self = this;
|
var self = this;
|
||||||
var dbType = this.name || this.connector.name;
|
var dbType = this.name || this.connector.name;
|
||||||
|
|
||||||
|
@ -1477,7 +1477,7 @@ DataSource.prototype.discoverSchemasSync = function (modelName, options) {
|
||||||
// Handle primary keys
|
// Handle primary keys
|
||||||
var primaryKeys = this.discoverPrimaryKeysSync(modelName, options);
|
var primaryKeys = this.discoverPrimaryKeysSync(modelName, options);
|
||||||
var pks = {};
|
var pks = {};
|
||||||
primaryKeys.forEach(function (pk) {
|
primaryKeys.forEach(function(pk) {
|
||||||
pks[pk.columnName] = pk.keySeq;
|
pks[pk.columnName] = pk.keySeq;
|
||||||
});
|
});
|
||||||
|
|
||||||
|
@ -1488,17 +1488,17 @@ DataSource.prototype.discoverSchemasSync = function (modelName, options) {
|
||||||
var schema = {
|
var schema = {
|
||||||
name: nameMapper('table', modelName),
|
name: nameMapper('table', modelName),
|
||||||
options: {
|
options: {
|
||||||
idInjection: false // DO NOT add id property
|
idInjection: false, // DO NOT add id property
|
||||||
},
|
},
|
||||||
properties: {}
|
properties: {},
|
||||||
};
|
};
|
||||||
|
|
||||||
schema.options[dbType] = {
|
schema.options[dbType] = {
|
||||||
schema: columns.length > 0 && columns[0].owner,
|
schema: columns.length > 0 && columns[0].owner,
|
||||||
table: modelName
|
table: modelName,
|
||||||
};
|
};
|
||||||
|
|
||||||
columns.forEach(function (item) {
|
columns.forEach(function(item) {
|
||||||
var i = item;
|
var i = item;
|
||||||
|
|
||||||
var propName = nameMapper('column', item.columnName);
|
var propName = nameMapper('column', item.columnName);
|
||||||
|
@ -1507,7 +1507,7 @@ DataSource.prototype.discoverSchemasSync = function (modelName, options) {
|
||||||
required: (item.nullable === 'N'),
|
required: (item.nullable === 'N'),
|
||||||
length: item.dataLength,
|
length: item.dataLength,
|
||||||
precision: item.dataPrecision,
|
precision: item.dataPrecision,
|
||||||
scale: item.dataScale
|
scale: item.dataScale,
|
||||||
};
|
};
|
||||||
|
|
||||||
if (pks[item.columnName]) {
|
if (pks[item.columnName]) {
|
||||||
|
@ -1519,7 +1519,7 @@ DataSource.prototype.discoverSchemasSync = function (modelName, options) {
|
||||||
dataLength: i.dataLength,
|
dataLength: i.dataLength,
|
||||||
dataPrecision: item.dataPrecision,
|
dataPrecision: item.dataPrecision,
|
||||||
dataScale: item.dataScale,
|
dataScale: item.dataScale,
|
||||||
nullable: i.nullable
|
nullable: i.nullable,
|
||||||
};
|
};
|
||||||
});
|
});
|
||||||
|
|
||||||
|
@ -1539,12 +1539,12 @@ DataSource.prototype.discoverSchemasSync = function (modelName, options) {
|
||||||
// Handle foreign keys
|
// Handle foreign keys
|
||||||
var fks = {};
|
var fks = {};
|
||||||
var foreignKeys = this.discoverForeignKeysSync(modelName, options);
|
var foreignKeys = this.discoverForeignKeysSync(modelName, options);
|
||||||
foreignKeys.forEach(function (fk) {
|
foreignKeys.forEach(function(fk) {
|
||||||
var fkInfo = {
|
var fkInfo = {
|
||||||
keySeq: fk.keySeq,
|
keySeq: fk.keySeq,
|
||||||
owner: fk.pkOwner,
|
owner: fk.pkOwner,
|
||||||
tableName: fk.pkTableName,
|
tableName: fk.pkTableName,
|
||||||
columnName: fk.pkColumnName
|
columnName: fk.pkColumnName,
|
||||||
};
|
};
|
||||||
if (fks[fk.fkName]) {
|
if (fks[fk.fkName]) {
|
||||||
fks[fk.fkName].push(fkInfo);
|
fks[fk.fkName].push(fkInfo);
|
||||||
|
@ -1558,17 +1558,17 @@ DataSource.prototype.discoverSchemasSync = function (modelName, options) {
|
||||||
}
|
}
|
||||||
|
|
||||||
schema.options.relations = {};
|
schema.options.relations = {};
|
||||||
foreignKeys.forEach(function (fk) {
|
foreignKeys.forEach(function(fk) {
|
||||||
var propName = nameMapper('column', fk.pkTableName);
|
var propName = nameMapper('column', fk.pkTableName);
|
||||||
schema.options.relations[propName] = {
|
schema.options.relations[propName] = {
|
||||||
model: nameMapper('table', fk.pkTableName),
|
model: nameMapper('table', fk.pkTableName),
|
||||||
type: 'belongsTo',
|
type: 'belongsTo',
|
||||||
foreignKey: nameMapper('column', fk.fkColumnName)
|
foreignKey: nameMapper('column', fk.fkColumnName),
|
||||||
};
|
};
|
||||||
|
|
||||||
var key = fk.pkOwner + '.' + fk.pkTableName;
|
var key = fk.pkOwner + '.' + fk.pkTableName;
|
||||||
if (!options.visited.hasOwnProperty(key) && !otherTables.hasOwnProperty(key)) {
|
if (!options.visited.hasOwnProperty(key) && !otherTables.hasOwnProperty(key)) {
|
||||||
otherTables[key] = {owner: fk.pkOwner, tableName: fk.pkTableName};
|
otherTables[key] = { owner: fk.pkOwner, tableName: fk.pkTableName };
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
@ -1604,10 +1604,10 @@ DataSource.prototype.discoverSchemasSync = function (modelName, options) {
|
||||||
* @property {Boolean} views True if views are included; false otherwise.
|
* @property {Boolean} views True if views are included; false otherwise.
|
||||||
* @param {Function} [cb] The callback function
|
* @param {Function} [cb] The callback function
|
||||||
*/
|
*/
|
||||||
DataSource.prototype.discoverAndBuildModels = function (modelName, options, cb) {
|
DataSource.prototype.discoverAndBuildModels = function(modelName, options, cb) {
|
||||||
var self = this;
|
var self = this;
|
||||||
options = options || {};
|
options = options || {};
|
||||||
this.discoverSchemas(modelName, options, function (err, schemas) {
|
this.discoverSchemas(modelName, options, function(err, schemas) {
|
||||||
if (err) {
|
if (err) {
|
||||||
cb && cb(err, schemas);
|
cb && cb(err, schemas);
|
||||||
return;
|
return;
|
||||||
|
@ -1643,7 +1643,7 @@ DataSource.prototype.discoverAndBuildModels = function (modelName, options, cb)
|
||||||
* @param {String} modelName The model name
|
* @param {String} modelName The model name
|
||||||
* @param {Object} [options] The options
|
* @param {Object} [options] The options
|
||||||
*/
|
*/
|
||||||
DataSource.prototype.discoverAndBuildModelsSync = function (modelName, options) {
|
DataSource.prototype.discoverAndBuildModelsSync = function(modelName, options) {
|
||||||
options = options || {};
|
options = options || {};
|
||||||
var schemas = this.discoverSchemasSync(modelName, options);
|
var schemas = this.discoverSchemasSync(modelName, options);
|
||||||
|
|
||||||
|
@ -1670,7 +1670,7 @@ DataSource.prototype.discoverAndBuildModelsSync = function (modelName, options)
|
||||||
* @param {Object} options Options
|
* @param {Object} options Options
|
||||||
* @returns {*}
|
* @returns {*}
|
||||||
*/
|
*/
|
||||||
DataSource.prototype.buildModelFromInstance = function (name, json, options) {
|
DataSource.prototype.buildModelFromInstance = function(name, json, options) {
|
||||||
|
|
||||||
// Introspect the JSON document to generate a schema
|
// Introspect the JSON document to generate a schema
|
||||||
var schema = ModelBuilder.introspect(json);
|
var schema = ModelBuilder.introspect(json);
|
||||||
|
@ -1684,7 +1684,7 @@ DataSource.prototype.buildModelFromInstance = function (name, json, options) {
|
||||||
* This method applies only to SQL connectors.
|
* This method applies only to SQL connectors.
|
||||||
* @param {String|String[]} [models] A model name or an array of model names. If not present, apply to all models.
|
* @param {String|String[]} [models] A model name or an array of model names. If not present, apply to all models.
|
||||||
*/
|
*/
|
||||||
DataSource.prototype.isActual = function (models, cb) {
|
DataSource.prototype.isActual = function(models, cb) {
|
||||||
this.freeze();
|
this.freeze();
|
||||||
if (this.connector.isActual) {
|
if (this.connector.isActual) {
|
||||||
this.connector.isActual(models, cb);
|
this.connector.isActual(models, cb);
|
||||||
|
@ -1694,7 +1694,7 @@ DataSource.prototype.isActual = function (models, cb) {
|
||||||
models = undefined;
|
models = undefined;
|
||||||
}
|
}
|
||||||
if (cb) {
|
if (cb) {
|
||||||
process.nextTick(function () {
|
process.nextTick(function() {
|
||||||
cb(null, true);
|
cb(null, true);
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
@ -1707,7 +1707,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);
|
debug(sql, t);
|
||||||
this.emit('log', sql, t);
|
this.emit('log', sql, t);
|
||||||
};
|
};
|
||||||
|
@ -1731,7 +1731,7 @@ DataSource.prototype.freeze = function freeze() {
|
||||||
* Return table name for specified `modelName`
|
* Return table name for specified `modelName`
|
||||||
* @param {String} modelName The model name
|
* @param {String} modelName The model name
|
||||||
*/
|
*/
|
||||||
DataSource.prototype.tableName = function (modelName) {
|
DataSource.prototype.tableName = function(modelName) {
|
||||||
return this.getModelDefinition(modelName).tableName(this.connector.name);
|
return this.getModelDefinition(modelName).tableName(this.connector.name);
|
||||||
};
|
};
|
||||||
|
|
||||||
|
@ -1741,7 +1741,7 @@ DataSource.prototype.tableName = function (modelName) {
|
||||||
* @param {String} propertyName The property name
|
* @param {String} propertyName The property name
|
||||||
* @returns {String} columnName The column name.
|
* @returns {String} columnName The column name.
|
||||||
*/
|
*/
|
||||||
DataSource.prototype.columnName = function (modelName, propertyName) {
|
DataSource.prototype.columnName = function(modelName, propertyName) {
|
||||||
return this.getModelDefinition(modelName).columnName(this.connector.name, propertyName);
|
return this.getModelDefinition(modelName).columnName(this.connector.name, propertyName);
|
||||||
};
|
};
|
||||||
|
|
||||||
|
@ -1751,7 +1751,7 @@ DataSource.prototype.columnName = function (modelName, propertyName) {
|
||||||
* @param {String} propertyName The property name
|
* @param {String} propertyName The property name
|
||||||
* @returns {Object} column metadata
|
* @returns {Object} column metadata
|
||||||
*/
|
*/
|
||||||
DataSource.prototype.columnMetadata = function (modelName, propertyName) {
|
DataSource.prototype.columnMetadata = function(modelName, propertyName) {
|
||||||
return this.getModelDefinition(modelName).columnMetadata(this.connector.name, propertyName);
|
return this.getModelDefinition(modelName).columnMetadata(this.connector.name, propertyName);
|
||||||
};
|
};
|
||||||
|
|
||||||
|
@ -1760,7 +1760,7 @@ DataSource.prototype.columnMetadata = function (modelName, propertyName) {
|
||||||
* @param {String} modelName The model name
|
* @param {String} modelName The model name
|
||||||
* @returns {String[]} column names
|
* @returns {String[]} column names
|
||||||
*/
|
*/
|
||||||
DataSource.prototype.columnNames = function (modelName) {
|
DataSource.prototype.columnNames = function(modelName) {
|
||||||
return this.getModelDefinition(modelName).columnNames(this.connector.name);
|
return this.getModelDefinition(modelName).columnNames(this.connector.name);
|
||||||
};
|
};
|
||||||
|
|
||||||
|
@ -1769,7 +1769,7 @@ DataSource.prototype.columnNames = function (modelName) {
|
||||||
* @param {String} modelName The model name
|
* @param {String} modelName The model name
|
||||||
* @returns {String} columnName for ID
|
* @returns {String} columnName for ID
|
||||||
*/
|
*/
|
||||||
DataSource.prototype.idColumnName = function (modelName) {
|
DataSource.prototype.idColumnName = function(modelName) {
|
||||||
return this.getModelDefinition(modelName).idColumnName(this.connector.name);
|
return this.getModelDefinition(modelName).idColumnName(this.connector.name);
|
||||||
};
|
};
|
||||||
|
|
||||||
|
@ -1778,7 +1778,7 @@ DataSource.prototype.idColumnName = function (modelName) {
|
||||||
* @param {String} modelName The model name
|
* @param {String} modelName The model name
|
||||||
* @returns {String} property name for ID
|
* @returns {String} property name for ID
|
||||||
*/
|
*/
|
||||||
DataSource.prototype.idName = function (modelName) {
|
DataSource.prototype.idName = function(modelName) {
|
||||||
if (!this.getModelDefinition(modelName).idName) {
|
if (!this.getModelDefinition(modelName).idName) {
|
||||||
console.error('No id name', this.getModelDefinition(modelName));
|
console.error('No id name', this.getModelDefinition(modelName));
|
||||||
}
|
}
|
||||||
|
@ -1790,7 +1790,7 @@ DataSource.prototype.idName = function (modelName) {
|
||||||
* @param {String} modelName The model name
|
* @param {String} modelName The model name
|
||||||
* @returns {String[]} property names for IDs
|
* @returns {String[]} property names for IDs
|
||||||
*/
|
*/
|
||||||
DataSource.prototype.idNames = function (modelName) {
|
DataSource.prototype.idNames = function(modelName) {
|
||||||
return this.getModelDefinition(modelName).idNames();
|
return this.getModelDefinition(modelName).idNames();
|
||||||
};
|
};
|
||||||
|
|
||||||
|
@ -1799,7 +1799,7 @@ DataSource.prototype.idNames = function (modelName) {
|
||||||
* @param {String} modelName The model name
|
* @param {String} modelName The model name
|
||||||
* @returns {Object} The id property definition
|
* @returns {Object} The id property definition
|
||||||
*/
|
*/
|
||||||
DataSource.prototype.idProperty = function (modelName) {
|
DataSource.prototype.idProperty = function(modelName) {
|
||||||
var def = this.getModelDefinition(modelName);
|
var def = this.getModelDefinition(modelName);
|
||||||
var idProps = def && def.ids();
|
var idProps = def && def.ids();
|
||||||
return idProps && idProps[0] && idProps[0].property;
|
return idProps && idProps[0] && idProps[0].property;
|
||||||
|
@ -1828,7 +1828,7 @@ DataSource.prototype.defineForeignKey = function defineForeignKey(className, key
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
var fkDef = {type: pkType};
|
var fkDef = { type: pkType };
|
||||||
var foreignMeta = this.columnMetadata(foreignClassName, pkName);
|
var foreignMeta = this.columnMetadata(foreignClassName, pkName);
|
||||||
if (foreignMeta && (foreignMeta.dataType || foreignMeta.dataLength)) {
|
if (foreignMeta && (foreignMeta.dataType || foreignMeta.dataLength)) {
|
||||||
fkDef[this.connector.name] = {};
|
fkDef[this.connector.name] = {};
|
||||||
|
@ -1840,7 +1840,7 @@ DataSource.prototype.defineForeignKey = function defineForeignKey(className, key
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
if (this.connector.defineForeignKey) {
|
if (this.connector.defineForeignKey) {
|
||||||
var cb = function (err, keyType) {
|
var cb = function(err, keyType) {
|
||||||
if (err) throw err;
|
if (err) throw err;
|
||||||
fkDef.type = keyType || pkType;
|
fkDef.type = keyType || pkType;
|
||||||
// Add the foreign key property to the data source _models
|
// Add the foreign key property to the data source _models
|
||||||
|
@ -1869,12 +1869,12 @@ DataSource.prototype.defineForeignKey = function defineForeignKey(className, key
|
||||||
DataSource.prototype.disconnect = function disconnect(cb) {
|
DataSource.prototype.disconnect = function disconnect(cb) {
|
||||||
var self = this;
|
var self = this;
|
||||||
if (this.connected && (typeof this.connector.disconnect === 'function')) {
|
if (this.connected && (typeof this.connector.disconnect === 'function')) {
|
||||||
this.connector.disconnect(function (err, result) {
|
this.connector.disconnect(function(err, result) {
|
||||||
self.connected = false;
|
self.connected = false;
|
||||||
cb && cb(err, result);
|
cb && cb(err, result);
|
||||||
});
|
});
|
||||||
} else {
|
} else {
|
||||||
process.nextTick(function () {
|
process.nextTick(function() {
|
||||||
cb && cb();
|
cb && cb();
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
@ -1914,7 +1914,7 @@ DataSource.prototype.copyModel = function copyModel(Master) {
|
||||||
dataSource.connector.define({
|
dataSource.connector.define({
|
||||||
model: Slave,
|
model: Slave,
|
||||||
properties: md.properties,
|
properties: md.properties,
|
||||||
settings: md.settings
|
settings: md.settings,
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -1928,7 +1928,7 @@ DataSource.prototype.copyModel = function copyModel(Master) {
|
||||||
* @returns {EventEmitter}
|
* @returns {EventEmitter}
|
||||||
* @private
|
* @private
|
||||||
*/
|
*/
|
||||||
DataSource.prototype.transaction = function () {
|
DataSource.prototype.transaction = function() {
|
||||||
var dataSource = this;
|
var dataSource = this;
|
||||||
var transaction = new EventEmitter();
|
var transaction = new EventEmitter();
|
||||||
|
|
||||||
|
@ -1953,7 +1953,7 @@ DataSource.prototype.transaction = function () {
|
||||||
dataSource.copyModel.call(transaction, dataSource.modelBuilder.models[i]);
|
dataSource.copyModel.call(transaction, dataSource.modelBuilder.models[i]);
|
||||||
}
|
}
|
||||||
|
|
||||||
transaction.exec = function (cb) {
|
transaction.exec = function(cb) {
|
||||||
transaction.connector.exec(cb);
|
transaction.connector.exec(cb);
|
||||||
};
|
};
|
||||||
|
|
||||||
|
@ -1966,14 +1966,14 @@ DataSource.prototype.transaction = function () {
|
||||||
* @param {String} operation The operation name
|
* @param {String} operation The operation name
|
||||||
*/
|
*/
|
||||||
|
|
||||||
DataSource.prototype.enableRemote = function (operation) {
|
DataSource.prototype.enableRemote = function(operation) {
|
||||||
var op = this.getOperation(operation);
|
var op = this.getOperation(operation);
|
||||||
if (op) {
|
if (op) {
|
||||||
op.remoteEnabled = true;
|
op.remoteEnabled = true;
|
||||||
} else {
|
} else {
|
||||||
throw new Error(operation + ' is not provided by the attached connector');
|
throw new Error(operation + ' is not provided by the attached connector');
|
||||||
}
|
}
|
||||||
}
|
};
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Disable remote access to a data source operation. Each [connector](#connector) has its own set of set enabled
|
* Disable remote access to a data source operation. Each [connector](#connector) has its own set of set enabled
|
||||||
|
@ -1995,21 +1995,21 @@ DataSource.prototype.enableRemote = function (operation) {
|
||||||
* @param {String} operation The operation name
|
* @param {String} operation The operation name
|
||||||
*/
|
*/
|
||||||
|
|
||||||
DataSource.prototype.disableRemote = function (operation) {
|
DataSource.prototype.disableRemote = function(operation) {
|
||||||
var op = this.getOperation(operation);
|
var op = this.getOperation(operation);
|
||||||
if (op) {
|
if (op) {
|
||||||
op.remoteEnabled = false;
|
op.remoteEnabled = false;
|
||||||
} else {
|
} else {
|
||||||
throw new Error(operation + ' is not provided by the attached connector');
|
throw new Error(operation + ' is not provided by the attached connector');
|
||||||
}
|
}
|
||||||
}
|
};
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Get an operation's metadata.
|
* Get an operation's metadata.
|
||||||
* @param {String} operation The operation name
|
* @param {String} operation The operation name
|
||||||
*/
|
*/
|
||||||
|
|
||||||
DataSource.prototype.getOperation = function (operation) {
|
DataSource.prototype.getOperation = function(operation) {
|
||||||
var ops = this.operations();
|
var ops = this.operations();
|
||||||
var opKeys = Object.keys(ops);
|
var opKeys = Object.keys(ops);
|
||||||
|
|
||||||
|
@ -2020,7 +2020,7 @@ DataSource.prototype.getOperation = function (operation) {
|
||||||
return op;
|
return op;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
};
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Return JSON object describing all operations.
|
* Return JSON object describing all operations.
|
||||||
|
@ -2045,9 +2045,9 @@ DataSource.prototype.getOperation = function (operation) {
|
||||||
* }
|
* }
|
||||||
* ```
|
* ```
|
||||||
*/
|
*/
|
||||||
DataSource.prototype.operations = function () {
|
DataSource.prototype.operations = function() {
|
||||||
return this._operations;
|
return this._operations;
|
||||||
}
|
};
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Define an operation to the data source
|
* Define an operation to the data source
|
||||||
|
@ -2055,7 +2055,7 @@ DataSource.prototype.operations = function () {
|
||||||
* @param {Object} options The options
|
* @param {Object} options The options
|
||||||
* @param {Function} fn The function
|
* @param {Function} fn The function
|
||||||
*/
|
*/
|
||||||
DataSource.prototype.defineOperation = function (name, options, fn) {
|
DataSource.prototype.defineOperation = function(name, options, fn) {
|
||||||
options.fn = fn;
|
options.fn = fn;
|
||||||
options.name = name;
|
options.name = name;
|
||||||
this._operations[name] = options;
|
this._operations[name] = options;
|
||||||
|
@ -2065,7 +2065,7 @@ DataSource.prototype.defineOperation = function (name, options, fn) {
|
||||||
* Check if the backend is a relational DB
|
* Check if the backend is a relational DB
|
||||||
* @returns {Boolean}
|
* @returns {Boolean}
|
||||||
*/
|
*/
|
||||||
DataSource.prototype.isRelational = function () {
|
DataSource.prototype.isRelational = function() {
|
||||||
return this.connector && this.connector.relational;
|
return this.connector && this.connector.relational;
|
||||||
};
|
};
|
||||||
|
|
||||||
|
@ -2075,7 +2075,7 @@ DataSource.prototype.isRelational = function () {
|
||||||
* @param {Object} obj ?
|
* @param {Object} obj ?
|
||||||
* @param {Object} args ?
|
* @param {Object} args ?
|
||||||
*/
|
*/
|
||||||
DataSource.prototype.ready = function (obj, args) {
|
DataSource.prototype.ready = function(obj, args) {
|
||||||
var self = this;
|
var self = this;
|
||||||
if (this.connected) {
|
if (this.connected) {
|
||||||
// Connected
|
// Connected
|
||||||
|
@ -2107,7 +2107,7 @@ DataSource.prototype.ready = function (obj, args) {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
onError = function (err) {
|
onError = function(err) {
|
||||||
// Remove the connected listener
|
// Remove the connected listener
|
||||||
self.removeListener('connected', onConnected);
|
self.removeListener('connected', onConnected);
|
||||||
if (timeoutHandle) {
|
if (timeoutHandle) {
|
||||||
|
@ -2126,7 +2126,7 @@ DataSource.prototype.ready = function (obj, args) {
|
||||||
|
|
||||||
// Set up a timeout to cancel the invocation
|
// Set up a timeout to cancel the invocation
|
||||||
var timeout = this.settings.connectionTimeout || 5000;
|
var timeout = this.settings.connectionTimeout || 5000;
|
||||||
timeoutHandle = setTimeout(function () {
|
timeoutHandle = setTimeout(function() {
|
||||||
self.removeListener('error', onError);
|
self.removeListener('error', onError);
|
||||||
self.removeListener('connected', onConnected);
|
self.removeListener('connected', onConnected);
|
||||||
var params = [].slice.call(args);
|
var params = [].slice.call(args);
|
||||||
|
@ -2146,14 +2146,14 @@ DataSource.prototype.ready = function (obj, args) {
|
||||||
* Ping the underlying connector to test the connections
|
* Ping the underlying connector to test the connections
|
||||||
* @param {Function} [cb] Callback function
|
* @param {Function} [cb] Callback function
|
||||||
*/
|
*/
|
||||||
DataSource.prototype.ping = function (cb) {
|
DataSource.prototype.ping = function(cb) {
|
||||||
var self = this;
|
var self = this;
|
||||||
if (self.connector.ping) {
|
if (self.connector.ping) {
|
||||||
this.connector.ping(cb);
|
this.connector.ping(cb);
|
||||||
} else if (self.connector.discoverModelProperties) {
|
} else if (self.connector.discoverModelProperties) {
|
||||||
self.discoverModelProperties('dummy', {}, cb);
|
self.discoverModelProperties('dummy', {}, cb);
|
||||||
} else {
|
} else {
|
||||||
process.nextTick(function () {
|
process.nextTick(function() {
|
||||||
var err = self.connected ? null : 'Not connected';
|
var err = self.connected ? null : 'Not connected';
|
||||||
cb(err);
|
cb(err);
|
||||||
});
|
});
|
||||||
|
@ -2171,7 +2171,7 @@ function hiddenProperty(obj, key, value) {
|
||||||
writable: false,
|
writable: false,
|
||||||
enumerable: false,
|
enumerable: false,
|
||||||
configurable: false,
|
configurable: false,
|
||||||
value: value
|
value: value,
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -2187,7 +2187,7 @@ function defineReadonlyProp(obj, key, value) {
|
||||||
writable: false,
|
writable: false,
|
||||||
enumerable: true,
|
enumerable: true,
|
||||||
configurable: true,
|
configurable: true,
|
||||||
value: value
|
value: value,
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -2200,6 +2200,6 @@ DataSource.Any = ModelBuilder.Any;
|
||||||
* @deprecated Use ModelBuilder.registerType instead
|
* @deprecated Use ModelBuilder.registerType instead
|
||||||
* @param type
|
* @param type
|
||||||
*/
|
*/
|
||||||
DataSource.registerType = function (type) {
|
DataSource.registerType = function(type) {
|
||||||
ModelBuilder.registerType(type);
|
ModelBuilder.registerType(type);
|
||||||
};
|
};
|
||||||
|
|
62
lib/geo.js
62
lib/geo.js
|
@ -13,7 +13,7 @@ exports.nearFilter = function nearFilter(where) {
|
||||||
var result = false;
|
var result = false;
|
||||||
|
|
||||||
if (where && typeof where === 'object') {
|
if (where && typeof where === 'object') {
|
||||||
Object.keys(where).forEach(function (key) {
|
Object.keys(where).forEach(function(key) {
|
||||||
var ex = where[key];
|
var ex = where[key];
|
||||||
|
|
||||||
if (ex && ex.near) {
|
if (ex && ex.near) {
|
||||||
|
@ -21,20 +21,20 @@ exports.nearFilter = function nearFilter(where) {
|
||||||
near: ex.near,
|
near: ex.near,
|
||||||
maxDistance: ex.maxDistance,
|
maxDistance: ex.maxDistance,
|
||||||
unit: ex.unit,
|
unit: ex.unit,
|
||||||
key: key
|
key: key,
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
return result;
|
return result;
|
||||||
}
|
};
|
||||||
|
|
||||||
/*!
|
/*!
|
||||||
* Filter a set of objects using the given `nearFilter`.
|
* Filter a set of objects using the given `nearFilter`.
|
||||||
*/
|
*/
|
||||||
|
|
||||||
exports.filter = function (arr, filter) {
|
exports.filter = function(arr, filter) {
|
||||||
var origin = filter.near;
|
var origin = filter.near;
|
||||||
var max = filter.maxDistance > 0 ? filter.maxDistance : false;
|
var max = filter.maxDistance > 0 ? filter.maxDistance : false;
|
||||||
var unit = filter.unit;
|
var unit = filter.unit;
|
||||||
|
@ -44,7 +44,7 @@ exports.filter = function (arr, filter) {
|
||||||
var distances = {};
|
var distances = {};
|
||||||
var result = [];
|
var result = [];
|
||||||
|
|
||||||
arr.forEach(function (obj) {
|
arr.forEach(function(obj) {
|
||||||
var loc = obj[key];
|
var loc = obj[key];
|
||||||
|
|
||||||
// filter out objects without locations
|
// filter out objects without locations
|
||||||
|
@ -57,7 +57,7 @@ exports.filter = function (arr, filter) {
|
||||||
if (typeof loc.lat !== 'number') return;
|
if (typeof loc.lat !== 'number') return;
|
||||||
if (typeof loc.lng !== 'number') return;
|
if (typeof loc.lng !== 'number') return;
|
||||||
|
|
||||||
var d = GeoPoint.distanceBetween(origin, loc, {type: unit});
|
var d = GeoPoint.distanceBetween(origin, loc, { type: unit });
|
||||||
|
|
||||||
if (max && d > max) {
|
if (max && d > max) {
|
||||||
// dont add
|
// dont add
|
||||||
|
@ -67,7 +67,7 @@ exports.filter = function (arr, filter) {
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
return result.sort(function (objA, objB) {
|
return result.sort(function(objA, objB) {
|
||||||
var a = objA[key];
|
var a = objA[key];
|
||||||
var b = objB[key];
|
var b = objB[key];
|
||||||
|
|
||||||
|
@ -81,31 +81,31 @@ exports.filter = function (arr, filter) {
|
||||||
return 0;
|
return 0;
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
}
|
};
|
||||||
|
|
||||||
exports.GeoPoint = GeoPoint;
|
exports.GeoPoint = GeoPoint;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* The GeoPoint object represents a physical location.
|
* The GeoPoint object represents a physical location.
|
||||||
*
|
*
|
||||||
* For example:
|
* For example:
|
||||||
*
|
*
|
||||||
* ```js
|
* ```js
|
||||||
* var loopback = require(‘loopback’);
|
* var loopback = require(‘loopback’);
|
||||||
* var here = new loopback.GeoPoint({lat: 10.32424, lng: 5.84978});
|
* var here = new loopback.GeoPoint({lat: 10.32424, lng: 5.84978});
|
||||||
* ```
|
* ```
|
||||||
*
|
*
|
||||||
* Embed a latitude / longitude point in a model.
|
* Embed a latitude / longitude point in a model.
|
||||||
*
|
*
|
||||||
* ```js
|
* ```js
|
||||||
* var CoffeeShop = loopback.createModel('coffee-shop', {
|
* var CoffeeShop = loopback.createModel('coffee-shop', {
|
||||||
* location: 'GeoPoint'
|
* location: 'GeoPoint'
|
||||||
* });
|
* });
|
||||||
* ```
|
* ```
|
||||||
*
|
*
|
||||||
* You can query LoopBack models with a GeoPoint property and an attached data source using geo-spatial filters and
|
* You can query LoopBack models with a GeoPoint property and an attached data source using geo-spatial filters and
|
||||||
* sorting. For example, the following code finds the three nearest coffee shops.
|
* sorting. For example, the following code finds the three nearest coffee shops.
|
||||||
*
|
*
|
||||||
* ```js
|
* ```js
|
||||||
* CoffeeShop.attachTo(oracle);
|
* CoffeeShop.attachTo(oracle);
|
||||||
* var here = new GeoPoint({lat: 10.32424, lng: 5.84978});
|
* var here = new GeoPoint({lat: 10.32424, lng: 5.84978});
|
||||||
|
@ -114,9 +114,9 @@ exports.GeoPoint = GeoPoint;
|
||||||
* });
|
* });
|
||||||
* ```
|
* ```
|
||||||
* @class GeoPoint
|
* @class GeoPoint
|
||||||
* @property {Number} lat The latitude in degrees.
|
* @property {Number} lat The latitude in degrees.
|
||||||
* @property {Number} lng The longitude in degrees.
|
* @property {Number} lng The longitude in degrees.
|
||||||
*
|
*
|
||||||
* @options {Object} Options Object with two Number properties: lat and long.
|
* @options {Object} Options Object with two Number properties: lat and long.
|
||||||
* @property {Number} lat The latitude point in degrees. Range: -90 to 90.
|
* @property {Number} lat The latitude point in degrees. Range: -90 to 90.
|
||||||
* @property {Number} lng The longitude point in degrees. Range: -180 to 180.
|
* @property {Number} lng The longitude point in degrees. Range: -180 to 180.
|
||||||
|
@ -131,10 +131,10 @@ function GeoPoint(data) {
|
||||||
return new GeoPoint(data);
|
return new GeoPoint(data);
|
||||||
}
|
}
|
||||||
|
|
||||||
if(arguments.length === 2) {
|
if (arguments.length === 2) {
|
||||||
data = {
|
data = {
|
||||||
lat: arguments[0],
|
lat: arguments[0],
|
||||||
lng: arguments[1]
|
lng: arguments[1],
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -147,7 +147,7 @@ function GeoPoint(data) {
|
||||||
if (Array.isArray(data)) {
|
if (Array.isArray(data)) {
|
||||||
data = {
|
data = {
|
||||||
lat: Number(data[0]),
|
lat: Number(data[0]),
|
||||||
lng: Number(data[1])
|
lng: Number(data[1]),
|
||||||
};
|
};
|
||||||
} else {
|
} else {
|
||||||
data.lng = Number(data.lng);
|
data.lng = Number(data.lng);
|
||||||
|
@ -162,18 +162,18 @@ function GeoPoint(data) {
|
||||||
assert(data.lat <= 90, 'lat must be <= 90');
|
assert(data.lat <= 90, 'lat must be <= 90');
|
||||||
assert(data.lat >= -90, 'lat must be >= -90');
|
assert(data.lat >= -90, 'lat must be >= -90');
|
||||||
|
|
||||||
this.lat = data.lat;
|
this.lat = data.lat;
|
||||||
this.lng = data.lng;
|
this.lng = data.lng;
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Determine the spherical distance between two GeoPoints.
|
* Determine the spherical distance between two GeoPoints.
|
||||||
*
|
*
|
||||||
* @param {GeoPoint} pointA Point A
|
* @param {GeoPoint} pointA Point A
|
||||||
* @param {GeoPoint} pointB Point B
|
* @param {GeoPoint} pointB Point B
|
||||||
* @options {Object} options Options object with one key, 'type'. See below.
|
* @options {Object} options Options object with one key, 'type'. See below.
|
||||||
* @property {String} type Unit of measurement, one of:
|
* @property {String} type Unit of measurement, one of:
|
||||||
*
|
*
|
||||||
* - `miles` (default)
|
* - `miles` (default)
|
||||||
* - `radians`
|
* - `radians`
|
||||||
* - `kilometers`
|
* - `kilometers`
|
||||||
|
@ -205,16 +205,16 @@ GeoPoint.distanceBetween = function distanceBetween(a, b, options) {
|
||||||
* Example:
|
* Example:
|
||||||
* ```js
|
* ```js
|
||||||
* var loopback = require(‘loopback’);
|
* var loopback = require(‘loopback’);
|
||||||
*
|
*
|
||||||
* var here = new loopback.GeoPoint({lat: 10, lng: 10});
|
* var here = new loopback.GeoPoint({lat: 10, lng: 10});
|
||||||
* var there = new loopback.GeoPoint({lat: 5, lng: 5});
|
* var there = new loopback.GeoPoint({lat: 5, lng: 5});
|
||||||
*
|
*
|
||||||
* loopback.GeoPoint.distanceBetween(here, there, {type: 'miles'}) // 438
|
* loopback.GeoPoint.distanceBetween(here, there, {type: 'miles'}) // 438
|
||||||
* ```
|
* ```
|
||||||
* @param {Object} point GeoPoint object to which to measure distance.
|
* @param {Object} point GeoPoint object to which to measure distance.
|
||||||
* @options {Object} options Options object with one key, 'type'. See below.
|
* @options {Object} options Options object with one key, 'type'. See below.
|
||||||
* @property {String} type Unit of measurement, one of:
|
* @property {String} type Unit of measurement, one of:
|
||||||
*
|
*
|
||||||
* - `miles` (default)
|
* - `miles` (default)
|
||||||
* - `radians`
|
* - `radians`
|
||||||
* - `kilometers`
|
* - `kilometers`
|
||||||
|
@ -224,7 +224,7 @@ GeoPoint.distanceBetween = function distanceBetween(a, b, options) {
|
||||||
* - `degrees`
|
* - `degrees`
|
||||||
*/
|
*/
|
||||||
|
|
||||||
GeoPoint.prototype.distanceTo = function (point, options) {
|
GeoPoint.prototype.distanceTo = function(point, options) {
|
||||||
return GeoPoint.distanceBetween(this, point, options);
|
return GeoPoint.distanceBetween(this, point, options);
|
||||||
};
|
};
|
||||||
|
|
||||||
|
@ -232,7 +232,7 @@ GeoPoint.prototype.distanceTo = function (point, options) {
|
||||||
* Simple serialization.
|
* Simple serialization.
|
||||||
*/
|
*/
|
||||||
|
|
||||||
GeoPoint.prototype.toString = function () {
|
GeoPoint.prototype.toString = function() {
|
||||||
return this.lat + ',' + this.lng;
|
return this.lat + ',' + this.lng;
|
||||||
};
|
};
|
||||||
|
|
||||||
|
@ -255,7 +255,7 @@ var EARTH_RADIUS = {
|
||||||
miles: 3958.75,
|
miles: 3958.75,
|
||||||
feet: 20902200,
|
feet: 20902200,
|
||||||
radians: 1,
|
radians: 1,
|
||||||
degrees: RAD2DEG
|
degrees: RAD2DEG,
|
||||||
};
|
};
|
||||||
|
|
||||||
function geoDistance(x1, y1, x2, y2, options) {
|
function geoDistance(x1, y1, x2, y2, options) {
|
||||||
|
@ -268,7 +268,7 @@ function geoDistance(x1, y1, x2, y2, options) {
|
||||||
x2 = x2 * DEG2RAD;
|
x2 = x2 * DEG2RAD;
|
||||||
y2 = y2 * DEG2RAD;
|
y2 = y2 * DEG2RAD;
|
||||||
|
|
||||||
// use the haversine formula to calculate distance for any 2 points on a sphere.
|
// use the haversine formula to calculate distance for any 2 points on a sphere.
|
||||||
// ref http://en.wikipedia.org/wiki/Haversine_formula
|
// ref http://en.wikipedia.org/wiki/Haversine_formula
|
||||||
var haversine = function(a) {
|
var haversine = function(a) {
|
||||||
return Math.pow(Math.sin(a / 2.0), 2);
|
return Math.pow(Math.sin(a / 2.0), 2);
|
||||||
|
|
10
lib/hooks.js
10
lib/hooks.js
|
@ -36,10 +36,10 @@ Hookable.afterDestroy = null;
|
||||||
// TODO: Evaluate https://github.com/bnoguchi/hooks-js/
|
// TODO: Evaluate https://github.com/bnoguchi/hooks-js/
|
||||||
Hookable.prototype.trigger = function trigger(actionName, work, data, callback) {
|
Hookable.prototype.trigger = function trigger(actionName, work, data, callback) {
|
||||||
var capitalizedName = capitalize(actionName);
|
var capitalizedName = capitalize(actionName);
|
||||||
var beforeHook = this.constructor["before" + capitalizedName]
|
var beforeHook = this.constructor['before' + capitalizedName]
|
||||||
|| this.constructor["pre" + capitalizedName];
|
|| this.constructor['pre' + capitalizedName];
|
||||||
var afterHook = this.constructor["after" + capitalizedName]
|
var afterHook = this.constructor['after' + capitalizedName]
|
||||||
|| this.constructor["post" + capitalizedName];
|
|| this.constructor['post' + capitalizedName];
|
||||||
if (actionName === 'validate') {
|
if (actionName === 'validate') {
|
||||||
beforeHook = beforeHook || this.constructor.beforeValidation;
|
beforeHook = beforeHook || this.constructor.beforeValidation;
|
||||||
afterHook = afterHook || this.constructor.afterValidation;
|
afterHook = afterHook || this.constructor.afterValidation;
|
||||||
|
@ -57,7 +57,7 @@ Hookable.prototype.trigger = function trigger(actionName, work, data, callback)
|
||||||
if (work) {
|
if (work) {
|
||||||
if (beforeHook) {
|
if (beforeHook) {
|
||||||
// before hook should be called on instance with two parameters: next and data
|
// before hook should be called on instance with two parameters: next and data
|
||||||
beforeHook.call(inst, function () {
|
beforeHook.call(inst, function() {
|
||||||
// Check arguments to next(err, result)
|
// Check arguments to next(err, result)
|
||||||
if (arguments.length) {
|
if (arguments.length) {
|
||||||
return callback && callback.apply(null, arguments);
|
return callback && callback.apply(null, arguments);
|
||||||
|
|
|
@ -100,11 +100,11 @@ function lookupModel(models, modelName) {
|
||||||
function execTasksWithInterLeave(tasks, callback) {
|
function execTasksWithInterLeave(tasks, callback) {
|
||||||
//let's give others some time to process.
|
//let's give others some time to process.
|
||||||
//Context Switch BEFORE Heavy Computation
|
//Context Switch BEFORE Heavy Computation
|
||||||
process.nextTick(function () {
|
process.nextTick(function() {
|
||||||
//Heavy Computation
|
//Heavy Computation
|
||||||
async.parallel(tasks, function (err, info) {
|
async.parallel(tasks, function(err, info) {
|
||||||
//Context Switch AFTER Heavy Computation
|
//Context Switch AFTER Heavy Computation
|
||||||
process.nextTick(function () {
|
process.nextTick(function() {
|
||||||
callback(err, info);
|
callback(err, info);
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
@ -156,7 +156,7 @@ Inclusion.normalizeInclude = normalizeInclude;
|
||||||
* @param {Function} cb Callback called when relations are loaded
|
* @param {Function} cb Callback called when relations are loaded
|
||||||
*
|
*
|
||||||
*/
|
*/
|
||||||
Inclusion.include = function (objects, include, options, cb) {
|
Inclusion.include = function(objects, include, options, cb) {
|
||||||
if (typeof options === 'function' && cb === undefined) {
|
if (typeof options === 'function' && cb === undefined) {
|
||||||
cb = options;
|
cb = options;
|
||||||
options = {};
|
options = {};
|
||||||
|
@ -236,14 +236,14 @@ Inclusion.include = function (objects, include, options, cb) {
|
||||||
if (filter.fields && Array.isArray(subInclude) &&
|
if (filter.fields && Array.isArray(subInclude) &&
|
||||||
relation.modelTo.relations) {
|
relation.modelTo.relations) {
|
||||||
includeScope.fields = [];
|
includeScope.fields = [];
|
||||||
subInclude.forEach(function (name) {
|
subInclude.forEach(function(name) {
|
||||||
var rel = relation.modelTo.relations[name];
|
var rel = relation.modelTo.relations[name];
|
||||||
if (rel && rel.type === 'belongsTo') {
|
if (rel && rel.type === 'belongsTo') {
|
||||||
includeScope.fields.push(rel.keyFrom);
|
includeScope.fields.push(rel.keyFrom);
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
utils.mergeQuery(filter, includeScope, {fields: false});
|
utils.mergeQuery(filter, includeScope, { fields: false });
|
||||||
}
|
}
|
||||||
//Let's add a placeholder where query
|
//Let's add a placeholder where query
|
||||||
filter.where = filter.where || {};
|
filter.where = filter.where || {};
|
||||||
|
@ -276,7 +276,7 @@ Inclusion.include = function (objects, include, options, cb) {
|
||||||
}
|
}
|
||||||
|
|
||||||
//This handles exactly hasMany. Fast and straightforward. Without parallel, each and other boilerplate.
|
//This handles exactly hasMany. Fast and straightforward. Without parallel, each and other boilerplate.
|
||||||
if(relation.type === 'hasMany' && relation.multiple && !subInclude){
|
if (relation.type === 'hasMany' && relation.multiple && !subInclude) {
|
||||||
return includeHasManySimple(cb);
|
return includeHasManySimple(cb);
|
||||||
}
|
}
|
||||||
//assuming all other relations with multiple=true as hasMany
|
//assuming all other relations with multiple=true as hasMany
|
||||||
|
@ -321,10 +321,10 @@ Inclusion.include = function (objects, include, options, cb) {
|
||||||
//default filters are not applicable on through model. should be applied
|
//default filters are not applicable on through model. should be applied
|
||||||
//on modelTo later in 2nd DB call.
|
//on modelTo later in 2nd DB call.
|
||||||
var throughFilter = {
|
var throughFilter = {
|
||||||
where: {}
|
where: {},
|
||||||
};
|
};
|
||||||
throughFilter.where[relation.keyTo] = {
|
throughFilter.where[relation.keyTo] = {
|
||||||
inq: uniq(sourceIds)
|
inq: uniq(sourceIds),
|
||||||
};
|
};
|
||||||
if (polymorphic) {
|
if (polymorphic) {
|
||||||
//handle polymorphic hasMany (reverse) in which case we need to filter
|
//handle polymorphic hasMany (reverse) in which case we need to filter
|
||||||
|
@ -367,7 +367,7 @@ Inclusion.include = function (objects, include, options, cb) {
|
||||||
//Polymorphic relation does not have idKey of modelTo. Find it manually
|
//Polymorphic relation does not have idKey of modelTo. Find it manually
|
||||||
var modelToIdName = idName(relation.modelTo);
|
var modelToIdName = idName(relation.modelTo);
|
||||||
filter.where[modelToIdName] = {
|
filter.where[modelToIdName] = {
|
||||||
inq: uniq(targetIds)
|
inq: uniq(targetIds),
|
||||||
};
|
};
|
||||||
|
|
||||||
//make sure that the modelToIdName is included if fields are specified
|
//make sure that the modelToIdName is included if fields are specified
|
||||||
|
@ -401,7 +401,7 @@ Inclusion.include = function (objects, include, options, cb) {
|
||||||
function linkManyToMany(target, next) {
|
function linkManyToMany(target, next) {
|
||||||
var targetId = target[modelToIdName];
|
var targetId = target[modelToIdName];
|
||||||
var objList = targetObjsMap[targetId.toString()];
|
var objList = targetObjsMap[targetId.toString()];
|
||||||
async.each(objList, function (obj, next) {
|
async.each(objList, function(obj, next) {
|
||||||
if (!obj) return next();
|
if (!obj) return next();
|
||||||
obj.__cachedRelations[relationName].push(target);
|
obj.__cachedRelations[relationName].push(target);
|
||||||
processTargetObj(obj, next);
|
processTargetObj(obj, next);
|
||||||
|
@ -450,7 +450,7 @@ Inclusion.include = function (objects, include, options, cb) {
|
||||||
obj.__cachedRelations[relationName] = [];
|
obj.__cachedRelations[relationName] = [];
|
||||||
}
|
}
|
||||||
filter.where[relation.keyTo] = {
|
filter.where[relation.keyTo] = {
|
||||||
inq: uniq(allTargetIds)
|
inq: uniq(allTargetIds),
|
||||||
};
|
};
|
||||||
relation.applyScope(null, filter);
|
relation.applyScope(null, filter);
|
||||||
/**
|
/**
|
||||||
|
@ -481,7 +481,7 @@ Inclusion.include = function (objects, include, options, cb) {
|
||||||
async.each(targets, linkManyToMany, next);
|
async.each(targets, linkManyToMany, next);
|
||||||
function linkManyToMany(target, next) {
|
function linkManyToMany(target, next) {
|
||||||
var objList = targetObjsMap[target[relation.keyTo].toString()];
|
var objList = targetObjsMap[target[relation.keyTo].toString()];
|
||||||
async.each(objList, function (obj, next) {
|
async.each(objList, function(obj, next) {
|
||||||
if (!obj) return next();
|
if (!obj) return next();
|
||||||
obj.__cachedRelations[relationName].push(target);
|
obj.__cachedRelations[relationName].push(target);
|
||||||
processTargetObj(obj, next);
|
processTargetObj(obj, next);
|
||||||
|
@ -503,21 +503,21 @@ Inclusion.include = function (objects, include, options, cb) {
|
||||||
var objIdMap2 = includeUtils.buildOneToOneIdentityMapWithOrigKeys(objs, relation.keyFrom);
|
var objIdMap2 = includeUtils.buildOneToOneIdentityMapWithOrigKeys(objs, relation.keyFrom);
|
||||||
|
|
||||||
filter.where[relation.keyTo] = {
|
filter.where[relation.keyTo] = {
|
||||||
inq: uniq(objIdMap2.getKeys())
|
inq: uniq(objIdMap2.getKeys()),
|
||||||
};
|
};
|
||||||
|
|
||||||
relation.applyScope(null, filter);
|
relation.applyScope(null, filter);
|
||||||
relation.modelTo.find(filter, options, targetFetchHandler);
|
relation.modelTo.find(filter, options, targetFetchHandler);
|
||||||
|
|
||||||
function targetFetchHandler(err, targets) {
|
function targetFetchHandler(err, targets) {
|
||||||
if(err) {
|
if (err) {
|
||||||
return callback(err);
|
return callback(err);
|
||||||
}
|
}
|
||||||
var targetsIdMap = includeUtils.buildOneToManyIdentityMapWithOrigKeys(targets, relation.keyTo);
|
var targetsIdMap = includeUtils.buildOneToManyIdentityMapWithOrigKeys(targets, relation.keyTo);
|
||||||
includeUtils.join(objIdMap2, targetsIdMap, function(obj1, valueToMergeIn){
|
includeUtils.join(objIdMap2, targetsIdMap, function(obj1, valueToMergeIn) {
|
||||||
defineCachedRelations(obj1);
|
defineCachedRelations(obj1);
|
||||||
obj1.__cachedRelations[relationName] = valueToMergeIn;
|
obj1.__cachedRelations[relationName] = valueToMergeIn;
|
||||||
processTargetObj(obj1, function(){});
|
processTargetObj(obj1, function() {});
|
||||||
});
|
});
|
||||||
callback(err, objs);
|
callback(err, objs);
|
||||||
}
|
}
|
||||||
|
@ -545,7 +545,7 @@ Inclusion.include = function (objects, include, options, cb) {
|
||||||
obj.__cachedRelations[relationName] = [];
|
obj.__cachedRelations[relationName] = [];
|
||||||
}
|
}
|
||||||
filter.where[relation.keyTo] = {
|
filter.where[relation.keyTo] = {
|
||||||
inq: uniq(sourceIds)
|
inq: uniq(sourceIds),
|
||||||
};
|
};
|
||||||
relation.applyScope(null, filter);
|
relation.applyScope(null, filter);
|
||||||
options.partitionBy = relation.keyTo;
|
options.partitionBy = relation.keyTo;
|
||||||
|
@ -580,7 +580,7 @@ Inclusion.include = function (objects, include, options, cb) {
|
||||||
function linkManyToOne(target, next) {
|
function linkManyToOne(target, next) {
|
||||||
//fix for bug in hasMany with referencesMany
|
//fix for bug in hasMany with referencesMany
|
||||||
var targetIds = [].concat(target[relation.keyTo]);
|
var targetIds = [].concat(target[relation.keyTo]);
|
||||||
async.each(targetIds, function (targetId, next) {
|
async.each(targetIds, function(targetId, next) {
|
||||||
var obj = objIdMap[targetId.toString()];
|
var obj = objIdMap[targetId.toString()];
|
||||||
if (!obj) return next();
|
if (!obj) return next();
|
||||||
obj.__cachedRelations[relationName].push(target);
|
obj.__cachedRelations[relationName].push(target);
|
||||||
|
@ -644,11 +644,11 @@ Inclusion.include = function (objects, include, options, cb) {
|
||||||
* @param callback
|
* @param callback
|
||||||
*/
|
*/
|
||||||
function processPolymorphicType(modelType, callback) {
|
function processPolymorphicType(modelType, callback) {
|
||||||
var typeFilter = {where: {}};
|
var typeFilter = { where: {}};
|
||||||
utils.mergeQuery(typeFilter, filter);
|
utils.mergeQuery(typeFilter, filter);
|
||||||
var targetIds = targetIdsByType[modelType];
|
var targetIds = targetIdsByType[modelType];
|
||||||
typeFilter.where[relation.keyTo] = {
|
typeFilter.where[relation.keyTo] = {
|
||||||
inq: uniq(targetIds)
|
inq: uniq(targetIds),
|
||||||
};
|
};
|
||||||
var Model = lookupModel(relation.modelFrom.dataSource.modelBuilder.
|
var Model = lookupModel(relation.modelFrom.dataSource.modelBuilder.
|
||||||
models, modelType);
|
models, modelType);
|
||||||
|
@ -684,7 +684,7 @@ Inclusion.include = function (objects, include, options, cb) {
|
||||||
async.each(targets, linkOneToMany, next);
|
async.each(targets, linkOneToMany, next);
|
||||||
function linkOneToMany(target, next) {
|
function linkOneToMany(target, next) {
|
||||||
var objList = targetObjsMap[target[relation.keyTo].toString()];
|
var objList = targetObjsMap[target[relation.keyTo].toString()];
|
||||||
async.each(objList, function (obj, next) {
|
async.each(objList, function(obj, next) {
|
||||||
if (!obj) return next();
|
if (!obj) return next();
|
||||||
obj.__cachedRelations[relationName] = target;
|
obj.__cachedRelations[relationName] = target;
|
||||||
processTargetObj(obj, next);
|
processTargetObj(obj, next);
|
||||||
|
@ -720,7 +720,7 @@ Inclusion.include = function (objects, include, options, cb) {
|
||||||
obj.__cachedRelations[relationName] = null;
|
obj.__cachedRelations[relationName] = null;
|
||||||
}
|
}
|
||||||
filter.where[relation.keyTo] = {
|
filter.where[relation.keyTo] = {
|
||||||
inq: uniq(sourceIds)
|
inq: uniq(sourceIds),
|
||||||
};
|
};
|
||||||
relation.applyScope(null, filter);
|
relation.applyScope(null, filter);
|
||||||
relation.modelTo.find(filter, options, targetFetchHandler);
|
relation.modelTo.find(filter, options, targetFetchHandler);
|
||||||
|
@ -787,7 +787,7 @@ Inclusion.include = function (objects, include, options, cb) {
|
||||||
obj.__cachedRelations[relationName] = null;
|
obj.__cachedRelations[relationName] = null;
|
||||||
}
|
}
|
||||||
filter.where[relation.keyTo] = {
|
filter.where[relation.keyTo] = {
|
||||||
inq: uniq(targetIds)
|
inq: uniq(targetIds),
|
||||||
};
|
};
|
||||||
relation.applyScope(null, filter);
|
relation.applyScope(null, filter);
|
||||||
relation.modelTo.find(filter, options, targetFetchHandler);
|
relation.modelTo.find(filter, options, targetFetchHandler);
|
||||||
|
@ -815,7 +815,7 @@ Inclusion.include = function (objects, include, options, cb) {
|
||||||
function linkOneToMany(target, next) {
|
function linkOneToMany(target, next) {
|
||||||
var targetId = target[relation.keyTo];
|
var targetId = target[relation.keyTo];
|
||||||
var objList = objTargetIdMap[targetId.toString()];
|
var objList = objTargetIdMap[targetId.toString()];
|
||||||
async.each(objList, function (obj, next) {
|
async.each(objList, function(obj, next) {
|
||||||
if (!obj) return next();
|
if (!obj) return next();
|
||||||
obj.__cachedRelations[relationName] = target;
|
obj.__cachedRelations[relationName] = target;
|
||||||
processTargetObj(obj, next);
|
processTargetObj(obj, next);
|
||||||
|
@ -838,7 +838,7 @@ Inclusion.include = function (objects, include, options, cb) {
|
||||||
* @param callback
|
* @param callback
|
||||||
*/
|
*/
|
||||||
function includeEmbeds(callback) {
|
function includeEmbeds(callback) {
|
||||||
async.each(objs, function (obj, next) {
|
async.each(objs, function(obj, next) {
|
||||||
processTargetObj(obj, next);
|
processTargetObj(obj, next);
|
||||||
}, callback);
|
}, callback);
|
||||||
}
|
}
|
||||||
|
@ -914,14 +914,14 @@ Inclusion.include = function (objects, include, options, cb) {
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
utils.mergeQuery(filter, includeScope, {fields: false});
|
utils.mergeQuery(filter, includeScope, { fields: false });
|
||||||
|
|
||||||
related = inst[relationName].bind(inst, filter);
|
related = inst[relationName].bind(inst, filter);
|
||||||
} else {
|
} else {
|
||||||
related = inst[relationName].bind(inst, undefined);
|
related = inst[relationName].bind(inst, undefined);
|
||||||
}
|
}
|
||||||
|
|
||||||
related(options, function (err, result) {
|
related(options, function(err, result) {
|
||||||
if (err) {
|
if (err) {
|
||||||
return callback(err);
|
return callback(err);
|
||||||
} else {
|
} else {
|
||||||
|
|
|
@ -18,7 +18,7 @@ module.exports.KVMap = KVMap;
|
||||||
*/
|
*/
|
||||||
function buildOneToOneIdentityMapWithOrigKeys(objs, idName) {
|
function buildOneToOneIdentityMapWithOrigKeys(objs, idName) {
|
||||||
var kvMap = new KVMap();
|
var kvMap = new KVMap();
|
||||||
for(var i = 0; i < objs.length; i++) {
|
for (var i = 0; i < objs.length; i++) {
|
||||||
var obj = objs[i];
|
var obj = objs[i];
|
||||||
var id = obj[idName];
|
var id = obj[idName];
|
||||||
kvMap.set(id, obj);
|
kvMap.set(id, obj);
|
||||||
|
@ -28,7 +28,7 @@ function buildOneToOneIdentityMapWithOrigKeys(objs, idName) {
|
||||||
|
|
||||||
function buildOneToManyIdentityMapWithOrigKeys(objs, idName) {
|
function buildOneToManyIdentityMapWithOrigKeys(objs, idName) {
|
||||||
var kvMap = new KVMap();
|
var kvMap = new KVMap();
|
||||||
for(var i = 0; i < objs.length; i++) {
|
for (var i = 0; i < objs.length; i++) {
|
||||||
var obj = objs[i];
|
var obj = objs[i];
|
||||||
var id = obj[idName];
|
var id = obj[idName];
|
||||||
var value = kvMap.get(id) || [];
|
var value = kvMap.get(id) || [];
|
||||||
|
@ -48,7 +48,7 @@ function buildOneToManyIdentityMapWithOrigKeys(objs, idName) {
|
||||||
*/
|
*/
|
||||||
function join(oneToOneIdMap, oneToManyIdMap, mergeF) {
|
function join(oneToOneIdMap, oneToManyIdMap, mergeF) {
|
||||||
var ids = oneToOneIdMap.getKeys();
|
var ids = oneToOneIdMap.getKeys();
|
||||||
for(var i = 0; i < ids.length; i++) {
|
for (var i = 0; i < ids.length; i++) {
|
||||||
var id = ids[i];
|
var id = ids[i];
|
||||||
var obj = oneToOneIdMap.get(id);
|
var obj = oneToOneIdMap.get(id);
|
||||||
var objectsToMergeIn = oneToManyIdMap.get(id) || [];
|
var objectsToMergeIn = oneToManyIdMap.get(id) || [];
|
||||||
|
@ -62,28 +62,28 @@ function join(oneToOneIdMap, oneToManyIdMap, mergeF) {
|
||||||
* @returns {{set: Function, get: Function, remove: Function, exist: Function, getKeys: Function}}
|
* @returns {{set: Function, get: Function, remove: Function, exist: Function, getKeys: Function}}
|
||||||
* @constructor
|
* @constructor
|
||||||
*/
|
*/
|
||||||
function KVMap(){
|
function KVMap() {
|
||||||
var _originalKeyFieldName = 'originalKey';
|
var _originalKeyFieldName = 'originalKey';
|
||||||
var _valueKeyFieldName = 'value';
|
var _valueKeyFieldName = 'value';
|
||||||
var _dict = {};
|
var _dict = {};
|
||||||
var keyToString = function(key){ return key.toString() };
|
var keyToString = function(key) { return key.toString(); };
|
||||||
var mapImpl = {
|
var mapImpl = {
|
||||||
set: function(key, value){
|
set: function(key, value) {
|
||||||
var recordObj = {};
|
var recordObj = {};
|
||||||
recordObj[_originalKeyFieldName] = key;
|
recordObj[_originalKeyFieldName] = key;
|
||||||
recordObj[_valueKeyFieldName] = value;
|
recordObj[_valueKeyFieldName] = value;
|
||||||
_dict[keyToString(key)] = recordObj;
|
_dict[keyToString(key)] = recordObj;
|
||||||
return true;
|
return true;
|
||||||
},
|
},
|
||||||
get: function(key){
|
get: function(key) {
|
||||||
var storeObj = _dict[keyToString(key)];
|
var storeObj = _dict[keyToString(key)];
|
||||||
if(storeObj) {
|
if (storeObj) {
|
||||||
return storeObj[_valueKeyFieldName];
|
return storeObj[_valueKeyFieldName];
|
||||||
} else {
|
} else {
|
||||||
return undefined;
|
return undefined;
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
remove: function(key){
|
remove: function(key) {
|
||||||
delete _dict[keyToString(key)];
|
delete _dict[keyToString(key)];
|
||||||
return true;
|
return true;
|
||||||
},
|
},
|
||||||
|
@ -91,13 +91,13 @@ function KVMap(){
|
||||||
var result = _dict.hasOwnProperty(keyToString(key));
|
var result = _dict.hasOwnProperty(keyToString(key));
|
||||||
return result;
|
return result;
|
||||||
},
|
},
|
||||||
getKeys: function(){
|
getKeys: function() {
|
||||||
var result = [];
|
var result = [];
|
||||||
for(var key in _dict) {
|
for (var key in _dict) {
|
||||||
result.push(_dict[key][_originalKeyFieldName]);
|
result.push(_dict[key][_originalKeyFieldName]);
|
||||||
}
|
}
|
||||||
return result;
|
return result;
|
||||||
}
|
},
|
||||||
|
|
||||||
};
|
};
|
||||||
return mapImpl;
|
return mapImpl;
|
||||||
|
|
|
@ -62,6 +62,6 @@ module.exports = function getIntrospector(ModelBuilder) {
|
||||||
|
|
||||||
ModelBuilder.introspect = introspectType;
|
ModelBuilder.introspect = introspectType;
|
||||||
return introspectType;
|
return introspectType;
|
||||||
}
|
};
|
||||||
|
|
||||||
|
|
||||||
|
|
12
lib/jutil.js
12
lib/jutil.js
|
@ -10,16 +10,16 @@ var util = require('util');
|
||||||
* @param newClass
|
* @param newClass
|
||||||
* @param baseClass
|
* @param baseClass
|
||||||
*/
|
*/
|
||||||
exports.inherits = function (newClass, baseClass, options) {
|
exports.inherits = function(newClass, baseClass, options) {
|
||||||
util.inherits(newClass, baseClass);
|
util.inherits(newClass, baseClass);
|
||||||
|
|
||||||
options = options || {
|
options = options || {
|
||||||
staticProperties: true,
|
staticProperties: true,
|
||||||
override: false
|
override: false,
|
||||||
};
|
};
|
||||||
|
|
||||||
if (options.staticProperties) {
|
if (options.staticProperties) {
|
||||||
Object.keys(baseClass).forEach(function (classProp) {
|
Object.keys(baseClass).forEach(function(classProp) {
|
||||||
if (classProp !== 'super_' && (!newClass.hasOwnProperty(classProp)
|
if (classProp !== 'super_' && (!newClass.hasOwnProperty(classProp)
|
||||||
|| options.override)) {
|
|| options.override)) {
|
||||||
var pd = Object.getOwnPropertyDescriptor(baseClass, classProp);
|
var pd = Object.getOwnPropertyDescriptor(baseClass, classProp);
|
||||||
|
@ -35,7 +35,7 @@ exports.inherits = function (newClass, baseClass, options) {
|
||||||
* @param mixinClass The class to be mixed in
|
* @param mixinClass The class to be mixed in
|
||||||
* @param options
|
* @param options
|
||||||
*/
|
*/
|
||||||
exports.mixin = function (newClass, mixinClass, options) {
|
exports.mixin = function(newClass, mixinClass, options) {
|
||||||
if (Array.isArray(newClass._mixins)) {
|
if (Array.isArray(newClass._mixins)) {
|
||||||
if (newClass._mixins.indexOf(mixinClass) !== -1) {
|
if (newClass._mixins.indexOf(mixinClass) !== -1) {
|
||||||
return;
|
return;
|
||||||
|
@ -49,7 +49,7 @@ exports.mixin = function (newClass, mixinClass, options) {
|
||||||
staticProperties: true,
|
staticProperties: true,
|
||||||
instanceProperties: true,
|
instanceProperties: true,
|
||||||
override: false,
|
override: false,
|
||||||
proxyFunctions: false
|
proxyFunctions: false,
|
||||||
};
|
};
|
||||||
|
|
||||||
if (options.staticProperties === undefined) {
|
if (options.staticProperties === undefined) {
|
||||||
|
@ -72,7 +72,7 @@ exports.mixin = function (newClass, mixinClass, options) {
|
||||||
};
|
};
|
||||||
|
|
||||||
function mixInto(sourceScope, targetScope, options) {
|
function mixInto(sourceScope, targetScope, options) {
|
||||||
Object.keys(sourceScope).forEach(function (propertyName) {
|
Object.keys(sourceScope).forEach(function(propertyName) {
|
||||||
var targetPropertyExists = targetScope.hasOwnProperty(propertyName);
|
var targetPropertyExists = targetScope.hasOwnProperty(propertyName);
|
||||||
var sourceProperty = Object.getOwnPropertyDescriptor(sourceScope, propertyName);
|
var sourceProperty = Object.getOwnPropertyDescriptor(sourceScope, propertyName);
|
||||||
var targetProperty = targetPropertyExists && Object.getOwnPropertyDescriptor(targetScope, propertyName);
|
var targetProperty = targetPropertyExists && Object.getOwnPropertyDescriptor(targetScope, propertyName);
|
||||||
|
|
20
lib/list.js
20
lib/list.js
|
@ -34,7 +34,7 @@ function List(items, itemType, parent) {
|
||||||
throw err;
|
throw err;
|
||||||
}
|
}
|
||||||
|
|
||||||
if(!itemType) {
|
if (!itemType) {
|
||||||
itemType = items[0] && items[0].constructor;
|
itemType = items[0] && items[0].constructor;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -42,25 +42,25 @@ function List(items, itemType, parent) {
|
||||||
itemType = itemType[0];
|
itemType = itemType[0];
|
||||||
}
|
}
|
||||||
|
|
||||||
if(itemType === Array) {
|
if (itemType === Array) {
|
||||||
itemType = Any;
|
itemType = Any;
|
||||||
}
|
}
|
||||||
|
|
||||||
Object.defineProperty(arr, 'itemType', {
|
Object.defineProperty(arr, 'itemType', {
|
||||||
writable: true,
|
writable: true,
|
||||||
enumerable: false,
|
enumerable: false,
|
||||||
value: itemType
|
value: itemType,
|
||||||
});
|
});
|
||||||
|
|
||||||
if (parent) {
|
if (parent) {
|
||||||
Object.defineProperty(arr, 'parent', {
|
Object.defineProperty(arr, 'parent', {
|
||||||
writable: true,
|
writable: true,
|
||||||
enumerable: false,
|
enumerable: false,
|
||||||
value: parent
|
value: parent,
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
items.forEach(function (item, i) {
|
items.forEach(function(item, i) {
|
||||||
if (itemType && !(item instanceof itemType)) {
|
if (itemType && !(item instanceof itemType)) {
|
||||||
arr[i] = itemType(item);
|
arr[i] = itemType(item);
|
||||||
} else {
|
} else {
|
||||||
|
@ -75,15 +75,15 @@ util.inherits(List, Array);
|
||||||
|
|
||||||
var _push = List.prototype.push;
|
var _push = List.prototype.push;
|
||||||
|
|
||||||
List.prototype.push = function (obj) {
|
List.prototype.push = function(obj) {
|
||||||
var item = this.itemType && (obj instanceof this.itemType) ? obj : this.itemType(obj);
|
var item = this.itemType && (obj instanceof this.itemType) ? obj : this.itemType(obj);
|
||||||
_push.call(this, item);
|
_push.call(this, item);
|
||||||
return item;
|
return item;
|
||||||
};
|
};
|
||||||
|
|
||||||
List.prototype.toObject = function (onlySchema, removeHidden, removeProtected) {
|
List.prototype.toObject = function(onlySchema, removeHidden, removeProtected) {
|
||||||
var items = [];
|
var items = [];
|
||||||
this.forEach(function (item) {
|
this.forEach(function(item) {
|
||||||
if (item && typeof item === 'object' && item.toObject) {
|
if (item && typeof item === 'object' && item.toObject) {
|
||||||
items.push(item.toObject(onlySchema, removeHidden, removeProtected));
|
items.push(item.toObject(onlySchema, removeHidden, removeProtected));
|
||||||
} else {
|
} else {
|
||||||
|
@ -93,11 +93,11 @@ List.prototype.toObject = function (onlySchema, removeHidden, removeProtected) {
|
||||||
return items;
|
return items;
|
||||||
};
|
};
|
||||||
|
|
||||||
List.prototype.toJSON = function () {
|
List.prototype.toJSON = function() {
|
||||||
return this.toObject(true);
|
return this.toObject(true);
|
||||||
};
|
};
|
||||||
|
|
||||||
List.prototype.toString = function () {
|
List.prototype.toString = function() {
|
||||||
return JSON.stringify(this.toJSON());
|
return JSON.stringify(this.toJSON());
|
||||||
};
|
};
|
||||||
|
|
||||||
|
|
|
@ -40,7 +40,7 @@ MixinProvider.prototype.applyMixin = function applyMixin(modelClass, name, optio
|
||||||
} else {
|
} else {
|
||||||
// Try model name
|
// Try model name
|
||||||
var model = this.modelBuilder.getModel(name);
|
var model = this.modelBuilder.getModel(name);
|
||||||
if(model) {
|
if (model) {
|
||||||
debug('Mixin is resolved to a model: %s', name);
|
debug('Mixin is resolved to a model: %s', name);
|
||||||
modelClass.mixin(model, options);
|
modelClass.mixin(model, options);
|
||||||
} else {
|
} else {
|
||||||
|
@ -62,7 +62,7 @@ MixinProvider.prototype.define = function defineMixin(name, mixin) {
|
||||||
debug('Defining mixin: %s', name);
|
debug('Defining mixin: %s', name);
|
||||||
}
|
}
|
||||||
if (isModelClass(mixin)) {
|
if (isModelClass(mixin)) {
|
||||||
this.mixins[name] = function (Model, options) {
|
this.mixins[name] = function(Model, options) {
|
||||||
Model.mixin(mixin, options);
|
Model.mixin(mixin, options);
|
||||||
};
|
};
|
||||||
} else if (typeof mixin === 'function') {
|
} else if (typeof mixin === 'function') {
|
||||||
|
|
|
@ -68,10 +68,10 @@ function isModelClass(cls) {
|
||||||
* @param {Boolean} forceCreate Whether the create a stub for the given name if a model doesn't exist.
|
* @param {Boolean} forceCreate Whether the create a stub for the given name if a model doesn't exist.
|
||||||
* @returns {*} The model class
|
* @returns {*} The model class
|
||||||
*/
|
*/
|
||||||
ModelBuilder.prototype.getModel = function (name, forceCreate) {
|
ModelBuilder.prototype.getModel = function(name, forceCreate) {
|
||||||
var model = this.models[name];
|
var model = this.models[name];
|
||||||
if (!model && forceCreate) {
|
if (!model && forceCreate) {
|
||||||
model = this.define(name, {}, {unresolved: true});
|
model = this.define(name, {}, { unresolved: true });
|
||||||
}
|
}
|
||||||
return model;
|
return model;
|
||||||
};
|
};
|
||||||
|
@ -81,7 +81,7 @@ ModelBuilder.prototype.getModel = function (name, forceCreate) {
|
||||||
* @param {String} name The model name
|
* @param {String} name The model name
|
||||||
* @returns {ModelDefinition} The model definition
|
* @returns {ModelDefinition} The model definition
|
||||||
*/
|
*/
|
||||||
ModelBuilder.prototype.getModelDefinition = function (name) {
|
ModelBuilder.prototype.getModelDefinition = function(name) {
|
||||||
return this.definitions[name];
|
return this.definitions[name];
|
||||||
};
|
};
|
||||||
|
|
||||||
|
@ -214,7 +214,7 @@ ModelBuilder.prototype.define = function defineClass(className, properties, sett
|
||||||
|
|
||||||
// Return the unresolved model
|
// Return the unresolved model
|
||||||
if (settings.unresolved) {
|
if (settings.unresolved) {
|
||||||
ModelClass.settings = {unresolved: true};
|
ModelClass.settings = { unresolved: true };
|
||||||
return ModelClass;
|
return ModelClass;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -241,7 +241,7 @@ ModelBuilder.prototype.define = function defineClass(className, properties, sett
|
||||||
|
|
||||||
// Load and inject the model classes
|
// Load and inject the model classes
|
||||||
if (settings.models) {
|
if (settings.models) {
|
||||||
Object.keys(settings.models).forEach(function (m) {
|
Object.keys(settings.models).forEach(function(m) {
|
||||||
var model = settings.models[m];
|
var model = settings.models[m];
|
||||||
ModelClass[m] = typeof model === 'string' ? modelBuilder.getModel(model, true) : model;
|
ModelClass[m] = typeof model === 'string' ? modelBuilder.getModel(model, true) : model;
|
||||||
});
|
});
|
||||||
|
@ -297,18 +297,18 @@ ModelBuilder.prototype.define = function defineClass(className, properties, sett
|
||||||
var idProp = idNames[0];
|
var idProp = idNames[0];
|
||||||
if (idProp !== 'id') {
|
if (idProp !== 'id') {
|
||||||
Object.defineProperty(ModelClass.prototype, 'id', {
|
Object.defineProperty(ModelClass.prototype, 'id', {
|
||||||
get: function () {
|
get: function() {
|
||||||
var idProp = ModelClass.definition.idNames()[0];
|
var idProp = ModelClass.definition.idNames()[0];
|
||||||
return this.__data[idProp];
|
return this.__data[idProp];
|
||||||
},
|
},
|
||||||
configurable: true,
|
configurable: true,
|
||||||
enumerable: false
|
enumerable: false,
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
// Now the id property is an object that consists of multiple keys
|
// Now the id property is an object that consists of multiple keys
|
||||||
Object.defineProperty(ModelClass.prototype, 'id', {
|
Object.defineProperty(ModelClass.prototype, 'id', {
|
||||||
get: function () {
|
get: function() {
|
||||||
var compositeId = {};
|
var compositeId = {};
|
||||||
var idNames = ModelClass.definition.idNames();
|
var idNames = ModelClass.definition.idNames();
|
||||||
for (var i = 0, p; i < idNames.length; i++) {
|
for (var i = 0, p; i < idNames.length; i++) {
|
||||||
|
@ -318,12 +318,12 @@ ModelBuilder.prototype.define = function defineClass(className, properties, sett
|
||||||
return compositeId;
|
return compositeId;
|
||||||
},
|
},
|
||||||
configurable: true,
|
configurable: true,
|
||||||
enumerable: false
|
enumerable: false,
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
// A function to loop through the properties
|
// A function to loop through the properties
|
||||||
ModelClass.forEachProperty = function (cb) {
|
ModelClass.forEachProperty = function(cb) {
|
||||||
var props = ModelClass.definition.properties;
|
var props = ModelClass.definition.properties;
|
||||||
var keys = Object.keys(props);
|
var keys = Object.keys(props);
|
||||||
for (var i = 0, n = keys.length; i < n; i++) {
|
for (var i = 0, n = keys.length; i < n; i++) {
|
||||||
|
@ -332,7 +332,7 @@ ModelBuilder.prototype.define = function defineClass(className, properties, sett
|
||||||
};
|
};
|
||||||
|
|
||||||
// A function to attach the model class to a data source
|
// A function to attach the model class to a data source
|
||||||
ModelClass.attachTo = function (dataSource) {
|
ModelClass.attachTo = function(dataSource) {
|
||||||
dataSource.attach(this);
|
dataSource.attach(this);
|
||||||
};
|
};
|
||||||
|
|
||||||
|
@ -356,7 +356,7 @@ ModelBuilder.prototype.define = function defineClass(className, properties, sett
|
||||||
* @options {Object} settings Model settings, such as relations and acls.
|
* @options {Object} settings Model settings, such as relations and acls.
|
||||||
*
|
*
|
||||||
*/
|
*/
|
||||||
ModelClass.extend = function (className, subclassProperties, subclassSettings) {
|
ModelClass.extend = function(className, subclassProperties, subclassSettings) {
|
||||||
var properties = ModelClass.definition.properties;
|
var properties = ModelClass.definition.properties;
|
||||||
var settings = ModelClass.definition.settings;
|
var settings = ModelClass.definition.settings;
|
||||||
|
|
||||||
|
@ -418,7 +418,7 @@ ModelBuilder.prototype.define = function defineClass(className, properties, sett
|
||||||
* Register a property for the model class
|
* Register a property for the model class
|
||||||
* @param {String} propertyName Name of the property.
|
* @param {String} propertyName Name of the property.
|
||||||
*/
|
*/
|
||||||
ModelClass.registerProperty = function (propertyName) {
|
ModelClass.registerProperty = function(propertyName) {
|
||||||
var properties = modelDefinition.build();
|
var properties = modelDefinition.build();
|
||||||
var prop = properties[propertyName];
|
var prop = properties[propertyName];
|
||||||
var DataType = prop.type;
|
var DataType = prop.type;
|
||||||
|
@ -432,14 +432,14 @@ ModelBuilder.prototype.define = function defineClass(className, properties, sett
|
||||||
}
|
}
|
||||||
|
|
||||||
Object.defineProperty(ModelClass.prototype, propertyName, {
|
Object.defineProperty(ModelClass.prototype, propertyName, {
|
||||||
get: function () {
|
get: function() {
|
||||||
if (ModelClass.getter[propertyName]) {
|
if (ModelClass.getter[propertyName]) {
|
||||||
return ModelClass.getter[propertyName].call(this); // Try getter first
|
return ModelClass.getter[propertyName].call(this); // Try getter first
|
||||||
} else {
|
} else {
|
||||||
return this.__data && this.__data[propertyName]; // Try __data
|
return this.__data && this.__data[propertyName]; // Try __data
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
set: function (value) {
|
set: function(value) {
|
||||||
var DataType = ModelClass.definition.properties[propertyName].type;
|
var DataType = ModelClass.definition.properties[propertyName].type;
|
||||||
if (Array.isArray(DataType) || DataType === Array) {
|
if (Array.isArray(DataType) || DataType === Array) {
|
||||||
DataType = List;
|
DataType = List;
|
||||||
|
@ -474,23 +474,23 @@ ModelBuilder.prototype.define = function defineClass(className, properties, sett
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
configurable: true,
|
configurable: true,
|
||||||
enumerable: true
|
enumerable: true,
|
||||||
});
|
});
|
||||||
|
|
||||||
// FIXME: [rfeng] Do we need to keep the raw data?
|
// FIXME: [rfeng] Do we need to keep the raw data?
|
||||||
// Use $ as the prefix to avoid conflicts with properties such as _id
|
// Use $ as the prefix to avoid conflicts with properties such as _id
|
||||||
Object.defineProperty(ModelClass.prototype, '$' + propertyName, {
|
Object.defineProperty(ModelClass.prototype, '$' + propertyName, {
|
||||||
get: function () {
|
get: function() {
|
||||||
return this.__data && this.__data[propertyName];
|
return this.__data && this.__data[propertyName];
|
||||||
},
|
},
|
||||||
set: function (value) {
|
set: function(value) {
|
||||||
if (!this.__data) {
|
if (!this.__data) {
|
||||||
this.__data = {};
|
this.__data = {};
|
||||||
}
|
}
|
||||||
this.__data[propertyName] = value;
|
this.__data[propertyName] = value;
|
||||||
},
|
},
|
||||||
configurable: true,
|
configurable: true,
|
||||||
enumerable: false
|
enumerable: false,
|
||||||
});
|
});
|
||||||
};
|
};
|
||||||
|
|
||||||
|
@ -563,7 +563,7 @@ function BooleanType(arg) {
|
||||||
* @param {String} propertyName Name of property
|
* @param {String} propertyName Name of property
|
||||||
* @param {Object} propertyDefinition Property settings
|
* @param {Object} propertyDefinition Property settings
|
||||||
*/
|
*/
|
||||||
ModelBuilder.prototype.defineProperty = function (model, propertyName, propertyDefinition) {
|
ModelBuilder.prototype.defineProperty = function(model, propertyName, propertyDefinition) {
|
||||||
this.definitions[model].defineProperty(propertyName, propertyDefinition);
|
this.definitions[model].defineProperty(propertyName, propertyDefinition);
|
||||||
this.models[model].registerProperty(propertyName);
|
this.models[model].registerProperty(propertyName);
|
||||||
};
|
};
|
||||||
|
@ -607,7 +607,7 @@ ModelBuilder.prototype.defineValueType = function(type, aliases) {
|
||||||
* @property {String} type Datatype of property: Must be an [LDL type](http://docs.strongloop.com/display/LB/LoopBack+types).
|
* @property {String} type Datatype of property: Must be an [LDL type](http://docs.strongloop.com/display/LB/LoopBack+types).
|
||||||
* @property {Boolean} index True if the property is an index; false otherwise.
|
* @property {Boolean} index True if the property is an index; false otherwise.
|
||||||
*/
|
*/
|
||||||
ModelBuilder.prototype.extendModel = function (model, props) {
|
ModelBuilder.prototype.extendModel = function(model, props) {
|
||||||
var t = this;
|
var t = this;
|
||||||
var keys = Object.keys(props);
|
var keys = Object.keys(props);
|
||||||
for (var i = 0; i < keys.length; i++) {
|
for (var i = 0; i < keys.length; i++) {
|
||||||
|
@ -638,7 +638,7 @@ ModelBuilder.prototype.copyModel = function copyModel(Master) {
|
||||||
modelBuilder.models[className] = Slave;
|
modelBuilder.models[className] = Slave;
|
||||||
modelBuilder.definitions[className] = {
|
modelBuilder.definitions[className] = {
|
||||||
properties: md.properties,
|
properties: md.properties,
|
||||||
settings: md.settings
|
settings: md.settings,
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -653,14 +653,14 @@ function hiddenProperty(where, property, value) {
|
||||||
writable: true,
|
writable: true,
|
||||||
enumerable: false,
|
enumerable: false,
|
||||||
configurable: true,
|
configurable: true,
|
||||||
value: value
|
value: value,
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Get the schema name
|
* Get the schema name
|
||||||
*/
|
*/
|
||||||
ModelBuilder.prototype.getSchemaName = function (name) {
|
ModelBuilder.prototype.getSchemaName = function(name) {
|
||||||
if (name) {
|
if (name) {
|
||||||
return name;
|
return name;
|
||||||
}
|
}
|
||||||
|
@ -677,7 +677,7 @@ ModelBuilder.prototype.getSchemaName = function (name) {
|
||||||
* Returns {Function} if the type is resolved
|
* Returns {Function} if the type is resolved
|
||||||
* @param {String} type The type string, such as 'number', 'Number', 'boolean', or 'String'. It's case insensitive
|
* @param {String} type The type string, such as 'number', 'Number', 'boolean', or 'String'. It's case insensitive
|
||||||
*/
|
*/
|
||||||
ModelBuilder.prototype.resolveType = function (type) {
|
ModelBuilder.prototype.resolveType = function(type) {
|
||||||
if (!type) {
|
if (!type) {
|
||||||
return type;
|
return type;
|
||||||
}
|
}
|
||||||
|
@ -697,7 +697,7 @@ ModelBuilder.prototype.resolveType = function (type) {
|
||||||
return schemaType;
|
return schemaType;
|
||||||
} else {
|
} else {
|
||||||
// The type cannot be resolved, let's create a place holder
|
// The type cannot be resolved, let's create a place holder
|
||||||
type = this.define(type, {}, {unresolved: true});
|
type = this.define(type, {}, { unresolved: true });
|
||||||
return type;
|
return type;
|
||||||
}
|
}
|
||||||
} else if (type.constructor.name === 'Object') {
|
} else if (type.constructor.name === 'Object') {
|
||||||
|
@ -706,7 +706,7 @@ ModelBuilder.prototype.resolveType = function (type) {
|
||||||
return this.resolveType(type.type);
|
return this.resolveType(type.type);
|
||||||
} else {
|
} else {
|
||||||
return this.define(this.getSchemaName(null),
|
return this.define(this.getSchemaName(null),
|
||||||
type, {anonymous: true, idInjection: false});
|
type, { anonymous: true, idInjection: false });
|
||||||
}
|
}
|
||||||
} else if ('function' === typeof type) {
|
} else if ('function' === typeof type) {
|
||||||
return type;
|
return type;
|
||||||
|
@ -726,7 +726,7 @@ ModelBuilder.prototype.resolveType = function (type) {
|
||||||
* @param {*} schemas The schemas
|
* @param {*} schemas The schemas
|
||||||
* @returns {Object} A map of model constructors keyed by model name
|
* @returns {Object} A map of model constructors keyed by model name
|
||||||
*/
|
*/
|
||||||
ModelBuilder.prototype.buildModels = function (schemas, createModel) {
|
ModelBuilder.prototype.buildModels = function(schemas, createModel) {
|
||||||
var models = {};
|
var models = {};
|
||||||
|
|
||||||
// Normalize the schemas to be an array of the schema objects {name: <name>, properties: {}, options: {}}
|
// Normalize the schemas to be an array of the schema objects {name: <name>, properties: {}, options: {}}
|
||||||
|
@ -740,8 +740,8 @@ ModelBuilder.prototype.buildModels = function (schemas, createModel) {
|
||||||
{
|
{
|
||||||
name: this.getSchemaName(),
|
name: this.getSchemaName(),
|
||||||
properties: schemas,
|
properties: schemas,
|
||||||
options: {anonymous: true}
|
options: { anonymous: true },
|
||||||
}
|
},
|
||||||
];
|
];
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -751,7 +751,7 @@ ModelBuilder.prototype.buildModels = function (schemas, createModel) {
|
||||||
var name = this.getSchemaName(schemas[s].name);
|
var name = this.getSchemaName(schemas[s].name);
|
||||||
schemas[s].name = name;
|
schemas[s].name = name;
|
||||||
var model;
|
var model;
|
||||||
if(typeof createModel === 'function') {
|
if (typeof createModel === 'function') {
|
||||||
model = createModel(schemas[s].name, schemas[s].properties, schemas[s].options);
|
model = createModel(schemas[s].name, schemas[s].properties, schemas[s].options);
|
||||||
} else {
|
} else {
|
||||||
model = this.define(schemas[s].name, schemas[s].properties, schemas[s].options);
|
model = this.define(schemas[s].name, schemas[s].properties, schemas[s].options);
|
||||||
|
@ -767,7 +767,7 @@ ModelBuilder.prototype.buildModels = function (schemas, createModel) {
|
||||||
var targetModel = models[relation.target];
|
var targetModel = models[relation.target];
|
||||||
if (sourceModel && targetModel) {
|
if (sourceModel && targetModel) {
|
||||||
if (typeof sourceModel[relation.type] === 'function') {
|
if (typeof sourceModel[relation.type] === 'function') {
|
||||||
sourceModel[relation.type](targetModel, {as: relation.as});
|
sourceModel[relation.type](targetModel, { as: relation.as });
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -781,7 +781,7 @@ ModelBuilder.prototype.buildModels = function (schemas, createModel) {
|
||||||
* @param {Object} options The options
|
* @param {Object} options The options
|
||||||
* @returns {}
|
* @returns {}
|
||||||
*/
|
*/
|
||||||
ModelBuilder.prototype.buildModelFromInstance = function (name, json, options) {
|
ModelBuilder.prototype.buildModelFromInstance = function(name, json, options) {
|
||||||
|
|
||||||
// Introspect the JSON document to generate a schema
|
// Introspect the JSON document to generate a schema
|
||||||
var schema = introspect(json);
|
var schema = introspect(json);
|
||||||
|
|
|
@ -58,7 +58,7 @@ require('./types')(ModelDefinition);
|
||||||
* Return table name for specified `modelName`
|
* Return table name for specified `modelName`
|
||||||
* @param {String} connectorType The connector type, such as 'oracle' or 'mongodb'
|
* @param {String} connectorType The connector type, such as 'oracle' or 'mongodb'
|
||||||
*/
|
*/
|
||||||
ModelDefinition.prototype.tableName = function (connectorType) {
|
ModelDefinition.prototype.tableName = function(connectorType) {
|
||||||
var settings = this.settings;
|
var settings = this.settings;
|
||||||
if (settings[connectorType]) {
|
if (settings[connectorType]) {
|
||||||
return settings[connectorType].table || settings[connectorType].tableName || this.name;
|
return settings[connectorType].table || settings[connectorType].tableName || this.name;
|
||||||
|
@ -73,7 +73,7 @@ ModelDefinition.prototype.tableName = function (connectorType) {
|
||||||
* @param propertyName The property name
|
* @param propertyName The property name
|
||||||
* @returns {String} columnName
|
* @returns {String} columnName
|
||||||
*/
|
*/
|
||||||
ModelDefinition.prototype.columnName = function (connectorType, propertyName) {
|
ModelDefinition.prototype.columnName = function(connectorType, propertyName) {
|
||||||
if (!propertyName) {
|
if (!propertyName) {
|
||||||
return propertyName;
|
return propertyName;
|
||||||
}
|
}
|
||||||
|
@ -92,7 +92,7 @@ ModelDefinition.prototype.columnName = function (connectorType, propertyName) {
|
||||||
* @param propertyName The property name
|
* @param propertyName The property name
|
||||||
* @returns {Object} column metadata
|
* @returns {Object} column metadata
|
||||||
*/
|
*/
|
||||||
ModelDefinition.prototype.columnMetadata = function (connectorType, propertyName) {
|
ModelDefinition.prototype.columnMetadata = function(connectorType, propertyName) {
|
||||||
if (!propertyName) {
|
if (!propertyName) {
|
||||||
return propertyName;
|
return propertyName;
|
||||||
}
|
}
|
||||||
|
@ -110,7 +110,7 @@ ModelDefinition.prototype.columnMetadata = function (connectorType, propertyName
|
||||||
* @param {String} connectorType The connector type, such as 'oracle' or 'mongodb'
|
* @param {String} connectorType The connector type, such as 'oracle' or 'mongodb'
|
||||||
* @returns {String[]} column names
|
* @returns {String[]} column names
|
||||||
*/
|
*/
|
||||||
ModelDefinition.prototype.columnNames = function (connectorType) {
|
ModelDefinition.prototype.columnNames = function(connectorType) {
|
||||||
this.build();
|
this.build();
|
||||||
var props = this.properties;
|
var props = this.properties;
|
||||||
var cols = [];
|
var cols = [];
|
||||||
|
@ -128,7 +128,7 @@ ModelDefinition.prototype.columnNames = function (connectorType) {
|
||||||
* Find the ID properties sorted by the index
|
* Find the ID properties sorted by the index
|
||||||
* @returns {Object[]} property name/index for IDs
|
* @returns {Object[]} property name/index for IDs
|
||||||
*/
|
*/
|
||||||
ModelDefinition.prototype.ids = function () {
|
ModelDefinition.prototype.ids = function() {
|
||||||
if (this._ids) {
|
if (this._ids) {
|
||||||
return this._ids;
|
return this._ids;
|
||||||
}
|
}
|
||||||
|
@ -143,9 +143,9 @@ ModelDefinition.prototype.ids = function () {
|
||||||
if (typeof id !== 'number') {
|
if (typeof id !== 'number') {
|
||||||
id = 1;
|
id = 1;
|
||||||
}
|
}
|
||||||
ids.push({name: key, id: id, property: props[key]});
|
ids.push({ name: key, id: id, property: props[key] });
|
||||||
}
|
}
|
||||||
ids.sort(function (a, b) {
|
ids.sort(function(a, b) {
|
||||||
return a.id - b.id;
|
return a.id - b.id;
|
||||||
});
|
});
|
||||||
this._ids = ids;
|
this._ids = ids;
|
||||||
|
@ -157,7 +157,7 @@ ModelDefinition.prototype.ids = function () {
|
||||||
* @param {String} modelName The model name
|
* @param {String} modelName The model name
|
||||||
* @returns {String} columnName for ID
|
* @returns {String} columnName for ID
|
||||||
*/
|
*/
|
||||||
ModelDefinition.prototype.idColumnName = function (connectorType) {
|
ModelDefinition.prototype.idColumnName = function(connectorType) {
|
||||||
return this.columnName(connectorType, this.idName());
|
return this.columnName(connectorType, this.idName());
|
||||||
};
|
};
|
||||||
|
|
||||||
|
@ -165,7 +165,7 @@ ModelDefinition.prototype.idColumnName = function (connectorType) {
|
||||||
* Find the ID property name
|
* Find the ID property name
|
||||||
* @returns {String} property name for ID
|
* @returns {String} property name for ID
|
||||||
*/
|
*/
|
||||||
ModelDefinition.prototype.idName = function () {
|
ModelDefinition.prototype.idName = function() {
|
||||||
var id = this.ids()[0];
|
var id = this.ids()[0];
|
||||||
if (this.properties.id && this.properties.id.id) {
|
if (this.properties.id && this.properties.id.id) {
|
||||||
return 'id';
|
return 'id';
|
||||||
|
@ -178,9 +178,9 @@ ModelDefinition.prototype.idName = function () {
|
||||||
* Find the ID property names sorted by the index
|
* Find the ID property names sorted by the index
|
||||||
* @returns {String[]} property names for IDs
|
* @returns {String[]} property names for IDs
|
||||||
*/
|
*/
|
||||||
ModelDefinition.prototype.idNames = function () {
|
ModelDefinition.prototype.idNames = function() {
|
||||||
var ids = this.ids();
|
var ids = this.ids();
|
||||||
var names = ids.map(function (id) {
|
var names = ids.map(function(id) {
|
||||||
return id.name;
|
return id.name;
|
||||||
});
|
});
|
||||||
return names;
|
return names;
|
||||||
|
@ -190,7 +190,7 @@ ModelDefinition.prototype.idNames = function () {
|
||||||
*
|
*
|
||||||
* @returns {{}}
|
* @returns {{}}
|
||||||
*/
|
*/
|
||||||
ModelDefinition.prototype.indexes = function () {
|
ModelDefinition.prototype.indexes = function() {
|
||||||
this.build();
|
this.build();
|
||||||
var indexes = {};
|
var indexes = {};
|
||||||
if (this.settings.indexes) {
|
if (this.settings.indexes) {
|
||||||
|
@ -210,7 +210,7 @@ ModelDefinition.prototype.indexes = function () {
|
||||||
* Build a model definition
|
* Build a model definition
|
||||||
* @param {Boolean} force Forcing rebuild
|
* @param {Boolean} force Forcing rebuild
|
||||||
*/
|
*/
|
||||||
ModelDefinition.prototype.build = function (forceRebuild) {
|
ModelDefinition.prototype.build = function(forceRebuild) {
|
||||||
if (forceRebuild) {
|
if (forceRebuild) {
|
||||||
this.properties = null;
|
this.properties = null;
|
||||||
this.relations = [];
|
this.relations = [];
|
||||||
|
@ -229,11 +229,11 @@ ModelDefinition.prototype.build = function (forceRebuild) {
|
||||||
source: this.name,
|
source: this.name,
|
||||||
target: type,
|
target: type,
|
||||||
type: Array.isArray(prop) ? 'hasMany' : 'belongsTo',
|
type: Array.isArray(prop) ? 'hasMany' : 'belongsTo',
|
||||||
as: p
|
as: p,
|
||||||
});
|
});
|
||||||
} else {
|
} else {
|
||||||
var typeDef = {
|
var typeDef = {
|
||||||
type: type
|
type: type,
|
||||||
};
|
};
|
||||||
if (typeof prop === 'object' && prop !== null) {
|
if (typeof prop === 'object' && prop !== null) {
|
||||||
for (var a in prop) {
|
for (var a in prop) {
|
||||||
|
@ -254,7 +254,7 @@ ModelDefinition.prototype.build = function (forceRebuild) {
|
||||||
* @param {String} propertyName The property name
|
* @param {String} propertyName The property name
|
||||||
* @param {Object} propertyDefinition The property definition
|
* @param {Object} propertyDefinition The property definition
|
||||||
*/
|
*/
|
||||||
ModelDefinition.prototype.defineProperty = function (propertyName, propertyDefinition) {
|
ModelDefinition.prototype.defineProperty = function(propertyName, propertyDefinition) {
|
||||||
this.rawProperties[propertyName] = propertyDefinition;
|
this.rawProperties[propertyName] = propertyDefinition;
|
||||||
this.build(true);
|
this.build(true);
|
||||||
};
|
};
|
||||||
|
@ -266,7 +266,7 @@ function isModelClass(cls) {
|
||||||
return cls.prototype instanceof ModelBaseClass;
|
return cls.prototype instanceof ModelBaseClass;
|
||||||
}
|
}
|
||||||
|
|
||||||
ModelDefinition.prototype.toJSON = function (forceRebuild) {
|
ModelDefinition.prototype.toJSON = function(forceRebuild) {
|
||||||
if (forceRebuild) {
|
if (forceRebuild) {
|
||||||
this.json = null;
|
this.json = null;
|
||||||
}
|
}
|
||||||
|
@ -276,11 +276,11 @@ ModelDefinition.prototype.toJSON = function (forceRebuild) {
|
||||||
var json = {
|
var json = {
|
||||||
name: this.name,
|
name: this.name,
|
||||||
properties: {},
|
properties: {},
|
||||||
settings: this.settings
|
settings: this.settings,
|
||||||
};
|
};
|
||||||
this.build(forceRebuild);
|
this.build(forceRebuild);
|
||||||
|
|
||||||
var mapper = function (val) {
|
var mapper = function(val) {
|
||||||
if (val === undefined || val === null) {
|
if (val === undefined || val === null) {
|
||||||
return val;
|
return val;
|
||||||
}
|
}
|
||||||
|
|
62
lib/model.js
62
lib/model.js
|
@ -31,7 +31,7 @@ var BASE_TYPES = {
|
||||||
'Number': true,
|
'Number': true,
|
||||||
'Date': true,
|
'Date': true,
|
||||||
'Text': true,
|
'Text': true,
|
||||||
'ObjectID': true
|
'ObjectID': true,
|
||||||
};
|
};
|
||||||
|
|
||||||
/**
|
/**
|
||||||
|
@ -44,7 +44,7 @@ var BASE_TYPES = {
|
||||||
*/
|
*/
|
||||||
function ModelBaseClass(data, options) {
|
function ModelBaseClass(data, options) {
|
||||||
options = options || {};
|
options = options || {};
|
||||||
if(!('applySetters' in options)) {
|
if (!('applySetters' in options)) {
|
||||||
// Default to true
|
// Default to true
|
||||||
options.applySetters = true;
|
options.applySetters = true;
|
||||||
}
|
}
|
||||||
|
@ -64,11 +64,11 @@ function ModelBaseClass(data, options) {
|
||||||
* @property {Boolean} persisted Whether the instance has been persisted
|
* @property {Boolean} persisted Whether the instance has been persisted
|
||||||
* @private
|
* @private
|
||||||
*/
|
*/
|
||||||
ModelBaseClass.prototype._initProperties = function (data, options) {
|
ModelBaseClass.prototype._initProperties = function(data, options) {
|
||||||
var self = this;
|
var self = this;
|
||||||
var ctor = this.constructor;
|
var ctor = this.constructor;
|
||||||
|
|
||||||
if(data instanceof ctor) {
|
if (data instanceof ctor) {
|
||||||
// Convert the data to be plain object to avoid pollutions
|
// Convert the data to be plain object to avoid pollutions
|
||||||
data = data.toObject(false);
|
data = data.toObject(false);
|
||||||
}
|
}
|
||||||
|
@ -84,7 +84,7 @@ ModelBaseClass.prototype._initProperties = function (data, options) {
|
||||||
var applyDefaultValues = options.applyDefaultValues;
|
var applyDefaultValues = options.applyDefaultValues;
|
||||||
var strict = options.strict;
|
var strict = options.strict;
|
||||||
|
|
||||||
if(strict === undefined) {
|
if (strict === undefined) {
|
||||||
strict = ctor.definition.settings.strict;
|
strict = ctor.definition.settings.strict;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -99,14 +99,14 @@ ModelBaseClass.prototype._initProperties = function (data, options) {
|
||||||
writable: true,
|
writable: true,
|
||||||
enumerable: false,
|
enumerable: false,
|
||||||
configurable: true,
|
configurable: true,
|
||||||
value: {}
|
value: {},
|
||||||
},
|
},
|
||||||
|
|
||||||
__data: {
|
__data: {
|
||||||
writable: true,
|
writable: true,
|
||||||
enumerable: false,
|
enumerable: false,
|
||||||
configurable: true,
|
configurable: true,
|
||||||
value: {}
|
value: {},
|
||||||
},
|
},
|
||||||
|
|
||||||
// Instance level data source
|
// Instance level data source
|
||||||
|
@ -114,7 +114,7 @@ ModelBaseClass.prototype._initProperties = function (data, options) {
|
||||||
writable: true,
|
writable: true,
|
||||||
enumerable: false,
|
enumerable: false,
|
||||||
configurable: true,
|
configurable: true,
|
||||||
value: options.dataSource
|
value: options.dataSource,
|
||||||
},
|
},
|
||||||
|
|
||||||
// Instance level strict mode
|
// Instance level strict mode
|
||||||
|
@ -122,14 +122,14 @@ ModelBaseClass.prototype._initProperties = function (data, options) {
|
||||||
writable: true,
|
writable: true,
|
||||||
enumerable: false,
|
enumerable: false,
|
||||||
configurable: true,
|
configurable: true,
|
||||||
value: strict
|
value: strict,
|
||||||
},
|
},
|
||||||
|
|
||||||
__persisted: {
|
__persisted: {
|
||||||
writable: true,
|
writable: true,
|
||||||
enumerable: false,
|
enumerable: false,
|
||||||
configurable: true,
|
configurable: true,
|
||||||
value: false
|
value: false,
|
||||||
},
|
},
|
||||||
});
|
});
|
||||||
|
|
||||||
|
@ -138,7 +138,7 @@ ModelBaseClass.prototype._initProperties = function (data, options) {
|
||||||
writable: true,
|
writable: true,
|
||||||
enumerable: false,
|
enumerable: false,
|
||||||
configrable: true,
|
configrable: true,
|
||||||
value: []
|
value: [],
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
|
@ -320,13 +320,13 @@ ModelBaseClass.prototype._initProperties = function (data, options) {
|
||||||
if (type.prototype instanceof ModelBaseClass) {
|
if (type.prototype instanceof ModelBaseClass) {
|
||||||
if (!(self.__data[p] instanceof type)
|
if (!(self.__data[p] instanceof type)
|
||||||
&& typeof self.__data[p] === 'object'
|
&& typeof self.__data[p] === 'object'
|
||||||
&& self.__data[p] !== null ) {
|
&& self.__data[p] !== null) {
|
||||||
self.__data[p] = new type(self.__data[p]);
|
self.__data[p] = new type(self.__data[p]);
|
||||||
}
|
}
|
||||||
} else if (type.name === 'Array' || Array.isArray(type)) {
|
} else if (type.name === 'Array' || Array.isArray(type)) {
|
||||||
if (!(self.__data[p] instanceof List)
|
if (!(self.__data[p] instanceof List)
|
||||||
&& self.__data[p] !== undefined
|
&& self.__data[p] !== undefined
|
||||||
&& self.__data[p] !== null ) {
|
&& self.__data[p] !== null) {
|
||||||
self.__data[p] = List(self.__data[p], type, self);
|
self.__data[p] = List(self.__data[p], type, self);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -340,15 +340,15 @@ ModelBaseClass.prototype._initProperties = function (data, options) {
|
||||||
* @param {String} prop Property name
|
* @param {String} prop Property name
|
||||||
* @param {Object} params Various property configuration
|
* @param {Object} params Various property configuration
|
||||||
*/
|
*/
|
||||||
ModelBaseClass.defineProperty = function (prop, params) {
|
ModelBaseClass.defineProperty = function(prop, params) {
|
||||||
if(this.dataSource) {
|
if (this.dataSource) {
|
||||||
this.dataSource.defineProperty(this.modelName, prop, params);
|
this.dataSource.defineProperty(this.modelName, prop, params);
|
||||||
} else {
|
} else {
|
||||||
this.modelBuilder.defineProperty(this.modelName, prop, params);
|
this.modelBuilder.defineProperty(this.modelName, prop, params);
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
ModelBaseClass.getPropertyType = function (propName) {
|
ModelBaseClass.getPropertyType = function(propName) {
|
||||||
var prop = this.definition.properties[propName];
|
var prop = this.definition.properties[propName];
|
||||||
if (!prop) {
|
if (!prop) {
|
||||||
// The property is not part of the definition
|
// The property is not part of the definition
|
||||||
|
@ -361,7 +361,7 @@ ModelBaseClass.getPropertyType = function (propName) {
|
||||||
return prop.type.name;
|
return prop.type.name;
|
||||||
};
|
};
|
||||||
|
|
||||||
ModelBaseClass.prototype.getPropertyType = function (propName) {
|
ModelBaseClass.prototype.getPropertyType = function(propName) {
|
||||||
return this.constructor.getPropertyType(propName);
|
return this.constructor.getPropertyType(propName);
|
||||||
};
|
};
|
||||||
|
|
||||||
|
@ -369,7 +369,7 @@ ModelBaseClass.prototype.getPropertyType = function (propName) {
|
||||||
* Return string representation of class
|
* Return string representation of class
|
||||||
* This overrides the default `toString()` method
|
* This overrides the default `toString()` method
|
||||||
*/
|
*/
|
||||||
ModelBaseClass.toString = function () {
|
ModelBaseClass.toString = function() {
|
||||||
return '[Model ' + this.modelName + ']';
|
return '[Model ' + this.modelName + ']';
|
||||||
};
|
};
|
||||||
|
|
||||||
|
@ -379,7 +379,7 @@ ModelBaseClass.toString = function () {
|
||||||
*
|
*
|
||||||
* @param {Boolean} onlySchema Restrict properties to dataSource only. Default is false. If true, the function returns only properties defined in the schema; Otherwise it returns all enumerable properties.
|
* @param {Boolean} onlySchema Restrict properties to dataSource only. Default is false. If true, the function returns only properties defined in the schema; Otherwise it returns all enumerable properties.
|
||||||
*/
|
*/
|
||||||
ModelBaseClass.prototype.toObject = function (onlySchema, removeHidden, removeProtected) {
|
ModelBaseClass.prototype.toObject = function(onlySchema, removeHidden, removeProtected) {
|
||||||
if (onlySchema === undefined) {
|
if (onlySchema === undefined) {
|
||||||
onlySchema = true;
|
onlySchema = true;
|
||||||
}
|
}
|
||||||
|
@ -504,7 +504,7 @@ ModelBaseClass.prototype.toObject = function (onlySchema, removeHidden, removePr
|
||||||
return data;
|
return data;
|
||||||
};
|
};
|
||||||
|
|
||||||
ModelBaseClass.isProtectedProperty = function (propertyName) {
|
ModelBaseClass.isProtectedProperty = function(propertyName) {
|
||||||
var Model = this;
|
var Model = this;
|
||||||
var settings = Model.definition && Model.definition.settings;
|
var settings = Model.definition && Model.definition.settings;
|
||||||
var protectedProperties = settings && (settings.protectedProperties || settings.protected);
|
var protectedProperties = settings && (settings.protectedProperties || settings.protected);
|
||||||
|
@ -523,7 +523,7 @@ ModelBaseClass.isProtectedProperty = function (propertyName) {
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
ModelBaseClass.isHiddenProperty = function (propertyName) {
|
ModelBaseClass.isHiddenProperty = function(propertyName) {
|
||||||
var Model = this;
|
var Model = this;
|
||||||
var settings = Model.definition && Model.definition.settings;
|
var settings = Model.definition && Model.definition.settings;
|
||||||
var hiddenProperties = settings && (settings.hiddenProperties || settings.hidden);
|
var hiddenProperties = settings && (settings.hiddenProperties || settings.hidden);
|
||||||
|
@ -542,11 +542,11 @@ ModelBaseClass.isHiddenProperty = function (propertyName) {
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
ModelBaseClass.prototype.toJSON = function () {
|
ModelBaseClass.prototype.toJSON = function() {
|
||||||
return this.toObject(false, true, false);
|
return this.toObject(false, true, false);
|
||||||
};
|
};
|
||||||
|
|
||||||
ModelBaseClass.prototype.fromObject = function (obj) {
|
ModelBaseClass.prototype.fromObject = function(obj) {
|
||||||
for (var key in obj) {
|
for (var key in obj) {
|
||||||
this[key] = obj[key];
|
this[key] = obj[key];
|
||||||
}
|
}
|
||||||
|
@ -557,7 +557,7 @@ ModelBaseClass.prototype.fromObject = function (obj) {
|
||||||
* This method does not perform any database operations; it just resets the object to its
|
* This method does not perform any database operations; it just resets the object to its
|
||||||
* initial state.
|
* initial state.
|
||||||
*/
|
*/
|
||||||
ModelBaseClass.prototype.reset = function () {
|
ModelBaseClass.prototype.reset = function() {
|
||||||
var obj = this;
|
var obj = this;
|
||||||
for (var k in obj) {
|
for (var k in obj) {
|
||||||
if (k !== 'id' && !obj.constructor.dataSource.definitions[obj.constructor.modelName].properties[k]) {
|
if (k !== 'id' && !obj.constructor.dataSource.definitions[obj.constructor.modelName].properties[k]) {
|
||||||
|
@ -578,20 +578,20 @@ var INSPECT_SUPPORTS_OBJECT_RETVAL =
|
||||||
versionParts[1] > 11 ||
|
versionParts[1] > 11 ||
|
||||||
(versionParts[0] === 11 && versionParts[1] >= 14);
|
(versionParts[0] === 11 && versionParts[1] >= 14);
|
||||||
|
|
||||||
ModelBaseClass.prototype.inspect = function (depth) {
|
ModelBaseClass.prototype.inspect = function(depth) {
|
||||||
if (INSPECT_SUPPORTS_OBJECT_RETVAL)
|
if (INSPECT_SUPPORTS_OBJECT_RETVAL)
|
||||||
return this.__data;
|
return this.__data;
|
||||||
|
|
||||||
// Workaround for older versions
|
// Workaround for older versions
|
||||||
// See also https://github.com/joyent/node/commit/66280de133
|
// See also https://github.com/joyent/node/commit/66280de133
|
||||||
return util.inspect(this.__data, {
|
return util.inspect(this.__data, {
|
||||||
showHidden: false,
|
showHidden: false,
|
||||||
depth: depth,
|
depth: depth,
|
||||||
colors: false
|
colors: false,
|
||||||
});
|
});
|
||||||
};
|
};
|
||||||
|
|
||||||
ModelBaseClass.mixin = function (anotherClass, options) {
|
ModelBaseClass.mixin = function(anotherClass, options) {
|
||||||
if (typeof anotherClass === 'string') {
|
if (typeof anotherClass === 'string') {
|
||||||
this.modelBuilder.mixins.applyMixin(this, anotherClass, options);
|
this.modelBuilder.mixins.applyMixin(this, anotherClass, options);
|
||||||
} else {
|
} else {
|
||||||
|
@ -608,15 +608,15 @@ ModelBaseClass.mixin = function (anotherClass, options) {
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
ModelBaseClass.prototype.getDataSource = function () {
|
ModelBaseClass.prototype.getDataSource = function() {
|
||||||
return this.__dataSource || this.constructor.dataSource;
|
return this.__dataSource || this.constructor.dataSource;
|
||||||
};
|
};
|
||||||
|
|
||||||
ModelBaseClass.getDataSource = function () {
|
ModelBaseClass.getDataSource = function() {
|
||||||
return this.dataSource;
|
return this.dataSource;
|
||||||
};
|
};
|
||||||
|
|
||||||
ModelBaseClass.prototype.setStrict = function (strict) {
|
ModelBaseClass.prototype.setStrict = function(strict) {
|
||||||
this.__strict = strict;
|
this.__strict = strict;
|
||||||
};
|
};
|
||||||
|
|
||||||
|
|
|
@ -108,7 +108,7 @@ ObserverMixin.notifyObserversOf = function(operation, context, callback) {
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
function(err) { callback(err, context) }
|
function(err) { callback(err, context); }
|
||||||
);
|
);
|
||||||
});
|
});
|
||||||
return callback.promise;
|
return callback.promise;
|
||||||
|
|
File diff suppressed because it is too large
Load Diff
|
@ -21,12 +21,12 @@ function RelationMixin() {
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Define a "one to many" relationship by specifying the model name
|
* Define a "one to many" relationship by specifying the model name
|
||||||
*
|
*
|
||||||
* Examples:
|
* Examples:
|
||||||
* ```
|
* ```
|
||||||
* User.hasMany(Post, {as: 'posts', foreignKey: 'authorId'});
|
* User.hasMany(Post, {as: 'posts', foreignKey: 'authorId'});
|
||||||
* ```
|
* ```
|
||||||
*
|
*
|
||||||
* ```
|
* ```
|
||||||
* Book.hasMany(Chapter);
|
* Book.hasMany(Chapter);
|
||||||
* ```
|
* ```
|
||||||
|
@ -39,24 +39,24 @@ function RelationMixin() {
|
||||||
*
|
*
|
||||||
* ```js
|
* ```js
|
||||||
* Book.create(function(err, book) {
|
* Book.create(function(err, book) {
|
||||||
*
|
*
|
||||||
* // Create a chapter instance ready to be saved in the data source.
|
* // Create a chapter instance ready to be saved in the data source.
|
||||||
* var chapter = book.chapters.build({name: 'Chapter 1'});
|
* var chapter = book.chapters.build({name: 'Chapter 1'});
|
||||||
*
|
*
|
||||||
* // Save the new chapter
|
* // Save the new chapter
|
||||||
* chapter.save();
|
* chapter.save();
|
||||||
*
|
*
|
||||||
* // you can also call the Chapter.create method with the `chapters` property which will build a chapter
|
* // you can also call the Chapter.create method with the `chapters` property which will build a chapter
|
||||||
* // instance and save the it in the data source.
|
* // instance and save the it in the data source.
|
||||||
* book.chapters.create({name: 'Chapter 2'}, function(err, savedChapter) {
|
* book.chapters.create({name: 'Chapter 2'}, function(err, savedChapter) {
|
||||||
* // this callback is optional
|
* // this callback is optional
|
||||||
* });
|
* });
|
||||||
*
|
*
|
||||||
* // Query chapters for the book
|
* // Query chapters for the book
|
||||||
* book.chapters(function(err, chapters) { // all chapters with bookId = book.id
|
* book.chapters(function(err, chapters) { // all chapters with bookId = book.id
|
||||||
* console.log(chapters);
|
* console.log(chapters);
|
||||||
* });
|
* });
|
||||||
*
|
*
|
||||||
* book.chapters({where: {name: 'test'}, function(err, chapters) {
|
* book.chapters({where: {name: 'test'}, function(err, chapters) {
|
||||||
* // All chapters with bookId = book.id and name = 'test'
|
* // All chapters with bookId = book.id and name = 'test'
|
||||||
* console.log(chapters);
|
* console.log(chapters);
|
||||||
|
@ -94,10 +94,10 @@ RelationMixin.hasMany = function hasMany(modelTo, params) {
|
||||||
* ```
|
* ```
|
||||||
* Set the author to be the given user:
|
* Set the author to be the given user:
|
||||||
* ```
|
* ```
|
||||||
* post.author(user)
|
* post.author(user)
|
||||||
* ```
|
* ```
|
||||||
* Examples:
|
* Examples:
|
||||||
*
|
*
|
||||||
* Suppose the model Post has a *belongsTo* relationship with User (the author of the post). You could declare it this way:
|
* Suppose the model Post has a *belongsTo* relationship with User (the author of the post). You could declare it this way:
|
||||||
* ```js
|
* ```js
|
||||||
* Post.belongsTo(User, {as: 'author', foreignKey: 'userId'});
|
* Post.belongsTo(User, {as: 'author', foreignKey: 'userId'});
|
||||||
|
@ -123,9 +123,9 @@ RelationMixin.hasMany = function hasMany(modelTo, params) {
|
||||||
* @options {Object} params Configuration parameters; see below.
|
* @options {Object} params Configuration parameters; see below.
|
||||||
* @property {String} as Name of the property in the referring model that corresponds to the foreign key field in the related model.
|
* @property {String} as Name of the property in the referring model that corresponds to the foreign key field in the related model.
|
||||||
* @property {String} foreignKey Name of foreign key property.
|
* @property {String} foreignKey Name of foreign key property.
|
||||||
*
|
*
|
||||||
*/
|
*/
|
||||||
RelationMixin.belongsTo = function (modelTo, params) {
|
RelationMixin.belongsTo = function(modelTo, params) {
|
||||||
return RelationDefinition.belongsTo(this, modelTo, params);
|
return RelationDefinition.belongsTo(this, modelTo, params);
|
||||||
};
|
};
|
||||||
|
|
||||||
|
@ -150,9 +150,9 @@ RelationMixin.belongsTo = function (modelTo, params) {
|
||||||
* ```
|
* ```
|
||||||
* Remove the user from the group:
|
* Remove the user from the group:
|
||||||
* ```
|
* ```
|
||||||
* user.groups.remove(group, callback);
|
* user.groups.remove(group, callback);
|
||||||
* ```
|
* ```
|
||||||
*
|
*
|
||||||
* @param {String|Object} modelTo Model object (or String name of model) to which you are creating the relationship.
|
* @param {String|Object} modelTo Model object (or String name of model) to which you are creating the relationship.
|
||||||
* the relation
|
* the relation
|
||||||
* @options {Object} params Configuration parameters; see below.
|
* @options {Object} params Configuration parameters; see below.
|
||||||
|
|
64
lib/scope.js
64
lib/scope.js
|
@ -83,9 +83,9 @@ ScopeDefinition.prototype.related = function(receiver, scopeParams, condOrRefres
|
||||||
if (!self.__cachedRelations || self.__cachedRelations[name] === undefined
|
if (!self.__cachedRelations || self.__cachedRelations[name] === undefined
|
||||||
|| actualRefresh) {
|
|| actualRefresh) {
|
||||||
// It either doesn't hit the cache or refresh is required
|
// It either doesn't hit the cache or refresh is required
|
||||||
var params = mergeQuery(actualCond, scopeParams, {nestedInclude: true});
|
var params = mergeQuery(actualCond, scopeParams, { nestedInclude: true });
|
||||||
var targetModel = this.targetModel(receiver);
|
var targetModel = this.targetModel(receiver);
|
||||||
targetModel.find(params, options, function (err, data) {
|
targetModel.find(params, options, function(err, data) {
|
||||||
if (!err && saveOnCache) {
|
if (!err && saveOnCache) {
|
||||||
defineCachedRelations(self);
|
defineCachedRelations(self);
|
||||||
self.__cachedRelations[name] = data;
|
self.__cachedRelations[name] = data;
|
||||||
|
@ -97,7 +97,7 @@ ScopeDefinition.prototype.related = function(receiver, scopeParams, condOrRefres
|
||||||
cb(null, self.__cachedRelations[name]);
|
cb(null, self.__cachedRelations[name]);
|
||||||
}
|
}
|
||||||
return cb.promise;
|
return cb.promise;
|
||||||
}
|
};
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Define a scope method
|
* Define a scope method
|
||||||
|
@ -106,7 +106,7 @@ ScopeDefinition.prototype.related = function(receiver, scopeParams, condOrRefres
|
||||||
*/
|
*/
|
||||||
ScopeDefinition.prototype.defineMethod = function(name, fn) {
|
ScopeDefinition.prototype.defineMethod = function(name, fn) {
|
||||||
return this.methods[name] = fn;
|
return this.methods[name] = fn;
|
||||||
}
|
};
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Define a scope to the class
|
* Define a scope to the class
|
||||||
|
@ -143,10 +143,10 @@ function defineScope(cls, targetClass, name, params, methods, options) {
|
||||||
name: name,
|
name: name,
|
||||||
params: params,
|
params: params,
|
||||||
methods: methods,
|
methods: methods,
|
||||||
options: options
|
options: options,
|
||||||
});
|
});
|
||||||
|
|
||||||
if(isStatic) {
|
if (isStatic) {
|
||||||
cls.scopes = cls.scopes || {};
|
cls.scopes = cls.scopes || {};
|
||||||
cls.scopes[name] = definition;
|
cls.scopes[name] = definition;
|
||||||
} else {
|
} else {
|
||||||
|
@ -169,7 +169,7 @@ function defineScope(cls, targetClass, name, params, methods, options) {
|
||||||
* user.accounts.create(act, cb).
|
* user.accounts.create(act, cb).
|
||||||
*
|
*
|
||||||
*/
|
*/
|
||||||
get: function () {
|
get: function() {
|
||||||
var targetModel = definition.targetModel(this);
|
var targetModel = definition.targetModel(this);
|
||||||
var self = this;
|
var self = this;
|
||||||
|
|
||||||
|
@ -192,23 +192,23 @@ function defineScope(cls, targetClass, name, params, methods, options) {
|
||||||
cb = options;
|
cb = options;
|
||||||
options = {};
|
options = {};
|
||||||
}
|
}
|
||||||
options = options || {}
|
options = options || {};
|
||||||
// Check if there is a through model
|
// Check if there is a through model
|
||||||
// see https://github.com/strongloop/loopback/issues/1076
|
// see https://github.com/strongloop/loopback/issues/1076
|
||||||
if (f._scope.collect &&
|
if (f._scope.collect &&
|
||||||
condOrRefresh !== null && typeof condOrRefresh === 'object') {
|
condOrRefresh !== null && typeof condOrRefresh === 'object') {
|
||||||
//extract the paging filters to the through model
|
//extract the paging filters to the through model
|
||||||
['limit','offset','skip','order'].forEach(function(pagerFilter){
|
['limit', 'offset', 'skip', 'order'].forEach(function(pagerFilter) {
|
||||||
if(typeof(condOrRefresh[pagerFilter]) !== 'undefined'){
|
if (typeof(condOrRefresh[pagerFilter]) !== 'undefined') {
|
||||||
f._scope[pagerFilter] = condOrRefresh[pagerFilter];
|
f._scope[pagerFilter] = condOrRefresh[pagerFilter];
|
||||||
delete condOrRefresh[pagerFilter];
|
delete condOrRefresh[pagerFilter];
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
// Adjust the include so that the condition will be applied to
|
// Adjust the include so that the condition will be applied to
|
||||||
// the target model
|
// the target model
|
||||||
f._scope.include = {
|
f._scope.include = {
|
||||||
relation: f._scope.collect,
|
relation: f._scope.collect,
|
||||||
scope: condOrRefresh
|
scope: condOrRefresh,
|
||||||
};
|
};
|
||||||
condOrRefresh = {};
|
condOrRefresh = {};
|
||||||
}
|
}
|
||||||
|
@ -237,9 +237,9 @@ function defineScope(cls, targetClass, name, params, methods, options) {
|
||||||
cb = options;
|
cb = options;
|
||||||
options = {};
|
options = {};
|
||||||
}
|
}
|
||||||
options = options || {}
|
options = options || {};
|
||||||
return definition.related(self, f._scope, condOrRefresh, options, cb);
|
return definition.related(self, f._scope, condOrRefresh, options, cb);
|
||||||
}
|
};
|
||||||
|
|
||||||
f.build = build;
|
f.build = build;
|
||||||
f.create = create;
|
f.create = create;
|
||||||
|
@ -259,21 +259,21 @@ function defineScope(cls, targetClass, name, params, methods, options) {
|
||||||
// Station.scope('active', {where: {isActive: true}});
|
// Station.scope('active', {where: {isActive: true}});
|
||||||
// Station.scope('subway', {where: {isUndeground: true}});
|
// Station.scope('subway', {where: {isUndeground: true}});
|
||||||
// Station.active.subway(cb);
|
// Station.active.subway(cb);
|
||||||
Object.keys(targetClass._scopeMeta).forEach(function (name) {
|
Object.keys(targetClass._scopeMeta).forEach(function(name) {
|
||||||
Object.defineProperty(f, name, {
|
Object.defineProperty(f, name, {
|
||||||
enumerable: false,
|
enumerable: false,
|
||||||
get: function () {
|
get: function() {
|
||||||
mergeQuery(f._scope, targetModel._scopeMeta[name]);
|
mergeQuery(f._scope, targetModel._scopeMeta[name]);
|
||||||
return f;
|
return f;
|
||||||
}
|
},
|
||||||
});
|
});
|
||||||
}.bind(self));
|
}.bind(self));
|
||||||
return f;
|
return f;
|
||||||
}
|
},
|
||||||
});
|
});
|
||||||
|
|
||||||
// Wrap the property into a function for remoting
|
// Wrap the property into a function for remoting
|
||||||
var fn = function () {
|
var fn = function() {
|
||||||
// primaryObject.scopeName, such as user.accounts
|
// primaryObject.scopeName, such as user.accounts
|
||||||
var f = this[name];
|
var f = this[name];
|
||||||
// set receiver to be the scope property whose value is a function
|
// set receiver to be the scope property whose value is a function
|
||||||
|
@ -282,42 +282,42 @@ function defineScope(cls, targetClass, name, params, methods, options) {
|
||||||
|
|
||||||
cls['__get__' + name] = fn;
|
cls['__get__' + name] = fn;
|
||||||
|
|
||||||
var fn_create = function () {
|
var fn_create = function() {
|
||||||
var f = this[name].create;
|
var f = this[name].create;
|
||||||
f.apply(this[name], arguments);
|
f.apply(this[name], arguments);
|
||||||
};
|
};
|
||||||
|
|
||||||
cls['__create__' + name] = fn_create;
|
cls['__create__' + name] = fn_create;
|
||||||
|
|
||||||
var fn_delete = function () {
|
var fn_delete = function() {
|
||||||
var f = this[name].destroyAll;
|
var f = this[name].destroyAll;
|
||||||
f.apply(this[name], arguments);
|
f.apply(this[name], arguments);
|
||||||
};
|
};
|
||||||
|
|
||||||
cls['__delete__' + name] = fn_delete;
|
cls['__delete__' + name] = fn_delete;
|
||||||
|
|
||||||
var fn_update = function () {
|
var fn_update = function() {
|
||||||
var f = this[name].updateAll;
|
var f = this[name].updateAll;
|
||||||
f.apply(this[name], arguments);
|
f.apply(this[name], arguments);
|
||||||
};
|
};
|
||||||
|
|
||||||
cls['__update__' + name] = fn_update;
|
cls['__update__' + name] = fn_update;
|
||||||
|
|
||||||
var fn_findById = function (cb) {
|
var fn_findById = function(cb) {
|
||||||
var f = this[name].findById;
|
var f = this[name].findById;
|
||||||
f.apply(this[name], arguments);
|
f.apply(this[name], arguments);
|
||||||
};
|
};
|
||||||
|
|
||||||
cls['__findById__' + name] = fn_findById;
|
cls['__findById__' + name] = fn_findById;
|
||||||
|
|
||||||
var fn_findOne = function (cb) {
|
var fn_findOne = function(cb) {
|
||||||
var f = this[name].findOne;
|
var f = this[name].findOne;
|
||||||
f.apply(this[name], arguments);
|
f.apply(this[name], arguments);
|
||||||
};
|
};
|
||||||
|
|
||||||
cls['__findOne__' + name] = fn_findOne;
|
cls['__findOne__' + name] = fn_findOne;
|
||||||
|
|
||||||
var fn_count = function (cb) {
|
var fn_count = function(cb) {
|
||||||
var f = this[name].count;
|
var f = this[name].count;
|
||||||
f.apply(this[name], arguments);
|
f.apply(this[name], arguments);
|
||||||
};
|
};
|
||||||
|
@ -369,7 +369,7 @@ function defineScope(cls, targetClass, name, params, methods, options) {
|
||||||
|
|
||||||
var targetModel = definition.targetModel(this._receiver);
|
var targetModel = definition.targetModel(this._receiver);
|
||||||
var scoped = (this._scope && this._scope.where) || {};
|
var scoped = (this._scope && this._scope.where) || {};
|
||||||
var filter = mergeQuery({ where: scoped }, { where: where || {} });
|
var filter = mergeQuery({ where: scoped }, { where: where || {}});
|
||||||
return targetModel.destroyAll(filter.where, options, cb);
|
return targetModel.destroyAll(filter.where, options, cb);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -389,7 +389,7 @@ function defineScope(cls, targetClass, name, params, methods, options) {
|
||||||
options = options || {};
|
options = options || {};
|
||||||
var targetModel = definition.targetModel(this._receiver);
|
var targetModel = definition.targetModel(this._receiver);
|
||||||
var scoped = (this._scope && this._scope.where) || {};
|
var scoped = (this._scope && this._scope.where) || {};
|
||||||
var filter = mergeQuery({ where: scoped }, { where: where || {} });
|
var filter = mergeQuery({ where: scoped }, { where: where || {}});
|
||||||
return targetModel.updateAll(filter.where, data, options, cb);
|
return targetModel.updateAll(filter.where, data, options, cb);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -412,12 +412,12 @@ function defineScope(cls, targetClass, name, params, methods, options) {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
options = options || {};
|
options = options || {};
|
||||||
filter = filter || {};
|
filter = filter || {};
|
||||||
var targetModel = definition.targetModel(this._receiver);
|
var targetModel = definition.targetModel(this._receiver);
|
||||||
var idName = targetModel.definition.idName();
|
var idName = targetModel.definition.idName();
|
||||||
var query = {where: {}};
|
var query = { where: {}};
|
||||||
query.where[idName] = id;
|
query.where[idName] = id;
|
||||||
query = mergeQuery(query, filter);
|
query = mergeQuery(query, filter);
|
||||||
return this.findOne(query, options, cb);
|
return this.findOne(query, options, cb);
|
||||||
|
@ -455,7 +455,7 @@ function defineScope(cls, targetClass, name, params, methods, options) {
|
||||||
|
|
||||||
var targetModel = definition.targetModel(this._receiver);
|
var targetModel = definition.targetModel(this._receiver);
|
||||||
var scoped = (this._scope && this._scope.where) || {};
|
var scoped = (this._scope && this._scope.where) || {};
|
||||||
var filter = mergeQuery({ where: scoped }, { where: where || {} });
|
var filter = mergeQuery({ where: scoped }, { where: where || {}});
|
||||||
return targetModel.count(filter.where, options, cb);
|
return targetModel.count(filter.where, options, cb);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
|
@ -78,7 +78,7 @@ TransactionMixin.beginTransaction = function(options, cb) {
|
||||||
setTimeout(function() {
|
setTimeout(function() {
|
||||||
var context = {
|
var context = {
|
||||||
transaction: transaction,
|
transaction: transaction,
|
||||||
operation: 'timeout'
|
operation: 'timeout',
|
||||||
};
|
};
|
||||||
transaction.notifyObserversOf('timeout', context, function(err) {
|
transaction.notifyObserversOf('timeout', context, function(err) {
|
||||||
if (!err) {
|
if (!err) {
|
||||||
|
@ -121,7 +121,7 @@ if (Transaction) {
|
||||||
}
|
}
|
||||||
var context = {
|
var context = {
|
||||||
transaction: self,
|
transaction: self,
|
||||||
operation: 'commit'
|
operation: 'commit',
|
||||||
};
|
};
|
||||||
|
|
||||||
function work(done) {
|
function work(done) {
|
||||||
|
@ -155,7 +155,7 @@ if (Transaction) {
|
||||||
}
|
}
|
||||||
var context = {
|
var context = {
|
||||||
transaction: self,
|
transaction: self,
|
||||||
operation: 'rollback'
|
operation: 'rollback',
|
||||||
};
|
};
|
||||||
|
|
||||||
function work(done) {
|
function work(done) {
|
||||||
|
|
14
lib/types.js
14
lib/types.js
|
@ -14,7 +14,7 @@ Types.Text = function Text(value) {
|
||||||
this.value = value;
|
this.value = value;
|
||||||
}; // Text type
|
}; // Text type
|
||||||
|
|
||||||
Types.Text.prototype.toObject = Types.Text.prototype.toJSON = function () {
|
Types.Text.prototype.toObject = Types.Text.prototype.toJSON = function() {
|
||||||
return this.value;
|
return this.value;
|
||||||
};
|
};
|
||||||
|
|
||||||
|
@ -24,7 +24,7 @@ Types.JSON = function JSON(value) {
|
||||||
}
|
}
|
||||||
this.value = value;
|
this.value = value;
|
||||||
}; // JSON Object
|
}; // JSON Object
|
||||||
Types.JSON.prototype.toObject = Types.JSON.prototype.toJSON = function () {
|
Types.JSON.prototype.toObject = Types.JSON.prototype.toJSON = function() {
|
||||||
return this.value;
|
return this.value;
|
||||||
};
|
};
|
||||||
|
|
||||||
|
@ -34,20 +34,20 @@ Types.Any = function Any(value) {
|
||||||
}
|
}
|
||||||
this.value = value;
|
this.value = value;
|
||||||
}; // Any Type
|
}; // Any Type
|
||||||
Types.Any.prototype.toObject = Types.Any.prototype.toJSON = function () {
|
Types.Any.prototype.toObject = Types.Any.prototype.toJSON = function() {
|
||||||
return this.value;
|
return this.value;
|
||||||
};
|
};
|
||||||
|
|
||||||
module.exports = function (modelTypes) {
|
module.exports = function(modelTypes) {
|
||||||
|
|
||||||
var GeoPoint = require('./geo').GeoPoint;
|
var GeoPoint = require('./geo').GeoPoint;
|
||||||
|
|
||||||
for(var t in Types) {
|
for (var t in Types) {
|
||||||
modelTypes[t] = Types[t];
|
modelTypes[t] = Types[t];
|
||||||
}
|
}
|
||||||
|
|
||||||
modelTypes.schemaTypes = {};
|
modelTypes.schemaTypes = {};
|
||||||
modelTypes.registerType = function (type, names) {
|
modelTypes.registerType = function(type, names) {
|
||||||
names = names || [];
|
names = names || [];
|
||||||
names = names.concat([type.name]);
|
names = names.concat([type.name]);
|
||||||
for (var n = 0; n < names.length; n++) {
|
for (var n = 0; n < names.length; n++) {
|
||||||
|
@ -69,4 +69,4 @@ module.exports = function (modelTypes) {
|
||||||
modelTypes.registerType(Object);
|
modelTypes.registerType(Object);
|
||||||
};
|
};
|
||||||
|
|
||||||
module.exports.Types = Types;
|
module.exports.Types = Types;
|
||||||
|
|
24
lib/utils.js
24
lib/utils.js
|
@ -135,9 +135,9 @@ function convertToArray(include) {
|
||||||
if (typeof includeEntry === 'string') {
|
if (typeof includeEntry === 'string') {
|
||||||
var obj = {};
|
var obj = {};
|
||||||
obj[includeEntry] = true;
|
obj[includeEntry] = true;
|
||||||
normalized.push(obj)
|
normalized.push(obj);
|
||||||
}
|
}
|
||||||
else{
|
else {
|
||||||
normalized.push(includeEntry);
|
normalized.push(includeEntry);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -163,7 +163,7 @@ function mergeQuery(base, update, spec) {
|
||||||
|
|
||||||
if (update.where && Object.keys(update.where).length > 0) {
|
if (update.where && Object.keys(update.where).length > 0) {
|
||||||
if (base.where && Object.keys(base.where).length > 0) {
|
if (base.where && Object.keys(base.where).length > 0) {
|
||||||
base.where = {and: [base.where, update.where]};
|
base.where = { and: [base.where, update.where] };
|
||||||
} else {
|
} else {
|
||||||
base.where = update.where;
|
base.where = update.where;
|
||||||
}
|
}
|
||||||
|
@ -174,7 +174,7 @@ function mergeQuery(base, update, spec) {
|
||||||
if (!base.include) {
|
if (!base.include) {
|
||||||
base.include = update.include;
|
base.include = update.include;
|
||||||
} else {
|
} else {
|
||||||
if (spec.nestedInclude === true){
|
if (spec.nestedInclude === true) {
|
||||||
//specify nestedInclude=true to force nesting of inclusions on scoped
|
//specify nestedInclude=true to force nesting of inclusions on scoped
|
||||||
//queries. e.g. In physician.patients.getAsync({include: 'address'}),
|
//queries. e.g. In physician.patients.getAsync({include: 'address'}),
|
||||||
//inclusion should be on patient model, not on physician model.
|
//inclusion should be on patient model, not on physician model.
|
||||||
|
@ -182,7 +182,7 @@ function mergeQuery(base, update, spec) {
|
||||||
base.include = {};
|
base.include = {};
|
||||||
base.include[update.include] = saved;
|
base.include[update.include] = saved;
|
||||||
}
|
}
|
||||||
else{
|
else {
|
||||||
//default behaviour of inclusion merge - merge inclusions at the same
|
//default behaviour of inclusion merge - merge inclusions at the same
|
||||||
//level. - https://github.com/strongloop/loopback-datasource-juggler/pull/569#issuecomment-95310874
|
//level. - https://github.com/strongloop/loopback-datasource-juggler/pull/569#issuecomment-95310874
|
||||||
base.include = mergeIncludes(base.include, update.include);
|
base.include = mergeIncludes(base.include, update.include);
|
||||||
|
@ -283,7 +283,7 @@ function fieldsToArray(fields, properties, excludeUnknown) {
|
||||||
|
|
||||||
function selectFields(fields) {
|
function selectFields(fields) {
|
||||||
// map function
|
// map function
|
||||||
return function (obj) {
|
return function(obj) {
|
||||||
var result = {};
|
var result = {};
|
||||||
var key;
|
var key;
|
||||||
|
|
||||||
|
@ -308,7 +308,7 @@ function removeUndefined(query, handleUndefined) {
|
||||||
}
|
}
|
||||||
// WARNING: [rfeng] Use map() will cause mongodb to produce invalid BSON
|
// WARNING: [rfeng] Use map() will cause mongodb to produce invalid BSON
|
||||||
// as traverse doesn't transform the ObjectId correctly
|
// as traverse doesn't transform the ObjectId correctly
|
||||||
return traverse(query).forEach(function (x) {
|
return traverse(query).forEach(function(x) {
|
||||||
if (x === undefined) {
|
if (x === undefined) {
|
||||||
switch (handleUndefined) {
|
switch (handleUndefined) {
|
||||||
case 'nullify':
|
case 'nullify':
|
||||||
|
@ -430,7 +430,7 @@ function defineCachedRelations(obj) {
|
||||||
writable: true,
|
writable: true,
|
||||||
enumerable: false,
|
enumerable: false,
|
||||||
configurable: true,
|
configurable: true,
|
||||||
value: {}
|
value: {},
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -449,7 +449,7 @@ function isPlainObject(obj) {
|
||||||
|
|
||||||
function sortObjectsByIds(idName, ids, objects, strict) {
|
function sortObjectsByIds(idName, ids, objects, strict) {
|
||||||
ids = ids.map(function(id) {
|
ids = ids.map(function(id) {
|
||||||
return (typeof id === 'object') ? String(id) : id;
|
return (typeof id === 'object') ? String(id) : id;
|
||||||
});
|
});
|
||||||
|
|
||||||
var indexOf = function(x) {
|
var indexOf = function(x) {
|
||||||
|
@ -485,15 +485,15 @@ function createPromiseCallback() {
|
||||||
var cb;
|
var cb;
|
||||||
|
|
||||||
if (!global.Promise) {
|
if (!global.Promise) {
|
||||||
cb = function(){};
|
cb = function() {};
|
||||||
cb.promise = {};
|
cb.promise = {};
|
||||||
Object.defineProperty(cb.promise, 'then', { get: throwPromiseNotDefined });
|
Object.defineProperty(cb.promise, 'then', { get: throwPromiseNotDefined });
|
||||||
Object.defineProperty(cb.promise, 'catch', { get: throwPromiseNotDefined });
|
Object.defineProperty(cb.promise, 'catch', { get: throwPromiseNotDefined });
|
||||||
return cb;
|
return cb;
|
||||||
}
|
}
|
||||||
|
|
||||||
var promise = new Promise(function (resolve, reject) {
|
var promise = new Promise(function(resolve, reject) {
|
||||||
cb = function (err, data) {
|
cb = function(err, data) {
|
||||||
if (err) return reject(err);
|
if (err) return reject(err);
|
||||||
return resolve(data);
|
return resolve(data);
|
||||||
};
|
};
|
||||||
|
|
|
@ -207,7 +207,7 @@ Validatable.validate = getConfigurator('custom');
|
||||||
* @options {Object} Options See below
|
* @options {Object} Options See below
|
||||||
* @property {String} message Optional error message if property is not valid. Default error message: " is invalid".
|
* @property {String} message Optional error message if property is not valid. Default error message: " is invalid".
|
||||||
*/
|
*/
|
||||||
Validatable.validateAsync = getConfigurator('custom', {async: true});
|
Validatable.validateAsync = getConfigurator('custom', { async: true });
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Validate uniqueness. Ensure the value for property is unique in the collection of models.
|
* Validate uniqueness. Ensure the value for property is unique in the collection of models.
|
||||||
|
@ -231,7 +231,7 @@ Validatable.validateAsync = getConfigurator('custom', {async: true});
|
||||||
* @property {Array.<String>} scopedTo List of properties defining the scope.
|
* @property {Array.<String>} scopedTo List of properties defining the scope.
|
||||||
* @property {String} message Optional error message if property is not valid. Default error message: "is not unique".
|
* @property {String} message Optional error message if property is not valid. Default error message: "is not unique".
|
||||||
*/
|
*/
|
||||||
Validatable.validatesUniquenessOf = getConfigurator('uniqueness', {async: true});
|
Validatable.validatesUniquenessOf = getConfigurator('uniqueness', { async: true });
|
||||||
|
|
||||||
// implementation of validators
|
// implementation of validators
|
||||||
|
|
||||||
|
@ -292,7 +292,7 @@ function validateInclusion(attr, conf, err) {
|
||||||
if (nullCheck.call(this, attr, conf, err)) return;
|
if (nullCheck.call(this, attr, conf, err)) return;
|
||||||
|
|
||||||
if (!~conf.in.indexOf(this[attr])) {
|
if (!~conf.in.indexOf(this[attr])) {
|
||||||
err()
|
err();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -303,7 +303,7 @@ function validateExclusion(attr, conf, err) {
|
||||||
if (nullCheck.call(this, attr, conf, err)) return;
|
if (nullCheck.call(this, attr, conf, err)) return;
|
||||||
|
|
||||||
if (~conf.in.indexOf(this[attr])) {
|
if (~conf.in.indexOf(this[attr])) {
|
||||||
err()
|
err();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -336,7 +336,7 @@ function validateUniqueness(attr, conf, err, done) {
|
||||||
if (blank(this[attr])) {
|
if (blank(this[attr])) {
|
||||||
return process.nextTick(done);
|
return process.nextTick(done);
|
||||||
}
|
}
|
||||||
var cond = {where: {}};
|
var cond = { where: {}};
|
||||||
cond.where[attr] = this[attr];
|
cond.where[attr] = this[attr];
|
||||||
|
|
||||||
if (conf && conf.scopedTo) {
|
if (conf && conf.scopedTo) {
|
||||||
|
@ -349,7 +349,7 @@ function validateUniqueness(attr, conf, err, done) {
|
||||||
|
|
||||||
var idName = this.constructor.definition.idName();
|
var idName = this.constructor.definition.idName();
|
||||||
var isNewRecord = this.isNewRecord();
|
var isNewRecord = this.isNewRecord();
|
||||||
this.constructor.find(cond, function (error, found) {
|
this.constructor.find(cond, function(error, found) {
|
||||||
if (error) {
|
if (error) {
|
||||||
err(error);
|
err(error);
|
||||||
} else if (found.length > 1) {
|
} else if (found.length > 1) {
|
||||||
|
@ -372,11 +372,11 @@ var validators = {
|
||||||
exclusion: validateExclusion,
|
exclusion: validateExclusion,
|
||||||
format: validateFormat,
|
format: validateFormat,
|
||||||
custom: validateCustom,
|
custom: validateCustom,
|
||||||
uniqueness: validateUniqueness
|
uniqueness: validateUniqueness,
|
||||||
};
|
};
|
||||||
|
|
||||||
function getConfigurator(name, opts) {
|
function getConfigurator(name, opts) {
|
||||||
return function () {
|
return function() {
|
||||||
var args = Array.prototype.slice.call(arguments);
|
var args = Array.prototype.slice.call(arguments);
|
||||||
args[1] = args[1] || {};
|
args[1] = args[1] || {};
|
||||||
configure(this, name, args, opts);
|
configure(this, name, args, opts);
|
||||||
|
@ -415,7 +415,7 @@ function getConfigurator(name, opts) {
|
||||||
* @param {Function} callback called with (valid)
|
* @param {Function} callback called with (valid)
|
||||||
* @returns {Boolean} True if no asynchronous validation is configured and all properties pass validation.
|
* @returns {Boolean} True if no asynchronous validation is configured and all properties pass validation.
|
||||||
*/
|
*/
|
||||||
Validatable.prototype.isValid = function (callback, data) {
|
Validatable.prototype.isValid = function(callback, data) {
|
||||||
var valid = true, inst = this, wait = 0, async = false;
|
var valid = true, inst = this, wait = 0, async = false;
|
||||||
var validations = this.constructor.validations;
|
var validations = this.constructor.validations;
|
||||||
|
|
||||||
|
@ -426,8 +426,8 @@ Validatable.prototype.isValid = function (callback, data) {
|
||||||
if (typeof validations !== 'object' && !reportDiscardedProperties) {
|
if (typeof validations !== 'object' && !reportDiscardedProperties) {
|
||||||
cleanErrors(this);
|
cleanErrors(this);
|
||||||
if (callback) {
|
if (callback) {
|
||||||
this.trigger('validate', function (validationsDone) {
|
this.trigger('validate', function(validationsDone) {
|
||||||
validationsDone.call(inst, function () {
|
validationsDone.call(inst, function() {
|
||||||
callback(valid);
|
callback(valid);
|
||||||
});
|
});
|
||||||
}, data, callback);
|
}, data, callback);
|
||||||
|
@ -438,10 +438,10 @@ Validatable.prototype.isValid = function (callback, data) {
|
||||||
Object.defineProperty(this, 'errors', {
|
Object.defineProperty(this, 'errors', {
|
||||||
enumerable: false,
|
enumerable: false,
|
||||||
configurable: true,
|
configurable: true,
|
||||||
value: new Errors
|
value: new Errors,
|
||||||
});
|
});
|
||||||
|
|
||||||
this.trigger('validate', function (validationsDone) {
|
this.trigger('validate', function(validationsDone) {
|
||||||
var inst = this,
|
var inst = this,
|
||||||
asyncFail = false;
|
asyncFail = false;
|
||||||
|
|
||||||
|
@ -453,7 +453,7 @@ Validatable.prototype.isValid = function (callback, data) {
|
||||||
if (v.options && v.options.async) {
|
if (v.options && v.options.async) {
|
||||||
async = true;
|
async = true;
|
||||||
wait += 1;
|
wait += 1;
|
||||||
process.nextTick(function () {
|
process.nextTick(function() {
|
||||||
validationFailed(inst, attr, v, done);
|
validationFailed(inst, attr, v, done);
|
||||||
});
|
});
|
||||||
} else {
|
} else {
|
||||||
|
@ -475,7 +475,7 @@ Validatable.prototype.isValid = function (callback, data) {
|
||||||
}
|
}
|
||||||
|
|
||||||
if (!async) {
|
if (!async) {
|
||||||
validationsDone.call(inst, function () {
|
validationsDone.call(inst, function() {
|
||||||
if (valid) cleanErrors(inst);
|
if (valid) cleanErrors(inst);
|
||||||
if (callback) {
|
if (callback) {
|
||||||
callback(valid);
|
callback(valid);
|
||||||
|
@ -486,7 +486,7 @@ Validatable.prototype.isValid = function (callback, data) {
|
||||||
function done(fail) {
|
function done(fail) {
|
||||||
asyncFail = asyncFail || fail;
|
asyncFail = asyncFail || fail;
|
||||||
if (--wait === 0) {
|
if (--wait === 0) {
|
||||||
validationsDone.call(inst, function () {
|
validationsDone.call(inst, function() {
|
||||||
if (valid && !asyncFail) cleanErrors(inst);
|
if (valid && !asyncFail) cleanErrors(inst);
|
||||||
if (callback) {
|
if (callback) {
|
||||||
callback(valid && !asyncFail);
|
callback(valid && !asyncFail);
|
||||||
|
@ -511,7 +511,7 @@ function cleanErrors(inst) {
|
||||||
Object.defineProperty(inst, 'errors', {
|
Object.defineProperty(inst, 'errors', {
|
||||||
enumerable: false,
|
enumerable: false,
|
||||||
configurable: true,
|
configurable: true,
|
||||||
value: false
|
value: false,
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -559,7 +559,7 @@ function validationFailed(inst, attr, conf, cb) {
|
||||||
fail = true;
|
fail = true;
|
||||||
});
|
});
|
||||||
if (cb) {
|
if (cb) {
|
||||||
validatorArguments.push(function () {
|
validatorArguments.push(function() {
|
||||||
cb(fail);
|
cb(fail);
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
@ -593,19 +593,19 @@ var defaultMessages = {
|
||||||
length: {
|
length: {
|
||||||
min: 'too short',
|
min: 'too short',
|
||||||
max: 'too long',
|
max: 'too long',
|
||||||
is: 'length is wrong'
|
is: 'length is wrong',
|
||||||
},
|
},
|
||||||
common: {
|
common: {
|
||||||
blank: 'is blank',
|
blank: 'is blank',
|
||||||
'null': 'is null'
|
'null': 'is null',
|
||||||
},
|
},
|
||||||
numericality: {
|
numericality: {
|
||||||
'int': 'is not an integer',
|
'int': 'is not an integer',
|
||||||
'number': 'is not a number'
|
'number': 'is not a number',
|
||||||
},
|
},
|
||||||
inclusion: 'is not included in the list',
|
inclusion: 'is not included in the list',
|
||||||
exclusion: 'is reserved',
|
exclusion: 'is reserved',
|
||||||
uniqueness: 'is not unique'
|
uniqueness: 'is not unique',
|
||||||
};
|
};
|
||||||
|
|
||||||
function nullCheck(attr, conf, err) {
|
function nullCheck(attr, conf, err) {
|
||||||
|
@ -647,7 +647,7 @@ function configure(cls, validation, args, opts) {
|
||||||
writable: true,
|
writable: true,
|
||||||
configurable: true,
|
configurable: true,
|
||||||
enumerable: false,
|
enumerable: false,
|
||||||
value: {}
|
value: {},
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
args = [].slice.call(args);
|
args = [].slice.call(args);
|
||||||
|
@ -661,7 +661,7 @@ function configure(cls, validation, args, opts) {
|
||||||
conf.customValidator = args.pop();
|
conf.customValidator = args.pop();
|
||||||
}
|
}
|
||||||
conf.validation = validation;
|
conf.validation = validation;
|
||||||
args.forEach(function (attr) {
|
args.forEach(function(attr) {
|
||||||
if (typeof attr === 'string') {
|
if (typeof attr === 'string') {
|
||||||
var validation = extend({}, conf);
|
var validation = extend({}, conf);
|
||||||
validation.options = opts || {};
|
validation.options = opts || {};
|
||||||
|
@ -675,11 +675,11 @@ function Errors() {
|
||||||
Object.defineProperty(this, 'codes', {
|
Object.defineProperty(this, 'codes', {
|
||||||
enumerable: false,
|
enumerable: false,
|
||||||
configurable: true,
|
configurable: true,
|
||||||
value: {}
|
value: {},
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
Errors.prototype.add = function (field, message, code) {
|
Errors.prototype.add = function(field, message, code) {
|
||||||
code = code || 'invalid';
|
code = code || 'invalid';
|
||||||
if (!this[field]) {
|
if (!this[field]) {
|
||||||
this[field] = [];
|
this[field] = [];
|
||||||
|
@ -691,7 +691,7 @@ Errors.prototype.add = function (field, message, code) {
|
||||||
|
|
||||||
function ErrorCodes(messages) {
|
function ErrorCodes(messages) {
|
||||||
var c = this;
|
var c = this;
|
||||||
Object.keys(messages).forEach(function (field) {
|
Object.keys(messages).forEach(function(field) {
|
||||||
c[field] = messages[field].codes;
|
c[field] = messages[field].codes;
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
@ -763,7 +763,7 @@ function ValidationError(obj) {
|
||||||
this.details = {
|
this.details = {
|
||||||
context: context,
|
context: context,
|
||||||
codes: obj.errors && obj.errors.codes,
|
codes: obj.errors && obj.errors.codes,
|
||||||
messages: obj.errors
|
messages: obj.errors,
|
||||||
};
|
};
|
||||||
|
|
||||||
if (Error.captureStackTrace) {
|
if (Error.captureStackTrace) {
|
||||||
|
@ -813,7 +813,7 @@ function formatPropertyError(propertyName, propertyValue, errorMessage) {
|
||||||
showHidden: false,
|
showHidden: false,
|
||||||
color: false,
|
color: false,
|
||||||
// show top-level object properties only
|
// show top-level object properties only
|
||||||
depth: Array.isArray(propertyValue) ? 1 : 0
|
depth: Array.isArray(propertyValue) ? 1 : 0,
|
||||||
});
|
});
|
||||||
formattedValue = truncatePropertyString(formattedValue);
|
formattedValue = truncatePropertyString(formattedValue);
|
||||||
} else {
|
} else {
|
||||||
|
@ -839,5 +839,5 @@ function truncatePropertyString(value) {
|
||||||
len -= 3;
|
len -= 3;
|
||||||
}
|
}
|
||||||
|
|
||||||
return value.slice(0, len-4) + '...' + tail;
|
return value.slice(0, len - 4) + '...' + tail;
|
||||||
}
|
}
|
||||||
|
|
|
@ -17,12 +17,12 @@ var Memory = require('../lib/connectors/memory').Memory;
|
||||||
var HOOK_NAMES = [
|
var HOOK_NAMES = [
|
||||||
'access',
|
'access',
|
||||||
'before save', 'persist', 'after save',
|
'before save', 'persist', 'after save',
|
||||||
'before delete', 'after delete'
|
'before delete', 'after delete',
|
||||||
];
|
];
|
||||||
|
|
||||||
var dataSources = [
|
var dataSources = [
|
||||||
createOptimizedDataSource(),
|
createOptimizedDataSource(),
|
||||||
createUnoptimizedDataSource()
|
createUnoptimizedDataSource(),
|
||||||
];
|
];
|
||||||
|
|
||||||
var observedContexts = [];
|
var observedContexts = [];
|
||||||
|
@ -34,7 +34,7 @@ Promise.onPossiblyUnhandledRejection(function(err) {
|
||||||
|
|
||||||
var operations = [
|
var operations = [
|
||||||
function find(ds) {
|
function find(ds) {
|
||||||
return ds.TestModel.find({ where: { id: '1' } });
|
return ds.TestModel.find({ where: { id: '1' }});
|
||||||
},
|
},
|
||||||
|
|
||||||
function count(ds) {
|
function count(ds) {
|
||||||
|
@ -47,13 +47,13 @@ var operations = [
|
||||||
|
|
||||||
function findOrCreate_found(ds) {
|
function findOrCreate_found(ds) {
|
||||||
return ds.TestModel.findOrCreate(
|
return ds.TestModel.findOrCreate(
|
||||||
{ where: { name: ds.existingInstance.name } },
|
{ where: { name: ds.existingInstance.name }},
|
||||||
{ name: ds.existingInstance.name });
|
{ name: ds.existingInstance.name });
|
||||||
},
|
},
|
||||||
|
|
||||||
function findOrCreate_create(ds) {
|
function findOrCreate_create(ds) {
|
||||||
return ds.TestModel.findOrCreate(
|
return ds.TestModel.findOrCreate(
|
||||||
{ where: { name: 'new-record' } },
|
{ where: { name: 'new-record' }},
|
||||||
{ name: 'new-record' });
|
{ name: 'new-record' });
|
||||||
},
|
},
|
||||||
|
|
||||||
|
@ -134,7 +134,7 @@ function setupTestModels() {
|
||||||
var TestModel = ds.TestModel = ds.createModel('TestModel', {
|
var TestModel = ds.TestModel = ds.createModel('TestModel', {
|
||||||
id: { type: String, id: true, default: uid },
|
id: { type: String, id: true, default: uid },
|
||||||
name: { type: String, required: true },
|
name: { type: String, required: true },
|
||||||
extra: { type: String, required: false }
|
extra: { type: String, required: false },
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
return Promise.resolve();
|
return Promise.resolve();
|
||||||
|
@ -155,7 +155,7 @@ function runner(fn) {
|
||||||
observedContexts.push({
|
observedContexts.push({
|
||||||
operation: fn.name,
|
operation: fn.name,
|
||||||
connector: ds.name,
|
connector: ds.name,
|
||||||
hooks: {}
|
hooks: {},
|
||||||
});
|
});
|
||||||
return fn(ds);
|
return fn(ds);
|
||||||
});
|
});
|
||||||
|
@ -171,11 +171,11 @@ function resetStorage(ds) {
|
||||||
});
|
});
|
||||||
return TestModel.deleteAll()
|
return TestModel.deleteAll()
|
||||||
.then(function() {
|
.then(function() {
|
||||||
return TestModel.create({ name: 'first' })
|
return TestModel.create({ name: 'first' });
|
||||||
})
|
})
|
||||||
.then(function(instance) {
|
.then(function(instance) {
|
||||||
// Look it up from DB so that default values are retrieved
|
// Look it up from DB so that default values are retrieved
|
||||||
return TestModel.findById(instance.id)
|
return TestModel.findById(instance.id);
|
||||||
})
|
})
|
||||||
.then(function(instance) {
|
.then(function(instance) {
|
||||||
ds.existingInstance = instance;
|
ds.existingInstance = instance;
|
||||||
|
@ -184,7 +184,7 @@ function resetStorage(ds) {
|
||||||
.then(function() {
|
.then(function() {
|
||||||
HOOK_NAMES.forEach(function(hook) {
|
HOOK_NAMES.forEach(function(hook) {
|
||||||
TestModel.observe(hook, function(ctx, next) {
|
TestModel.observe(hook, function(ctx, next) {
|
||||||
var row = observedContexts[observedContexts.length-1];
|
var row = observedContexts[observedContexts.length - 1];
|
||||||
row.hooks[hook] = Object.keys(ctx);
|
row.hooks[hook] = Object.keys(ctx);
|
||||||
next();
|
next();
|
||||||
});
|
});
|
||||||
|
@ -193,7 +193,7 @@ function resetStorage(ds) {
|
||||||
}
|
}
|
||||||
|
|
||||||
function report() {
|
function report() {
|
||||||
console.log('<style>')
|
console.log('<style>');
|
||||||
console.log('td { font-family: "monospace": }');
|
console.log('td { font-family: "monospace": }');
|
||||||
console.log('td, th {');
|
console.log('td, th {');
|
||||||
console.log(' vertical-align: text-top;');
|
console.log(' vertical-align: text-top;');
|
||||||
|
@ -204,7 +204,7 @@ function report() {
|
||||||
// merge rows where Optimized and Unoptimized produce the same context
|
// merge rows where Optimized and Unoptimized produce the same context
|
||||||
observedContexts.forEach(function(row, ix) {
|
observedContexts.forEach(function(row, ix) {
|
||||||
if (!ix) return;
|
if (!ix) return;
|
||||||
var last = observedContexts[ix-1];
|
var last = observedContexts[ix - 1];
|
||||||
if (row.operation != last.operation) return;
|
if (row.operation != last.operation) return;
|
||||||
if (JSON.stringify(row.hooks) !== JSON.stringify(last.hooks)) return;
|
if (JSON.stringify(row.hooks) !== JSON.stringify(last.hooks)) return;
|
||||||
last.merge = true;
|
last.merge = true;
|
||||||
|
|
|
@ -9,36 +9,36 @@ var jdb = require('../');
|
||||||
var DataSource = jdb.DataSource;
|
var DataSource = jdb.DataSource;
|
||||||
|
|
||||||
var ds, Item, Variant;
|
var ds, Item, Variant;
|
||||||
describe('Datasource-specific field types for foreign keys', function () {
|
describe('Datasource-specific field types for foreign keys', function() {
|
||||||
before(function () {
|
before(function() {
|
||||||
ds = new DataSource('memory');
|
ds = new DataSource('memory');
|
||||||
Item = ds.define('Item', {
|
Item = ds.define('Item', {
|
||||||
"myProp": {
|
'myProp': {
|
||||||
"id": true,
|
'id': true,
|
||||||
"type": "string",
|
'type': 'string',
|
||||||
"memory": {
|
'memory': {
|
||||||
"dataType": "string"
|
'dataType': 'string',
|
||||||
}
|
},
|
||||||
}
|
},
|
||||||
});
|
});
|
||||||
Variant = ds.define('Variant', {}, {
|
Variant = ds.define('Variant', {}, {
|
||||||
relations: {
|
relations: {
|
||||||
"item": {
|
'item': {
|
||||||
"type": "belongsTo",
|
'type': 'belongsTo',
|
||||||
"as": "item",
|
'as': 'item',
|
||||||
"model": "Item",
|
'model': 'Item',
|
||||||
"foreignKey": "myProp"
|
'foreignKey': 'myProp',
|
||||||
}
|
},
|
||||||
}
|
},
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
it('should create foreign key with database-specific field type', function (done) {
|
it('should create foreign key with database-specific field type', function(done) {
|
||||||
var VariantDefinition = ds.getModelDefinition('Variant');
|
var VariantDefinition = ds.getModelDefinition('Variant');
|
||||||
should.exist(VariantDefinition);
|
should.exist(VariantDefinition);
|
||||||
should.exist(VariantDefinition.properties.myProp.memory);
|
should.exist(VariantDefinition.properties.myProp.memory);
|
||||||
should.exist(VariantDefinition.properties.myProp.memory.dataType);
|
should.exist(VariantDefinition.properties.myProp.memory.dataType);
|
||||||
VariantDefinition.properties.myProp.memory.dataType.should.be.equal("string");
|
VariantDefinition.properties.myProp.memory.dataType.should.be.equal('string');
|
||||||
done();
|
done();
|
||||||
});
|
});
|
||||||
})
|
})
|
||||||
|
|
|
@ -160,7 +160,7 @@ describe('async observer', function() {
|
||||||
it('passes context to final callback', function(done) {
|
it('passes context to final callback', function(done) {
|
||||||
var context = {};
|
var context = {};
|
||||||
TestModel.notifyObserversOf('event', context, function(err, ctx) {
|
TestModel.notifyObserversOf('event', context, function(err, ctx) {
|
||||||
(ctx || "null").should.equal(context);
|
(ctx || 'null').should.equal(context);
|
||||||
done();
|
done();
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
|
@ -8,52 +8,52 @@ var should = require('./init.js');
|
||||||
var async = require('async');
|
var async = require('async');
|
||||||
var db, User;
|
var db, User;
|
||||||
|
|
||||||
describe('basic-querying', function () {
|
describe('basic-querying', function() {
|
||||||
|
|
||||||
before(function (done) {
|
before(function(done) {
|
||||||
db = getSchema();
|
db = getSchema();
|
||||||
User = db.define('User', {
|
User = db.define('User', {
|
||||||
seq: {type: Number, index: true},
|
seq: { type: Number, index: true },
|
||||||
name: {type: String, index: true, sort: true},
|
name: { type: String, index: true, sort: true },
|
||||||
email: {type: String, index: true},
|
email: { type: String, index: true },
|
||||||
birthday: {type: Date, index: true},
|
birthday: { type: Date, index: true },
|
||||||
role: {type: String, index: true},
|
role: { type: String, index: true },
|
||||||
order: {type: Number, index: true, sort: true},
|
order: { type: Number, index: true, sort: true },
|
||||||
vip: {type: Boolean}
|
vip: { type: Boolean },
|
||||||
});
|
});
|
||||||
|
|
||||||
db.automigrate(done);
|
db.automigrate(done);
|
||||||
|
|
||||||
});
|
});
|
||||||
|
|
||||||
describe('ping', function () {
|
describe('ping', function() {
|
||||||
it('should be able to test connections', function (done) {
|
it('should be able to test connections', function(done) {
|
||||||
db.ping(function (err) {
|
db.ping(function(err) {
|
||||||
should.not.exist(err);
|
should.not.exist(err);
|
||||||
done();
|
done();
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
describe('findById', function () {
|
describe('findById', function() {
|
||||||
|
|
||||||
before(function (done) {
|
before(function(done) {
|
||||||
User.destroyAll(done);
|
User.destroyAll(done);
|
||||||
});
|
});
|
||||||
|
|
||||||
it('should query by id: not found', function (done) {
|
it('should query by id: not found', function(done) {
|
||||||
User.findById(1, function (err, u) {
|
User.findById(1, function(err, u) {
|
||||||
should.not.exist(u);
|
should.not.exist(u);
|
||||||
should.not.exist(err);
|
should.not.exist(err);
|
||||||
done();
|
done();
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
it('should query by id: found', function (done) {
|
it('should query by id: found', function(done) {
|
||||||
User.create(function (err, u) {
|
User.create(function(err, u) {
|
||||||
should.not.exist(err);
|
should.not.exist(err);
|
||||||
should.exist(u.id);
|
should.exist(u.id);
|
||||||
User.findById(u.id, function (err, u) {
|
User.findById(u.id, function(err, u) {
|
||||||
should.exist(u);
|
should.exist(u);
|
||||||
should.not.exist(err);
|
should.not.exist(err);
|
||||||
u.should.be.an.instanceOf(User);
|
u.should.be.an.instanceOf(User);
|
||||||
|
@ -64,7 +64,7 @@ describe('basic-querying', function () {
|
||||||
|
|
||||||
});
|
});
|
||||||
|
|
||||||
describe('findByIds', function () {
|
describe('findByIds', function() {
|
||||||
var createdUsers;
|
var createdUsers;
|
||||||
before(function(done) {
|
before(function(done) {
|
||||||
var people = [
|
var people = [
|
||||||
|
@ -73,7 +73,7 @@ describe('basic-querying', function () {
|
||||||
{ name: 'c' },
|
{ name: 'c' },
|
||||||
{ name: 'd', vip: true },
|
{ name: 'd', vip: true },
|
||||||
{ name: 'e' },
|
{ name: 'e' },
|
||||||
{ name: 'f' }
|
{ name: 'f' },
|
||||||
];
|
];
|
||||||
db.automigrate(['User'], function(err) {
|
db.automigrate(['User'], function(err) {
|
||||||
User.create(people, function(err, users) {
|
User.create(people, function(err, users) {
|
||||||
|
@ -103,11 +103,11 @@ describe('basic-querying', function () {
|
||||||
|
|
||||||
it('should query by ids and condition', function(done) {
|
it('should query by ids and condition', function(done) {
|
||||||
User.findByIds([
|
User.findByIds([
|
||||||
createdUsers[0].id,
|
createdUsers[0].id,
|
||||||
createdUsers[1].id,
|
createdUsers[1].id,
|
||||||
createdUsers[2].id,
|
createdUsers[2].id,
|
||||||
createdUsers[3].id],
|
createdUsers[3].id],
|
||||||
{ where: { vip: true } }, function(err, users) {
|
{ where: { vip: true }}, function(err, users) {
|
||||||
should.exist(users);
|
should.exist(users);
|
||||||
should.not.exist(err);
|
should.not.exist(err);
|
||||||
var names = users.map(function(u) {
|
var names = users.map(function(u) {
|
||||||
|
@ -125,12 +125,12 @@ describe('basic-querying', function () {
|
||||||
|
|
||||||
});
|
});
|
||||||
|
|
||||||
describe('find', function () {
|
describe('find', function() {
|
||||||
|
|
||||||
before(seed);
|
before(seed);
|
||||||
|
|
||||||
it('should query collection', function (done) {
|
it('should query collection', function(done) {
|
||||||
User.find(function (err, users) {
|
User.find(function(err, users) {
|
||||||
should.exists(users);
|
should.exists(users);
|
||||||
should.not.exists(err);
|
should.not.exists(err);
|
||||||
users.should.have.lengthOf(6);
|
users.should.have.lengthOf(6);
|
||||||
|
@ -138,8 +138,8 @@ describe('basic-querying', function () {
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
it('should query limited collection', function (done) {
|
it('should query limited collection', function(done) {
|
||||||
User.find({limit: 3}, function (err, users) {
|
User.find({ limit: 3 }, function(err, users) {
|
||||||
should.exists(users);
|
should.exists(users);
|
||||||
should.not.exists(err);
|
should.not.exists(err);
|
||||||
users.should.have.lengthOf(3);
|
users.should.have.lengthOf(3);
|
||||||
|
@ -147,8 +147,8 @@ describe('basic-querying', function () {
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
it('should query collection with skip & limit', function (done) {
|
it('should query collection with skip & limit', function(done) {
|
||||||
User.find({skip: 1, limit: 4, order: 'seq'}, function (err, users) {
|
User.find({ skip: 1, limit: 4, order: 'seq' }, function(err, users) {
|
||||||
should.exists(users);
|
should.exists(users);
|
||||||
should.not.exists(err);
|
should.not.exists(err);
|
||||||
users[0].seq.should.be.eql(1);
|
users[0].seq.should.be.eql(1);
|
||||||
|
@ -157,8 +157,8 @@ describe('basic-querying', function () {
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
it('should query collection with offset & limit', function (done) {
|
it('should query collection with offset & limit', function(done) {
|
||||||
User.find({offset: 2, limit: 3, order: 'seq'}, function (err, users) {
|
User.find({ offset: 2, limit: 3, order: 'seq' }, function(err, users) {
|
||||||
should.exists(users);
|
should.exists(users);
|
||||||
should.not.exists(err);
|
should.not.exists(err);
|
||||||
users[0].seq.should.be.eql(2);
|
users[0].seq.should.be.eql(2);
|
||||||
|
@ -167,8 +167,8 @@ describe('basic-querying', function () {
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
it('should query filtered collection', function (done) {
|
it('should query filtered collection', function(done) {
|
||||||
User.find({where: {role: 'lead'}}, function (err, users) {
|
User.find({ where: { role: 'lead' }}, function(err, users) {
|
||||||
should.exists(users);
|
should.exists(users);
|
||||||
should.not.exists(err);
|
should.not.exists(err);
|
||||||
users.should.have.lengthOf(2);
|
users.should.have.lengthOf(2);
|
||||||
|
@ -176,30 +176,30 @@ describe('basic-querying', function () {
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
it('should query collection sorted by numeric field', function (done) {
|
it('should query collection sorted by numeric field', function(done) {
|
||||||
User.find({order: 'order'}, function (err, users) {
|
User.find({ order: 'order' }, function(err, users) {
|
||||||
should.exists(users);
|
should.exists(users);
|
||||||
should.not.exists(err);
|
should.not.exists(err);
|
||||||
users.forEach(function (u, i) {
|
users.forEach(function(u, i) {
|
||||||
u.order.should.eql(i + 1);
|
u.order.should.eql(i + 1);
|
||||||
});
|
});
|
||||||
done();
|
done();
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
it('should query collection desc sorted by numeric field', function (done) {
|
it('should query collection desc sorted by numeric field', function(done) {
|
||||||
User.find({order: 'order DESC'}, function (err, users) {
|
User.find({ order: 'order DESC' }, function(err, users) {
|
||||||
should.exists(users);
|
should.exists(users);
|
||||||
should.not.exists(err);
|
should.not.exists(err);
|
||||||
users.forEach(function (u, i) {
|
users.forEach(function(u, i) {
|
||||||
u.order.should.eql(users.length - i);
|
u.order.should.eql(users.length - i);
|
||||||
});
|
});
|
||||||
done();
|
done();
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
it('should query collection sorted by string field', function (done) {
|
it('should query collection sorted by string field', function(done) {
|
||||||
User.find({order: 'name'}, function (err, users) {
|
User.find({ order: 'name' }, function(err, users) {
|
||||||
should.exists(users);
|
should.exists(users);
|
||||||
should.not.exists(err);
|
should.not.exists(err);
|
||||||
users.shift().name.should.equal('George Harrison');
|
users.shift().name.should.equal('George Harrison');
|
||||||
|
@ -209,8 +209,8 @@ describe('basic-querying', function () {
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
it('should query collection desc sorted by string field', function (done) {
|
it('should query collection desc sorted by string field', function(done) {
|
||||||
User.find({order: 'name DESC'}, function (err, users) {
|
User.find({ order: 'name DESC' }, function(err, users) {
|
||||||
should.exists(users);
|
should.exists(users);
|
||||||
should.not.exists(err);
|
should.not.exists(err);
|
||||||
users.pop().name.should.equal('George Harrison');
|
users.pop().name.should.equal('George Harrison');
|
||||||
|
@ -220,53 +220,53 @@ describe('basic-querying', function () {
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
it('should support "and" operator that is satisfied', function (done) {
|
it('should support "and" operator that is satisfied', function(done) {
|
||||||
User.find({where: {and: [
|
User.find({ where: { and: [
|
||||||
{name: 'John Lennon'},
|
{ name: 'John Lennon' },
|
||||||
{role: 'lead'}
|
{ role: 'lead' },
|
||||||
]}}, function (err, users) {
|
] }}, function(err, users) {
|
||||||
should.not.exist(err);
|
should.not.exist(err);
|
||||||
users.should.have.property('length', 1);
|
users.should.have.property('length', 1);
|
||||||
done();
|
done();
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
it('should support "and" operator that is not satisfied', function (done) {
|
it('should support "and" operator that is not satisfied', function(done) {
|
||||||
User.find({where: {and: [
|
User.find({ where: { and: [
|
||||||
{name: 'John Lennon'},
|
{ name: 'John Lennon' },
|
||||||
{role: 'member'}
|
{ role: 'member' },
|
||||||
]}}, function (err, users) {
|
] }}, function(err, users) {
|
||||||
should.not.exist(err);
|
should.not.exist(err);
|
||||||
users.should.have.property('length', 0);
|
users.should.have.property('length', 0);
|
||||||
done();
|
done();
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
it('should support "or" that is satisfied', function (done) {
|
it('should support "or" that is satisfied', function(done) {
|
||||||
User.find({where: {or: [
|
User.find({ where: { or: [
|
||||||
{name: 'John Lennon'},
|
{ name: 'John Lennon' },
|
||||||
{role: 'lead'}
|
{ role: 'lead' },
|
||||||
]}}, function (err, users) {
|
] }}, function(err, users) {
|
||||||
should.not.exist(err);
|
should.not.exist(err);
|
||||||
users.should.have.property('length', 2);
|
users.should.have.property('length', 2);
|
||||||
done();
|
done();
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
it('should support "or" operator that is not satisfied', function (done) {
|
it('should support "or" operator that is not satisfied', function(done) {
|
||||||
User.find({where: {or: [
|
User.find({ where: { or: [
|
||||||
{name: 'XYZ'},
|
{ name: 'XYZ' },
|
||||||
{role: 'Hello1'}
|
{ role: 'Hello1' },
|
||||||
]}}, function (err, users) {
|
] }}, function(err, users) {
|
||||||
should.not.exist(err);
|
should.not.exist(err);
|
||||||
users.should.have.property('length', 0);
|
users.should.have.property('length', 0);
|
||||||
done();
|
done();
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
it('should support date "gte" that is satisfied', function (done) {
|
it('should support date "gte" that is satisfied', function(done) {
|
||||||
User.find({order: 'seq', where: { birthday: { "gte": new Date('1980-12-08') }
|
User.find({ order: 'seq', where: { birthday: { 'gte': new Date('1980-12-08') },
|
||||||
}}, function (err, users) {
|
}}, function(err, users) {
|
||||||
should.not.exist(err);
|
should.not.exist(err);
|
||||||
users.should.have.property('length', 1);
|
users.should.have.property('length', 1);
|
||||||
users[0].name.should.equal('John Lennon');
|
users[0].name.should.equal('John Lennon');
|
||||||
|
@ -274,18 +274,18 @@ describe('basic-querying', function () {
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
it('should support date "gt" that is not satisfied', function (done) {
|
it('should support date "gt" that is not satisfied', function(done) {
|
||||||
User.find({order: 'seq', where: { birthday: { "gt": new Date('1980-12-08') }
|
User.find({ order: 'seq', where: { birthday: { 'gt': new Date('1980-12-08') },
|
||||||
}}, function (err, users) {
|
}}, function(err, users) {
|
||||||
should.not.exist(err);
|
should.not.exist(err);
|
||||||
users.should.have.property('length', 0);
|
users.should.have.property('length', 0);
|
||||||
done();
|
done();
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
it('should support date "gt" that is satisfied', function (done) {
|
it('should support date "gt" that is satisfied', function(done) {
|
||||||
User.find({order: 'seq', where: { birthday: { "gt": new Date('1980-12-07') }
|
User.find({ order: 'seq', where: { birthday: { 'gt': new Date('1980-12-07') },
|
||||||
}}, function (err, users) {
|
}}, function(err, users) {
|
||||||
should.not.exist(err);
|
should.not.exist(err);
|
||||||
users.should.have.property('length', 1);
|
users.should.have.property('length', 1);
|
||||||
users[0].name.should.equal('John Lennon');
|
users[0].name.should.equal('John Lennon');
|
||||||
|
@ -293,9 +293,9 @@ describe('basic-querying', function () {
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
it('should support date "lt" that is satisfied', function (done) {
|
it('should support date "lt" that is satisfied', function(done) {
|
||||||
User.find({order: 'seq', where: { birthday: { "lt": new Date('1980-12-07') }
|
User.find({ order: 'seq', where: { birthday: { 'lt': new Date('1980-12-07') },
|
||||||
}}, function (err, users) {
|
}}, function(err, users) {
|
||||||
should.not.exist(err);
|
should.not.exist(err);
|
||||||
users.should.have.property('length', 1);
|
users.should.have.property('length', 1);
|
||||||
users[0].name.should.equal('Paul McCartney');
|
users[0].name.should.equal('Paul McCartney');
|
||||||
|
@ -303,9 +303,9 @@ describe('basic-querying', function () {
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
it('should support number "gte" that is satisfied', function (done) {
|
it('should support number "gte" that is satisfied', function(done) {
|
||||||
User.find({order: 'seq', where: { order: { "gte": 3}
|
User.find({ order: 'seq', where: { order: { 'gte': 3 },
|
||||||
}}, function (err, users) {
|
}}, function(err, users) {
|
||||||
should.not.exist(err);
|
should.not.exist(err);
|
||||||
users.should.have.property('length', 4);
|
users.should.have.property('length', 4);
|
||||||
users[0].name.should.equal('George Harrison');
|
users[0].name.should.equal('George Harrison');
|
||||||
|
@ -313,18 +313,18 @@ describe('basic-querying', function () {
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
it('should support number "gt" that is not satisfied', function (done) {
|
it('should support number "gt" that is not satisfied', function(done) {
|
||||||
User.find({order: 'seq', where: { order: { "gt": 6 }
|
User.find({ order: 'seq', where: { order: { 'gt': 6 },
|
||||||
}}, function (err, users) {
|
}}, function(err, users) {
|
||||||
should.not.exist(err);
|
should.not.exist(err);
|
||||||
users.should.have.property('length', 0);
|
users.should.have.property('length', 0);
|
||||||
done();
|
done();
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
it('should support number "gt" that is satisfied', function (done) {
|
it('should support number "gt" that is satisfied', function(done) {
|
||||||
User.find({order: 'seq', where: { order: { "gt": 5 }
|
User.find({ order: 'seq', where: { order: { 'gt': 5 },
|
||||||
}}, function (err, users) {
|
}}, function(err, users) {
|
||||||
should.not.exist(err);
|
should.not.exist(err);
|
||||||
users.should.have.property('length', 1);
|
users.should.have.property('length', 1);
|
||||||
users[0].name.should.equal('Ringo Starr');
|
users[0].name.should.equal('Ringo Starr');
|
||||||
|
@ -332,9 +332,9 @@ describe('basic-querying', function () {
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
it('should support number "lt" that is satisfied', function (done) {
|
it('should support number "lt" that is satisfied', function(done) {
|
||||||
User.find({order: 'seq', where: { order: { "lt": 2 }
|
User.find({ order: 'seq', where: { order: { 'lt': 2 },
|
||||||
}}, function (err, users) {
|
}}, function(err, users) {
|
||||||
should.not.exist(err);
|
should.not.exist(err);
|
||||||
users.should.have.property('length', 1);
|
users.should.have.property('length', 1);
|
||||||
users[0].name.should.equal('Paul McCartney');
|
users[0].name.should.equal('Paul McCartney');
|
||||||
|
@ -342,36 +342,36 @@ describe('basic-querying', function () {
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
it('should support number "gt" that is satisfied by null value', function (done) {
|
it('should support number "gt" that is satisfied by null value', function(done) {
|
||||||
User.find({order: 'seq', where: { order: { "gt": null }
|
User.find({ order: 'seq', where: { order: { 'gt': null },
|
||||||
}}, function (err, users) {
|
}}, function(err, users) {
|
||||||
should.not.exist(err);
|
should.not.exist(err);
|
||||||
users.should.have.property('length', 0);
|
users.should.have.property('length', 0);
|
||||||
done();
|
done();
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
it('should support number "lt" that is not satisfied by null value', function (done) {
|
it('should support number "lt" that is not satisfied by null value', function(done) {
|
||||||
User.find({order: 'seq', where: { order: { "lt": null }
|
User.find({ order: 'seq', where: { order: { 'lt': null },
|
||||||
}}, function (err, users) {
|
}}, function(err, users) {
|
||||||
should.not.exist(err);
|
should.not.exist(err);
|
||||||
users.should.have.property('length', 0);
|
users.should.have.property('length', 0);
|
||||||
done();
|
done();
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
it('should support string "gte" that is satisfied by null value', function (done) {
|
it('should support string "gte" that is satisfied by null value', function(done) {
|
||||||
User.find({order: 'seq', where: { name: { "gte": null}
|
User.find({ order: 'seq', where: { name: { 'gte': null },
|
||||||
}}, function (err, users) {
|
}}, function(err, users) {
|
||||||
should.not.exist(err);
|
should.not.exist(err);
|
||||||
users.should.have.property('length', 0);
|
users.should.have.property('length', 0);
|
||||||
done();
|
done();
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
it('should support string "gte" that is satisfied', function (done) {
|
it('should support string "gte" that is satisfied', function(done) {
|
||||||
User.find({order: 'seq', where: { name: { "gte": 'Paul McCartney'}
|
User.find({ order: 'seq', where: { name: { 'gte': 'Paul McCartney' },
|
||||||
}}, function (err, users) {
|
}}, function(err, users) {
|
||||||
should.not.exist(err);
|
should.not.exist(err);
|
||||||
users.should.have.property('length', 4);
|
users.should.have.property('length', 4);
|
||||||
users[0].name.should.equal('Paul McCartney');
|
users[0].name.should.equal('Paul McCartney');
|
||||||
|
@ -379,18 +379,18 @@ describe('basic-querying', function () {
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
it('should support string "gt" that is not satisfied', function (done) {
|
it('should support string "gt" that is not satisfied', function(done) {
|
||||||
User.find({order: 'seq', where: { name: { "gt": 'xyz' }
|
User.find({ order: 'seq', where: { name: { 'gt': 'xyz' },
|
||||||
}}, function (err, users) {
|
}}, function(err, users) {
|
||||||
should.not.exist(err);
|
should.not.exist(err);
|
||||||
users.should.have.property('length', 0);
|
users.should.have.property('length', 0);
|
||||||
done();
|
done();
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
it('should support string "gt" that is satisfied', function (done) {
|
it('should support string "gt" that is satisfied', function(done) {
|
||||||
User.find({order: 'seq', where: { name: { "gt": 'Paul McCartney' }
|
User.find({ order: 'seq', where: { name: { 'gt': 'Paul McCartney' },
|
||||||
}}, function (err, users) {
|
}}, function(err, users) {
|
||||||
should.not.exist(err);
|
should.not.exist(err);
|
||||||
users.should.have.property('length', 3);
|
users.should.have.property('length', 3);
|
||||||
users[0].name.should.equal('Ringo Starr');
|
users[0].name.should.equal('Ringo Starr');
|
||||||
|
@ -398,9 +398,9 @@ describe('basic-querying', function () {
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
it('should support string "lt" that is satisfied', function (done) {
|
it('should support string "lt" that is satisfied', function(done) {
|
||||||
User.find({order: 'seq', where: { name: { "lt": 'Paul McCartney' }
|
User.find({ order: 'seq', where: { name: { 'lt': 'Paul McCartney' },
|
||||||
}}, function (err, users) {
|
}}, function(err, users) {
|
||||||
should.not.exist(err);
|
should.not.exist(err);
|
||||||
users.should.have.property('length', 2);
|
users.should.have.property('length', 2);
|
||||||
users[0].name.should.equal('John Lennon');
|
users[0].name.should.equal('John Lennon');
|
||||||
|
@ -408,9 +408,9 @@ describe('basic-querying', function () {
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
it('should support boolean "gte" that is satisfied', function (done) {
|
it('should support boolean "gte" that is satisfied', function(done) {
|
||||||
User.find({order: 'seq', where: { vip: { "gte": true}
|
User.find({ order: 'seq', where: { vip: { 'gte': true },
|
||||||
}}, function (err, users) {
|
}}, function(err, users) {
|
||||||
should.not.exist(err);
|
should.not.exist(err);
|
||||||
users.should.have.property('length', 3);
|
users.should.have.property('length', 3);
|
||||||
users[0].name.should.equal('John Lennon');
|
users[0].name.should.equal('John Lennon');
|
||||||
|
@ -418,18 +418,18 @@ describe('basic-querying', function () {
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
it('should support boolean "gt" that is not satisfied', function (done) {
|
it('should support boolean "gt" that is not satisfied', function(done) {
|
||||||
User.find({order: 'seq', where: { vip: { "gt": true }
|
User.find({ order: 'seq', where: { vip: { 'gt': true },
|
||||||
}}, function (err, users) {
|
}}, function(err, users) {
|
||||||
should.not.exist(err);
|
should.not.exist(err);
|
||||||
users.should.have.property('length', 0);
|
users.should.have.property('length', 0);
|
||||||
done();
|
done();
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
it('should support boolean "gt" that is satisfied', function (done) {
|
it('should support boolean "gt" that is satisfied', function(done) {
|
||||||
User.find({order: 'seq', where: { vip: { "gt": false }
|
User.find({ order: 'seq', where: { vip: { 'gt': false },
|
||||||
}}, function (err, users) {
|
}}, function(err, users) {
|
||||||
should.not.exist(err);
|
should.not.exist(err);
|
||||||
users.should.have.property('length', 3);
|
users.should.have.property('length', 3);
|
||||||
users[0].name.should.equal('John Lennon');
|
users[0].name.should.equal('John Lennon');
|
||||||
|
@ -437,9 +437,9 @@ describe('basic-querying', function () {
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
it('should support boolean "lt" that is satisfied', function (done) {
|
it('should support boolean "lt" that is satisfied', function(done) {
|
||||||
User.find({order: 'seq', where: { vip: { "lt": true }
|
User.find({ order: 'seq', where: { vip: { 'lt': true },
|
||||||
}}, function (err, users) {
|
}}, function(err, users) {
|
||||||
should.not.exist(err);
|
should.not.exist(err);
|
||||||
users.should.have.property('length', 2);
|
users.should.have.property('length', 2);
|
||||||
users[0].name.should.equal('George Harrison');
|
users[0].name.should.equal('George Harrison');
|
||||||
|
@ -448,15 +448,15 @@ describe('basic-querying', function () {
|
||||||
});
|
});
|
||||||
|
|
||||||
|
|
||||||
it('should only include fields as specified', function (done) {
|
it('should only include fields as specified', function(done) {
|
||||||
var remaining = 0;
|
var remaining = 0;
|
||||||
|
|
||||||
function sample(fields) {
|
function sample(fields) {
|
||||||
|
|
||||||
return {
|
return {
|
||||||
expect: function (arr) {
|
expect: function(arr) {
|
||||||
remaining++;
|
remaining++;
|
||||||
User.find({fields: fields}, function (err, users) {
|
User.find({ fields: fields }, function(err, users) {
|
||||||
|
|
||||||
remaining--;
|
remaining--;
|
||||||
if (err) return done(err);
|
if (err) return done(err);
|
||||||
|
@ -467,11 +467,11 @@ describe('basic-querying', function () {
|
||||||
done();
|
done();
|
||||||
}
|
}
|
||||||
|
|
||||||
users.forEach(function (user) {
|
users.forEach(function(user) {
|
||||||
var obj = user.toObject();
|
var obj = user.toObject();
|
||||||
|
|
||||||
Object.keys(obj)
|
Object.keys(obj)
|
||||||
.forEach(function (key) {
|
.forEach(function(key) {
|
||||||
// if the obj has an unexpected value
|
// if the obj has an unexpected value
|
||||||
if (obj[key] !== undefined && arr.indexOf(key) === -1) {
|
if (obj[key] !== undefined && arr.indexOf(key) === -1) {
|
||||||
console.log('Given fields:', fields);
|
console.log('Given fields:', fields);
|
||||||
|
@ -482,14 +482,14 @@ describe('basic-querying', function () {
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
}
|
},
|
||||||
}
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
sample({name: true}).expect(['name']);
|
sample({ name: true }).expect(['name']);
|
||||||
sample({name: false}).expect(['id', 'seq', 'email', 'role', 'order', 'birthday', 'vip']);
|
sample({ name: false }).expect(['id', 'seq', 'email', 'role', 'order', 'birthday', 'vip']);
|
||||||
sample({name: false, id: true}).expect(['id']);
|
sample({ name: false, id: true }).expect(['id']);
|
||||||
sample({id: true}).expect(['id']);
|
sample({ id: true }).expect(['id']);
|
||||||
sample('id').expect(['id']);
|
sample('id').expect(['id']);
|
||||||
sample(['id']).expect(['id']);
|
sample(['id']).expect(['id']);
|
||||||
sample(['email']).expect(['email']);
|
sample(['email']).expect(['email']);
|
||||||
|
@ -497,12 +497,12 @@ describe('basic-querying', function () {
|
||||||
|
|
||||||
});
|
});
|
||||||
|
|
||||||
describe('count', function () {
|
describe('count', function() {
|
||||||
|
|
||||||
before(seed);
|
before(seed);
|
||||||
|
|
||||||
it('should query total count', function (done) {
|
it('should query total count', function(done) {
|
||||||
User.count(function (err, n) {
|
User.count(function(err, n) {
|
||||||
should.not.exist(err);
|
should.not.exist(err);
|
||||||
should.exist(n);
|
should.exist(n);
|
||||||
n.should.equal(6);
|
n.should.equal(6);
|
||||||
|
@ -510,8 +510,8 @@ describe('basic-querying', function () {
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
it('should query filtered count', function (done) {
|
it('should query filtered count', function(done) {
|
||||||
User.count({role: 'lead'}, function (err, n) {
|
User.count({ role: 'lead' }, function(err, n) {
|
||||||
should.not.exist(err);
|
should.not.exist(err);
|
||||||
should.exist(n);
|
should.exist(n);
|
||||||
n.should.equal(2);
|
n.should.equal(2);
|
||||||
|
@ -520,13 +520,13 @@ describe('basic-querying', function () {
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
describe('findOne', function () {
|
describe('findOne', function() {
|
||||||
|
|
||||||
before(seed);
|
before(seed);
|
||||||
|
|
||||||
it('should find first record (default sort by id)', function (done) {
|
it('should find first record (default sort by id)', function(done) {
|
||||||
User.all({order: 'id'}, function (err, users) {
|
User.all({ order: 'id' }, function(err, users) {
|
||||||
User.findOne(function (e, u) {
|
User.findOne(function(e, u) {
|
||||||
should.not.exist(e);
|
should.not.exist(e);
|
||||||
should.exist(u);
|
should.exist(u);
|
||||||
u.id.toString().should.equal(users[0].id.toString());
|
u.id.toString().should.equal(users[0].id.toString());
|
||||||
|
@ -535,8 +535,8 @@ describe('basic-querying', function () {
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
it('should find first record', function (done) {
|
it('should find first record', function(done) {
|
||||||
User.findOne({order: 'order'}, function (e, u) {
|
User.findOne({ order: 'order' }, function(e, u) {
|
||||||
should.not.exist(e);
|
should.not.exist(e);
|
||||||
should.exist(u);
|
should.exist(u);
|
||||||
u.order.should.equal(1);
|
u.order.should.equal(1);
|
||||||
|
@ -545,8 +545,8 @@ describe('basic-querying', function () {
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
it('should find last record', function (done) {
|
it('should find last record', function(done) {
|
||||||
User.findOne({order: 'order DESC'}, function (e, u) {
|
User.findOne({ order: 'order DESC' }, function(e, u) {
|
||||||
should.not.exist(e);
|
should.not.exist(e);
|
||||||
should.exist(u);
|
should.exist(u);
|
||||||
u.order.should.equal(6);
|
u.order.should.equal(6);
|
||||||
|
@ -555,11 +555,11 @@ describe('basic-querying', function () {
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
it('should find last record in filtered set', function (done) {
|
it('should find last record in filtered set', function(done) {
|
||||||
User.findOne({
|
User.findOne({
|
||||||
where: {role: 'lead'},
|
where: { role: 'lead' },
|
||||||
order: 'order DESC'
|
order: 'order DESC',
|
||||||
}, function (e, u) {
|
}, function(e, u) {
|
||||||
should.not.exist(e);
|
should.not.exist(e);
|
||||||
should.exist(u);
|
should.exist(u);
|
||||||
u.order.should.equal(2);
|
u.order.should.equal(2);
|
||||||
|
@ -568,9 +568,9 @@ describe('basic-querying', function () {
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
it('should work even when find by id', function (done) {
|
it('should work even when find by id', function(done) {
|
||||||
User.findOne(function (e, u) {
|
User.findOne(function(e, u) {
|
||||||
User.findOne({where: {id: u.id}}, function (err, user) {
|
User.findOne({ where: { id: u.id }}, function(err, user) {
|
||||||
should.not.exist(err);
|
should.not.exist(err);
|
||||||
should.exist(user);
|
should.exist(user);
|
||||||
done();
|
done();
|
||||||
|
@ -580,13 +580,13 @@ describe('basic-querying', function () {
|
||||||
|
|
||||||
});
|
});
|
||||||
|
|
||||||
describe('exists', function () {
|
describe('exists', function() {
|
||||||
|
|
||||||
before(seed);
|
before(seed);
|
||||||
|
|
||||||
it('should check whether record exist', function (done) {
|
it('should check whether record exist', function(done) {
|
||||||
User.findOne(function (e, u) {
|
User.findOne(function(e, u) {
|
||||||
User.exists(u.id, function (err, exists) {
|
User.exists(u.id, function(err, exists) {
|
||||||
should.not.exist(err);
|
should.not.exist(err);
|
||||||
should.exist(exists);
|
should.exist(exists);
|
||||||
exists.should.be.ok;
|
exists.should.be.ok;
|
||||||
|
@ -595,9 +595,9 @@ describe('basic-querying', function () {
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
it('should check whether record not exist', function (done) {
|
it('should check whether record not exist', function(done) {
|
||||||
User.destroyAll(function () {
|
User.destroyAll(function() {
|
||||||
User.exists(42, function (err, exists) {
|
User.exists(42, function(err, exists) {
|
||||||
should.not.exist(err);
|
should.not.exist(err);
|
||||||
exists.should.not.be.ok;
|
exists.should.not.be.ok;
|
||||||
done();
|
done();
|
||||||
|
@ -615,7 +615,7 @@ describe('basic-querying', function () {
|
||||||
// `undefined` is not tested because the `removeUndefined` function
|
// `undefined` is not tested because the `removeUndefined` function
|
||||||
// in `lib/dao.js` removes it before coercion
|
// in `lib/dao.js` removes it before coercion
|
||||||
invalidDataTypes.forEach(function(invalidDataType) {
|
invalidDataTypes.forEach(function(invalidDataType) {
|
||||||
User.find({where: {name: {regexp: invalidDataType}}}, function(err,
|
User.find({ where: { name: { regexp: invalidDataType }}}, function(err,
|
||||||
users) {
|
users) {
|
||||||
should.exist(err);
|
should.exist(err);
|
||||||
});
|
});
|
||||||
|
@ -632,25 +632,25 @@ describe.skip('queries', function() {
|
||||||
var db = getSchema();
|
var db = getSchema();
|
||||||
Todo = db.define('Todo', {
|
Todo = db.define('Todo', {
|
||||||
id: false,
|
id: false,
|
||||||
content: {type: 'string'}
|
content: { type: 'string' },
|
||||||
}, {
|
}, {
|
||||||
idInjection: false
|
idInjection: false,
|
||||||
});
|
});
|
||||||
db.automigrate(['Todo'], done);
|
db.automigrate(['Todo'], done);
|
||||||
});
|
});
|
||||||
beforeEach(function resetFixtures(done) {
|
beforeEach(function resetFixtures(done) {
|
||||||
Todo.destroyAll(function() {
|
Todo.destroyAll(function() {
|
||||||
Todo.create([
|
Todo.create([
|
||||||
{content: 'Buy eggs'},
|
{ content: 'Buy eggs' },
|
||||||
{content: 'Buy milk'},
|
{ content: 'Buy milk' },
|
||||||
{content: 'Buy sausages'}
|
{ content: 'Buy sausages' },
|
||||||
], done);
|
], done);
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
context('that do not require an id', function() {
|
context('that do not require an id', function() {
|
||||||
it('should work for create', function(done) {
|
it('should work for create', function(done) {
|
||||||
Todo.create({content: 'Buy ham'}, function(err) {
|
Todo.create({ content: 'Buy ham' }, function(err) {
|
||||||
should.not.exist(err);
|
should.not.exist(err);
|
||||||
done();
|
done();
|
||||||
});
|
});
|
||||||
|
@ -659,7 +659,7 @@ describe.skip('queries', function() {
|
||||||
it('should work for updateOrCreate/upsert', function(done) {
|
it('should work for updateOrCreate/upsert', function(done) {
|
||||||
var aliases = ['updateOrCreate', 'upsert'];
|
var aliases = ['updateOrCreate', 'upsert'];
|
||||||
async.each(aliases, function(alias, cb) {
|
async.each(aliases, function(alias, cb) {
|
||||||
Todo[alias]({content: 'Buy ham'}, function(err) {
|
Todo[alias]({ content: 'Buy ham' }, function(err) {
|
||||||
should.not.exist(err);
|
should.not.exist(err);
|
||||||
cb();
|
cb();
|
||||||
});
|
});
|
||||||
|
@ -667,14 +667,14 @@ describe.skip('queries', function() {
|
||||||
});
|
});
|
||||||
|
|
||||||
it('should work for findOrCreate', function(done) {
|
it('should work for findOrCreate', function(done) {
|
||||||
Todo.findOrCreate({content: 'Buy ham'}, function(err) {
|
Todo.findOrCreate({ content: 'Buy ham' }, function(err) {
|
||||||
should.not.exist(err);
|
should.not.exist(err);
|
||||||
done();
|
done();
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
it('should work for exists', function(done) {
|
it('should work for exists', function(done) {
|
||||||
Todo.exists({content: 'Buy ham'}, function(err) {
|
Todo.exists({ content: 'Buy ham' }, function(err) {
|
||||||
should.not.exist(err);
|
should.not.exist(err);
|
||||||
done();
|
done();
|
||||||
});
|
});
|
||||||
|
@ -707,14 +707,14 @@ describe.skip('queries', function() {
|
||||||
});
|
});
|
||||||
|
|
||||||
it('should work for update/updateAll', function(done) {
|
it('should work for update/updateAll', function(done) {
|
||||||
Todo.update({content: 'Buy ham'}, function(err) {
|
Todo.update({ content: 'Buy ham' }, function(err) {
|
||||||
should.not.exist(err);
|
should.not.exist(err);
|
||||||
done();
|
done();
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
it('should work for count', function(done) {
|
it('should work for count', function(done) {
|
||||||
Todo.count({content: 'Buy eggs'}, function(err) {
|
Todo.count({ content: 'Buy eggs' }, function(err) {
|
||||||
should.not.exist(err);
|
should.not.exist(err);
|
||||||
done();
|
done();
|
||||||
});
|
});
|
||||||
|
@ -742,15 +742,15 @@ describe.skip('queries', function() {
|
||||||
|
|
||||||
it('should return an error for deleteById/destroyById/removeById',
|
it('should return an error for deleteById/destroyById/removeById',
|
||||||
function(done) {
|
function(done) {
|
||||||
var aliases = ['deleteById', 'destroyById', 'removeById'];
|
var aliases = ['deleteById', 'destroyById', 'removeById'];
|
||||||
async.each(aliases, function(alias, cb) {
|
async.each(aliases, function(alias, cb) {
|
||||||
Todo[alias](1, function(err) {
|
Todo[alias](1, function(err) {
|
||||||
should.exist(err);
|
should.exist(err);
|
||||||
err.message.should.equal(expectedErrMsg);
|
err.message.should.equal(expectedErrMsg);
|
||||||
cb();
|
cb();
|
||||||
});
|
});
|
||||||
}, done);
|
}, done);
|
||||||
});
|
});
|
||||||
|
|
||||||
it('should return an error for instance.save', function(done) {
|
it('should return an error for instance.save', function(done) {
|
||||||
var todo = new Todo();
|
var todo = new Todo();
|
||||||
|
@ -784,7 +784,7 @@ describe.skip('queries', function() {
|
||||||
|
|
||||||
it('should return an error for instance.updateAttributes', function(done) {
|
it('should return an error for instance.updateAttributes', function(done) {
|
||||||
Todo.findOne(function(err, todo) {
|
Todo.findOne(function(err, todo) {
|
||||||
todo.updateAttributes({content: 'Buy ham'}, function(err) {
|
todo.updateAttributes({ content: 'Buy ham' }, function(err) {
|
||||||
should.exist(err);
|
should.exist(err);
|
||||||
err.message.should.equal(expectedErrMsg);
|
err.message.should.equal(expectedErrMsg);
|
||||||
done();
|
done();
|
||||||
|
@ -803,7 +803,7 @@ function seed(done) {
|
||||||
role: 'lead',
|
role: 'lead',
|
||||||
birthday: new Date('1980-12-08'),
|
birthday: new Date('1980-12-08'),
|
||||||
order: 2,
|
order: 2,
|
||||||
vip: true
|
vip: true,
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
seq: 1,
|
seq: 1,
|
||||||
|
@ -812,18 +812,18 @@ function seed(done) {
|
||||||
role: 'lead',
|
role: 'lead',
|
||||||
birthday: new Date('1942-06-18'),
|
birthday: new Date('1942-06-18'),
|
||||||
order: 1,
|
order: 1,
|
||||||
vip: true
|
vip: true,
|
||||||
},
|
},
|
||||||
{seq: 2, name: 'George Harrison', order: 5, vip: false},
|
{ seq: 2, name: 'George Harrison', order: 5, vip: false },
|
||||||
{seq: 3, name: 'Ringo Starr', order: 6, vip: false},
|
{ seq: 3, name: 'Ringo Starr', order: 6, vip: false },
|
||||||
{seq: 4, name: 'Pete Best', order: 4},
|
{ seq: 4, name: 'Pete Best', order: 4 },
|
||||||
{seq: 5, name: 'Stuart Sutcliffe', order: 3, vip: true}
|
{ seq: 5, name: 'Stuart Sutcliffe', order: 3, vip: true },
|
||||||
];
|
];
|
||||||
|
|
||||||
async.series([
|
async.series([
|
||||||
User.destroyAll.bind(User),
|
User.destroyAll.bind(User),
|
||||||
function(cb) {
|
function(cb) {
|
||||||
async.each(beatles, User.create.bind(User), cb);
|
async.each(beatles, User.create.bind(User), cb);
|
||||||
}
|
},
|
||||||
], done);
|
], done);
|
||||||
}
|
}
|
||||||
|
|
|
@ -28,13 +28,13 @@ module.exports = function testSchema(exportCasesHere, dataSource) {
|
||||||
}
|
}
|
||||||
var start;
|
var start;
|
||||||
|
|
||||||
batch['should connect to database'] = function (test) {
|
batch['should connect to database'] = function(test) {
|
||||||
start = Date.now();
|
start = Date.now();
|
||||||
if (dataSource.connected) return test.done();
|
if (dataSource.connected) return test.done();
|
||||||
dataSource.on('connected', test.done);
|
dataSource.on('connected', test.done);
|
||||||
};
|
};
|
||||||
|
|
||||||
dataSource.log = function (a) {
|
dataSource.log = function(a) {
|
||||||
console.log(a);
|
console.log(a);
|
||||||
nbSchemaRequests++;
|
nbSchemaRequests++;
|
||||||
};
|
};
|
||||||
|
@ -43,7 +43,7 @@ module.exports = function testSchema(exportCasesHere, dataSource) {
|
||||||
|
|
||||||
testOrm(dataSource);
|
testOrm(dataSource);
|
||||||
|
|
||||||
batch['all tests done'] = function (test) {
|
batch['all tests done'] = function(test) {
|
||||||
test.done();
|
test.done();
|
||||||
process.nextTick(allTestsDone);
|
process.nextTick(allTestsDone);
|
||||||
};
|
};
|
||||||
|
@ -59,19 +59,19 @@ Object.defineProperty(module.exports, 'it', {
|
||||||
writable: true,
|
writable: true,
|
||||||
enumerable: false,
|
enumerable: false,
|
||||||
configurable: true,
|
configurable: true,
|
||||||
value: it
|
value: it,
|
||||||
});
|
});
|
||||||
|
|
||||||
Object.defineProperty(module.exports, 'skip', {
|
Object.defineProperty(module.exports, 'skip', {
|
||||||
writable: true,
|
writable: true,
|
||||||
enumerable: false,
|
enumerable: false,
|
||||||
configurable: true,
|
configurable: true,
|
||||||
value: skip
|
value: skip,
|
||||||
});
|
});
|
||||||
|
|
||||||
function clearAndCreate(model, data, callback) {
|
function clearAndCreate(model, data, callback) {
|
||||||
var createdItems = [];
|
var createdItems = [];
|
||||||
model.destroyAll(function () {
|
model.destroyAll(function() {
|
||||||
nextItem(null, null);
|
nextItem(null, null);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
@ -95,7 +95,7 @@ function testOrm(dataSource) {
|
||||||
|
|
||||||
var Post, User, Passport, Log, Dog;
|
var Post, User, Passport, Log, Dog;
|
||||||
|
|
||||||
it('should define class', function (test) {
|
it('should define class', function(test) {
|
||||||
|
|
||||||
User = dataSource.define('User', {
|
User = dataSource.define('User', {
|
||||||
name: { type: String, index: true },
|
name: { type: String, index: true },
|
||||||
|
@ -104,52 +104,52 @@ function testOrm(dataSource) {
|
||||||
approved: Boolean,
|
approved: Boolean,
|
||||||
joinedAt: Date,
|
joinedAt: Date,
|
||||||
age: Number,
|
age: Number,
|
||||||
passwd: { type: String, index: true }
|
passwd: { type: String, index: true },
|
||||||
});
|
});
|
||||||
|
|
||||||
Dog = dataSource.define('Dog', {
|
Dog = dataSource.define('Dog', {
|
||||||
name: { type: String, limit: 64, allowNull: false }
|
name: { type: String, limit: 64, allowNull: false },
|
||||||
});
|
});
|
||||||
|
|
||||||
Log = dataSource.define('Log', {
|
Log = dataSource.define('Log', {
|
||||||
ownerId: { type: Number, allowNull: true },
|
ownerId: { type: Number, allowNull: true },
|
||||||
name: { type: String, limit: 64, allowNull: false }
|
name: { type: String, limit: 64, allowNull: false },
|
||||||
});
|
});
|
||||||
|
|
||||||
Log.belongsTo(Dog, {as: 'owner', foreignKey: 'ownerId'});
|
Log.belongsTo(Dog, { as: 'owner', foreignKey: 'ownerId' });
|
||||||
|
|
||||||
dataSource.extendModel('User', {
|
dataSource.extendModel('User', {
|
||||||
settings: { type: Schema.JSON },
|
settings: { type: Schema.JSON },
|
||||||
extra: Object
|
extra: Object,
|
||||||
});
|
});
|
||||||
|
|
||||||
var newuser = new User({settings: {hey: 'you'}});
|
var newuser = new User({ settings: { hey: 'you' }});
|
||||||
test.ok(newuser.settings);
|
test.ok(newuser.settings);
|
||||||
|
|
||||||
Post = dataSource.define('Post', {
|
Post = dataSource.define('Post', {
|
||||||
title: { type: String, length: 255, index: true },
|
title: { type: String, length: 255, index: true },
|
||||||
subject: { type: String },
|
subject: { type: String },
|
||||||
content: { type: Text },
|
content: { type: Text },
|
||||||
date: { type: Date, default: function () {
|
date: { type: Date, default: function() {
|
||||||
return new Date
|
return new Date;
|
||||||
}, index: true },
|
}, index: true },
|
||||||
published: { type: Boolean, default: false, index: true },
|
published: { type: Boolean, default: false, index: true },
|
||||||
likes: [],
|
likes: [],
|
||||||
related: [RelatedPost]
|
related: [RelatedPost],
|
||||||
}, {table: 'posts'});
|
}, { table: 'posts' });
|
||||||
|
|
||||||
function RelatedPost() {
|
function RelatedPost() {
|
||||||
}
|
}
|
||||||
|
|
||||||
RelatedPost.prototype.someMethod = function () {
|
RelatedPost.prototype.someMethod = function() {
|
||||||
return this.parent;
|
return this.parent;
|
||||||
};
|
};
|
||||||
|
|
||||||
Post.validateAsync('title', function (err, done) {
|
Post.validateAsync('title', function(err, done) {
|
||||||
process.nextTick(done);
|
process.nextTick(done);
|
||||||
});
|
});
|
||||||
|
|
||||||
User.hasMany(Post, {as: 'posts', foreignKey: 'userId'});
|
User.hasMany(Post, { as: 'posts', foreignKey: 'userId' });
|
||||||
// creates instance methods:
|
// creates instance methods:
|
||||||
// user.posts(conds)
|
// user.posts(conds)
|
||||||
// user.posts.build(data) // like new Post({userId: user.id});
|
// user.posts.build(data) // like new Post({userId: user.id});
|
||||||
|
@ -164,18 +164,18 @@ function testOrm(dataSource) {
|
||||||
// user.latestPost.build(data)
|
// user.latestPost.build(data)
|
||||||
// user.latestPost.create(data)
|
// user.latestPost.create(data)
|
||||||
|
|
||||||
Post.belongsTo(User, {as: 'author', foreignKey: 'userId'});
|
Post.belongsTo(User, { as: 'author', foreignKey: 'userId' });
|
||||||
// creates instance methods:
|
// creates instance methods:
|
||||||
// post.author(callback) -- getter when called with function
|
// post.author(callback) -- getter when called with function
|
||||||
// post.author() -- sync getter when called without params
|
// post.author() -- sync getter when called without params
|
||||||
// post.author(user) -- setter when called with object
|
// post.author(user) -- setter when called with object
|
||||||
|
|
||||||
Passport = dataSource.define('Passport', {
|
Passport = dataSource.define('Passport', {
|
||||||
number: String
|
number: String,
|
||||||
});
|
});
|
||||||
|
|
||||||
Passport.belongsTo(User, {as: 'owner', foreignKey: 'ownerId'});
|
Passport.belongsTo(User, { as: 'owner', foreignKey: 'ownerId' });
|
||||||
User.hasMany(Passport, {as: 'passports', foreignKey: 'ownerId'});
|
User.hasMany(Passport, { as: 'passports', foreignKey: 'ownerId' });
|
||||||
|
|
||||||
var user = new User;
|
var user = new User;
|
||||||
|
|
||||||
|
@ -188,7 +188,7 @@ function testOrm(dataSource) {
|
||||||
// instance methods
|
// instance methods
|
||||||
test.ok(user.save instanceof Function);
|
test.ok(user.save instanceof Function);
|
||||||
|
|
||||||
dataSource.automigrate(function (err) {
|
dataSource.automigrate(function(err) {
|
||||||
if (err) {
|
if (err) {
|
||||||
console.log('Error while migrating');
|
console.log('Error while migrating');
|
||||||
console.log(err);
|
console.log(err);
|
||||||
|
@ -199,11 +199,11 @@ function testOrm(dataSource) {
|
||||||
|
|
||||||
});
|
});
|
||||||
|
|
||||||
it('should initialize object properly', function (test) {
|
it('should initialize object properly', function(test) {
|
||||||
var hw = 'Hello word',
|
var hw = 'Hello word',
|
||||||
now = Date.now(),
|
now = Date.now(),
|
||||||
post = new Post({title: hw}),
|
post = new Post({ title: hw }),
|
||||||
anotherPost = Post({title: 'Resig style constructor'});
|
anotherPost = Post({ title: 'Resig style constructor' });
|
||||||
|
|
||||||
test.equal(post.title, hw);
|
test.equal(post.title, hw);
|
||||||
test.ok(!post.propertyChanged('title'), 'property changed: title');
|
test.ok(!post.propertyChanged('title'), 'property changed: title');
|
||||||
|
@ -218,31 +218,31 @@ function testOrm(dataSource) {
|
||||||
test.done();
|
test.done();
|
||||||
});
|
});
|
||||||
|
|
||||||
it('should save object', function (test) {
|
it('should save object', function(test) {
|
||||||
var title = 'Initial title', title2 = 'Hello world',
|
var title = 'Initial title', title2 = 'Hello world',
|
||||||
date = new Date;
|
date = new Date;
|
||||||
|
|
||||||
Post.create({
|
Post.create({
|
||||||
title: title,
|
title: title,
|
||||||
date: date
|
date: date,
|
||||||
}, function (err, obj) {
|
}, function(err, obj) {
|
||||||
test.ok(obj.id, 'Object id should present');
|
test.ok(obj.id, 'Object id should present');
|
||||||
test.equals(obj.title, title);
|
test.equals(obj.title, title);
|
||||||
// test.equals(obj.date, date);
|
// test.equals(obj.date, date);
|
||||||
obj.title = title2;
|
obj.title = title2;
|
||||||
test.ok(obj.propertyChanged('title'), 'Title changed');
|
test.ok(obj.propertyChanged('title'), 'Title changed');
|
||||||
obj.save(function (err, obj) {
|
obj.save(function(err, obj) {
|
||||||
test.equal(obj.title, title2);
|
test.equal(obj.title, title2);
|
||||||
test.ok(!obj.propertyChanged('title'));
|
test.ok(!obj.propertyChanged('title'));
|
||||||
|
|
||||||
var p = new Post({title: 1});
|
var p = new Post({ title: 1 });
|
||||||
p.title = 2;
|
p.title = 2;
|
||||||
p.save(function (err, obj) {
|
p.save(function(err, obj) {
|
||||||
test.ok(!p.propertyChanged('title'));
|
test.ok(!p.propertyChanged('title'));
|
||||||
p.title = 3;
|
p.title = 3;
|
||||||
test.ok(p.propertyChanged('title'));
|
test.ok(p.propertyChanged('title'));
|
||||||
test.equal(p.title_was, 2);
|
test.equal(p.title_was, 2);
|
||||||
p.save(function () {
|
p.save(function() {
|
||||||
test.equal(p.title_was, 3);
|
test.equal(p.title_was, 3);
|
||||||
test.ok(!p.propertyChanged('title'));
|
test.ok(!p.propertyChanged('title'));
|
||||||
test.done();
|
test.done();
|
||||||
|
@ -252,18 +252,18 @@ function testOrm(dataSource) {
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
it('should create object with initial data', function (test) {
|
it('should create object with initial data', function(test) {
|
||||||
var title = 'Initial title',
|
var title = 'Initial title',
|
||||||
date = new Date;
|
date = new Date;
|
||||||
|
|
||||||
Post.create({
|
Post.create({
|
||||||
title: title,
|
title: title,
|
||||||
date: date
|
date: date,
|
||||||
}, function (err, obj) {
|
}, function(err, obj) {
|
||||||
test.ok(obj.id);
|
test.ok(obj.id);
|
||||||
test.equals(obj.title, title);
|
test.equals(obj.title, title);
|
||||||
test.equals(obj.date, date);
|
test.equals(obj.date, date);
|
||||||
Post.findById(obj.id, function () {
|
Post.findById(obj.id, function() {
|
||||||
test.equal(obj.title, title);
|
test.equal(obj.title, title);
|
||||||
test.equal(obj.date.toString(), date.toString());
|
test.equal(obj.date.toString(), date.toString());
|
||||||
test.done();
|
test.done();
|
||||||
|
@ -271,13 +271,13 @@ function testOrm(dataSource) {
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
it('should save only dataSource-defined field in database', function (test) {
|
it('should save only dataSource-defined field in database', function(test) {
|
||||||
Post.create({title: '1602', nonSchemaField: 'some value'}, function (err, post) {
|
Post.create({ title: '1602', nonSchemaField: 'some value' }, function(err, post) {
|
||||||
test.ok(!post.nonSchemaField);
|
test.ok(!post.nonSchemaField);
|
||||||
post.a = 1;
|
post.a = 1;
|
||||||
post.save(function () {
|
post.save(function() {
|
||||||
test.ok(post.a);
|
test.ok(post.a);
|
||||||
post.reload(function (err, psto) {
|
post.reload(function(err, psto) {
|
||||||
test.ok(!psto.a);
|
test.ok(!psto.a);
|
||||||
test.done();
|
test.done();
|
||||||
});
|
});
|
||||||
|
@ -301,24 +301,24 @@ function testOrm(dataSource) {
|
||||||
});
|
});
|
||||||
*/
|
*/
|
||||||
|
|
||||||
it('should not re-instantiate object on saving', function (test) {
|
it('should not re-instantiate object on saving', function(test) {
|
||||||
var title = 'Initial title';
|
var title = 'Initial title';
|
||||||
var post = new Post({title: title});
|
var post = new Post({ title: title });
|
||||||
post.save(function (err, savedPost) {
|
post.save(function(err, savedPost) {
|
||||||
test.strictEqual(post, savedPost);
|
test.strictEqual(post, savedPost);
|
||||||
test.done();
|
test.done();
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
it('should destroy object', function (test) {
|
it('should destroy object', function(test) {
|
||||||
Post.create(function (err, post) {
|
Post.create(function(err, post) {
|
||||||
Post.exists(post.id, function (err, exists) {
|
Post.exists(post.id, function(err, exists) {
|
||||||
test.ok(exists, 'Object exists');
|
test.ok(exists, 'Object exists');
|
||||||
post.destroy(function () {
|
post.destroy(function() {
|
||||||
Post.exists(post.id, function (err, exists) {
|
Post.exists(post.id, function(err, exists) {
|
||||||
if (err) console.log(err);
|
if (err) console.log(err);
|
||||||
test.ok(!exists, 'Hey! ORM told me that object exists, but it looks like it doesn\'t. Something went wrong...');
|
test.ok(!exists, 'Hey! ORM told me that object exists, but it looks like it doesn\'t. Something went wrong...');
|
||||||
Post.findById(post.id, function (err, obj) {
|
Post.findById(post.id, function(err, obj) {
|
||||||
test.equal(obj, null, 'Param obj should be null');
|
test.equal(obj, null, 'Param obj should be null');
|
||||||
test.done();
|
test.done();
|
||||||
});
|
});
|
||||||
|
@ -328,10 +328,10 @@ function testOrm(dataSource) {
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
it('should handle virtual attributes', function (test) {
|
it('should handle virtual attributes', function(test) {
|
||||||
var salt = 's0m3s3cr3t5a1t';
|
var salt = 's0m3s3cr3t5a1t';
|
||||||
|
|
||||||
User.setter.passwd = function (password) {
|
User.setter.passwd = function(password) {
|
||||||
this._passwd = calcHash(password, salt);
|
this._passwd = calcHash(password, salt);
|
||||||
};
|
};
|
||||||
|
|
||||||
|
@ -361,15 +361,15 @@ function testOrm(dataSource) {
|
||||||
// });
|
// });
|
||||||
// });
|
// });
|
||||||
|
|
||||||
it('should update single attribute', function (test) {
|
it('should update single attribute', function(test) {
|
||||||
Post.create({title: 'title', content: 'content', published: true}, function (err, post) {
|
Post.create({ title: 'title', content: 'content', published: true }, function(err, post) {
|
||||||
post.content = 'New content';
|
post.content = 'New content';
|
||||||
post.updateAttribute('title', 'New title', function () {
|
post.updateAttribute('title', 'New title', function() {
|
||||||
test.equal(post.title, 'New title');
|
test.equal(post.title, 'New title');
|
||||||
test.ok(!post.propertyChanged('title'));
|
test.ok(!post.propertyChanged('title'));
|
||||||
test.equal(post.content, 'New content', 'dirty state saved');
|
test.equal(post.content, 'New content', 'dirty state saved');
|
||||||
test.ok(post.propertyChanged('content'));
|
test.ok(post.propertyChanged('content'));
|
||||||
post.reload(function (err, post) {
|
post.reload(function(err, post) {
|
||||||
test.equal(post.title, 'New title');
|
test.equal(post.title, 'New title');
|
||||||
test.ok(!post.propertyChanged('title'), 'title not changed');
|
test.ok(!post.propertyChanged('title'), 'title not changed');
|
||||||
test.equal(post.content, 'content', 'real value turned back');
|
test.equal(post.content, 'content', 'real value turned back');
|
||||||
|
@ -381,22 +381,22 @@ function testOrm(dataSource) {
|
||||||
});
|
});
|
||||||
|
|
||||||
var countOfposts, countOfpostsFiltered;
|
var countOfposts, countOfpostsFiltered;
|
||||||
it('should fetch collection', function (test) {
|
it('should fetch collection', function(test) {
|
||||||
Post.all(function (err, posts) {
|
Post.all(function(err, posts) {
|
||||||
countOfposts = posts.length;
|
countOfposts = posts.length;
|
||||||
test.ok(countOfposts > 0);
|
test.ok(countOfposts > 0);
|
||||||
test.ok(posts[0] instanceof Post);
|
test.ok(posts[0] instanceof Post);
|
||||||
countOfpostsFiltered = posts.filter(function (p) {
|
countOfpostsFiltered = posts.filter(function(p) {
|
||||||
return p.title === 'title';
|
return p.title === 'title';
|
||||||
}).length;
|
}).length;
|
||||||
test.done();
|
test.done();
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
it('should find records filtered with multiple attributes', function (test) {
|
it('should find records filtered with multiple attributes', function(test) {
|
||||||
var d = new Date;
|
var d = new Date;
|
||||||
Post.create({title: 'title', content: 'content', published: true, date: d}, function (err, post) {
|
Post.create({ title: 'title', content: 'content', published: true, date: d }, function(err, post) {
|
||||||
Post.all({where: {title: 'title', date: d, published: true}}, function (err, res) {
|
Post.all({ where: { title: 'title', date: d, published: true }}, function(err, res) {
|
||||||
test.equals(res.length, 1, 'Filtering Posts returns one post');
|
test.equals(res.length, 1, 'Filtering Posts returns one post');
|
||||||
test.done();
|
test.done();
|
||||||
});
|
});
|
||||||
|
@ -409,7 +409,7 @@ function testOrm(dataSource) {
|
||||||
dataSource.name !== 'neo4j' &&
|
dataSource.name !== 'neo4j' &&
|
||||||
dataSource.name !== 'cradle'
|
dataSource.name !== 'cradle'
|
||||||
)
|
)
|
||||||
it('relations key is working', function (test) {
|
it('relations key is working', function(test) {
|
||||||
test.ok(User.relations, 'Relations key should be defined');
|
test.ok(User.relations, 'Relations key should be defined');
|
||||||
test.ok(User.relations.posts, 'posts relation should exist on User');
|
test.ok(User.relations.posts, 'posts relation should exist on User');
|
||||||
test.equal(User.relations.posts.type, 'hasMany', 'Type of hasMany relation is hasMany');
|
test.equal(User.relations.posts.type, 'hasMany', 'Type of hasMany relation is hasMany');
|
||||||
|
@ -426,15 +426,15 @@ function testOrm(dataSource) {
|
||||||
test.done();
|
test.done();
|
||||||
});
|
});
|
||||||
|
|
||||||
it('should handle hasMany relationship', function (test) {
|
it('should handle hasMany relationship', function(test) {
|
||||||
User.create(function (err, u) {
|
User.create(function(err, u) {
|
||||||
if (err) return console.log(err);
|
if (err) return console.log(err);
|
||||||
test.ok(u.posts, 'Method defined: posts');
|
test.ok(u.posts, 'Method defined: posts');
|
||||||
test.ok(u.posts.build, 'Method defined: posts.build');
|
test.ok(u.posts.build, 'Method defined: posts.build');
|
||||||
test.ok(u.posts.create, 'Method defined: posts.create');
|
test.ok(u.posts.create, 'Method defined: posts.create');
|
||||||
u.posts.create(function (err, post) {
|
u.posts.create(function(err, post) {
|
||||||
if (err) return console.log(err);
|
if (err) return console.log(err);
|
||||||
u.posts(function (err, posts) {
|
u.posts(function(err, posts) {
|
||||||
test.equal(posts.pop().id.toString(), post.id.toString());
|
test.equal(posts.pop().id.toString(), post.id.toString());
|
||||||
test.done();
|
test.done();
|
||||||
});
|
});
|
||||||
|
@ -442,13 +442,13 @@ function testOrm(dataSource) {
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
it('should navigate variations of belongsTo regardless of column name', function (test) {
|
it('should navigate variations of belongsTo regardless of column name', function(test) {
|
||||||
|
|
||||||
Dog.create({name: 'theDog'}, function (err, obj) {
|
Dog.create({ name: 'theDog' }, function(err, obj) {
|
||||||
test.ok(obj instanceof Dog);
|
test.ok(obj instanceof Dog);
|
||||||
Log.create({name: 'theLog', ownerId: obj.id}, function (err, obj) {
|
Log.create({ name: 'theLog', ownerId: obj.id }, function(err, obj) {
|
||||||
test.ok(obj instanceof Log);
|
test.ok(obj instanceof Log);
|
||||||
obj.owner(function (err, obj) {
|
obj.owner(function(err, obj) {
|
||||||
test.ok(!err, 'Should not have an error.'); // Before cba174b this would be 'Error: Permission denied'
|
test.ok(!err, 'Should not have an error.'); // Before cba174b this would be 'Error: Permission denied'
|
||||||
if (err) {
|
if (err) {
|
||||||
console.log('Found: ' + err);
|
console.log('Found: ' + err);
|
||||||
|
@ -467,11 +467,11 @@ function testOrm(dataSource) {
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
it('hasMany should support additional conditions', function (test) {
|
it('hasMany should support additional conditions', function(test) {
|
||||||
|
|
||||||
User.create(function (e, u) {
|
User.create(function(e, u) {
|
||||||
u.posts.create({}, function (e, p) {
|
u.posts.create({}, function(e, p) {
|
||||||
u.posts({where: {id: p.id}}, function (e, posts) {
|
u.posts({ where: { id: p.id }}, function(e, posts) {
|
||||||
test.equal(posts.length, 1, 'There should be only 1 post.');
|
test.equal(posts.length, 1, 'There should be only 1 post.');
|
||||||
test.done();
|
test.done();
|
||||||
});
|
});
|
||||||
|
@ -480,26 +480,26 @@ function testOrm(dataSource) {
|
||||||
|
|
||||||
});
|
});
|
||||||
|
|
||||||
it('hasMany should be cached', function (test) {
|
it('hasMany should be cached', function(test) {
|
||||||
//User.create(function (e, u) {
|
//User.create(function (e, u) {
|
||||||
// u.posts.create({}, function (e, p) {
|
// u.posts.create({}, function (e, p) {
|
||||||
// find all posts for a user.
|
// find all posts for a user.
|
||||||
// Finding one post with an existing author associated
|
// Finding one post with an existing author associated
|
||||||
Post.all(function (err, posts) {
|
Post.all(function(err, posts) {
|
||||||
// We try to get the first post with a userId != NULL
|
// We try to get the first post with a userId != NULL
|
||||||
for (var i = 0; i < posts.length; i++) {
|
for (var i = 0; i < posts.length; i++) {
|
||||||
var post = posts[i];
|
var post = posts[i];
|
||||||
if (post.userId) {
|
if (post.userId) {
|
||||||
// We could get the user with belongs to relationship but it is better if there is no interactions.
|
// We could get the user with belongs to relationship but it is better if there is no interactions.
|
||||||
User.findById(post.userId, function (err, user) {
|
User.findById(post.userId, function(err, user) {
|
||||||
User.create(function (err, voidUser) {
|
User.create(function(err, voidUser) {
|
||||||
Post.create({userId: user.id}, function () {
|
Post.create({ userId: user.id }, function() {
|
||||||
|
|
||||||
// There can't be any concurrency because we are counting requests
|
// There can't be any concurrency because we are counting requests
|
||||||
// We are first testing cases when user has posts
|
// We are first testing cases when user has posts
|
||||||
user.posts(function (err, data) {
|
user.posts(function(err, data) {
|
||||||
var nbInitialRequests = nbSchemaRequests;
|
var nbInitialRequests = nbSchemaRequests;
|
||||||
user.posts(function (err, data2) {
|
user.posts(function(err, data2) {
|
||||||
test.equal(data.length, 2, 'There should be 2 posts.');
|
test.equal(data.length, 2, 'There should be 2 posts.');
|
||||||
test.equal(data.length, data2.length, 'Posts should be the same, since we are loading on the same object.');
|
test.equal(data.length, data2.length, 'Posts should be the same, since we are loading on the same object.');
|
||||||
requestsAreCounted && test.equal(nbInitialRequests, nbSchemaRequests, 'There should not be any request because value is cached.');
|
requestsAreCounted && test.equal(nbInitialRequests, nbSchemaRequests, 'There should not be any request because value is cached.');
|
||||||
|
@ -507,23 +507,23 @@ function testOrm(dataSource) {
|
||||||
if (dataSource.name === 'mongodb') { // for the moment mongodb doesn\'t support additional conditions on hasMany relations (see above)
|
if (dataSource.name === 'mongodb') { // for the moment mongodb doesn\'t support additional conditions on hasMany relations (see above)
|
||||||
test.done();
|
test.done();
|
||||||
} else {
|
} else {
|
||||||
user.posts({where: {id: data[0].id}}, function (err, data) {
|
user.posts({ where: { id: data[0].id }}, function(err, data) {
|
||||||
test.equal(data.length, 1, 'There should be only one post.');
|
test.equal(data.length, 1, 'There should be only one post.');
|
||||||
requestsAreCounted && test.equal(nbInitialRequests + 1, nbSchemaRequests, 'There should be one additional request since we added conditions.');
|
requestsAreCounted && test.equal(nbInitialRequests + 1, nbSchemaRequests, 'There should be one additional request since we added conditions.');
|
||||||
|
|
||||||
user.posts(function (err, data) {
|
user.posts(function(err, data) {
|
||||||
test.equal(data.length, 2, 'Previous get shouldn\'t have changed cached value though, since there was additional conditions.');
|
test.equal(data.length, 2, 'Previous get shouldn\'t have changed cached value though, since there was additional conditions.');
|
||||||
requestsAreCounted && test.equal(nbInitialRequests + 1, nbSchemaRequests, 'There should not be any request because value is cached.');
|
requestsAreCounted && test.equal(nbInitialRequests + 1, nbSchemaRequests, 'There should not be any request because value is cached.');
|
||||||
|
|
||||||
// We are now testing cases when user doesn't have any post
|
// We are now testing cases when user doesn't have any post
|
||||||
voidUser.posts(function (err, data) {
|
voidUser.posts(function(err, data) {
|
||||||
var nbInitialRequests = nbSchemaRequests;
|
var nbInitialRequests = nbSchemaRequests;
|
||||||
voidUser.posts(function (err, data2) {
|
voidUser.posts(function(err, data2) {
|
||||||
test.equal(data.length, 0, 'There shouldn\'t be any posts (1/2).');
|
test.equal(data.length, 0, 'There shouldn\'t be any posts (1/2).');
|
||||||
test.equal(data2.length, 0, 'There shouldn\'t be any posts (2/2).');
|
test.equal(data2.length, 0, 'There shouldn\'t be any posts (2/2).');
|
||||||
requestsAreCounted && test.equal(nbInitialRequests, nbSchemaRequests, 'There should not be any request because value is cached.');
|
requestsAreCounted && test.equal(nbInitialRequests, nbSchemaRequests, 'There should not be any request because value is cached.');
|
||||||
|
|
||||||
voidUser.posts(true, function (err, data3) {
|
voidUser.posts(true, function(err, data3) {
|
||||||
test.equal(data3.length, 0, 'There shouldn\'t be any posts.');
|
test.equal(data3.length, 0, 'There shouldn\'t be any posts.');
|
||||||
requestsAreCounted && test.equal(nbInitialRequests + 1, nbSchemaRequests, 'There should be one additional request since we forced refresh.');
|
requestsAreCounted && test.equal(nbInitialRequests + 1, nbSchemaRequests, 'There should be one additional request since we forced refresh.');
|
||||||
|
|
||||||
|
@ -555,24 +555,24 @@ function testOrm(dataSource) {
|
||||||
// });
|
// });
|
||||||
// });
|
// });
|
||||||
|
|
||||||
it('should support scopes', function (test) {
|
it('should support scopes', function(test) {
|
||||||
var wait = 2;
|
var wait = 2;
|
||||||
|
|
||||||
test.ok(Post.scope, 'Scope supported');
|
test.ok(Post.scope, 'Scope supported');
|
||||||
Post.scope('published', {where: {published: true}});
|
Post.scope('published', { where: { published: true }});
|
||||||
test.ok(typeof Post.published === 'function');
|
test.ok(typeof Post.published === 'function');
|
||||||
test.ok(Post.published._scope.where.published === true);
|
test.ok(Post.published._scope.where.published === true);
|
||||||
var post = Post.published.build();
|
var post = Post.published.build();
|
||||||
test.ok(post.published, 'Can build');
|
test.ok(post.published, 'Can build');
|
||||||
test.ok(post.isNewRecord());
|
test.ok(post.isNewRecord());
|
||||||
Post.published.create(function (err, psto) {
|
Post.published.create(function(err, psto) {
|
||||||
if (err) return console.log(err);
|
if (err) return console.log(err);
|
||||||
test.ok(psto.published);
|
test.ok(psto.published);
|
||||||
test.ok(!psto.isNewRecord());
|
test.ok(!psto.isNewRecord());
|
||||||
done();
|
done();
|
||||||
});
|
});
|
||||||
|
|
||||||
User.create(function (err, u) {
|
User.create(function(err, u) {
|
||||||
if (err) return console.log(err);
|
if (err) return console.log(err);
|
||||||
test.ok(typeof u.posts.published == 'function');
|
test.ok(typeof u.posts.published == 'function');
|
||||||
test.ok(u.posts.published._scope.where.published);
|
test.ok(u.posts.published._scope.where.published);
|
||||||
|
@ -586,7 +586,7 @@ function testOrm(dataSource) {
|
||||||
};
|
};
|
||||||
});
|
});
|
||||||
|
|
||||||
it('should return type of property', function (test) {
|
it('should return type of property', function(test) {
|
||||||
test.equal(Post.getPropertyType('title'), 'String');
|
test.equal(Post.getPropertyType('title'), 'String');
|
||||||
test.equal(Post.getPropertyType('content'), 'Text');
|
test.equal(Post.getPropertyType('content'), 'Text');
|
||||||
var p = new Post;
|
var p = new Post;
|
||||||
|
@ -595,26 +595,26 @@ function testOrm(dataSource) {
|
||||||
test.done();
|
test.done();
|
||||||
});
|
});
|
||||||
|
|
||||||
it('should handle ORDER clause', function (test) {
|
it('should handle ORDER clause', function(test) {
|
||||||
var titles = [
|
var titles = [
|
||||||
{ title: 'Title A', subject: "B" },
|
{ title: 'Title A', subject: 'B' },
|
||||||
{ title: 'Title Z', subject: "A" },
|
{ title: 'Title Z', subject: 'A' },
|
||||||
{ title: 'Title M', subject: "C" },
|
{ title: 'Title M', subject: 'C' },
|
||||||
{ title: 'Title A', subject: "A" },
|
{ title: 'Title A', subject: 'A' },
|
||||||
{ title: 'Title B', subject: "A" },
|
{ title: 'Title B', subject: 'A' },
|
||||||
{ title: 'Title C', subject: "D" }
|
{ title: 'Title C', subject: 'D' },
|
||||||
];
|
];
|
||||||
var isRedis = Post.dataSource.name === 'redis';
|
var isRedis = Post.dataSource.name === 'redis';
|
||||||
var dates = isRedis ? [ 5, 9, 0, 17, 10, 9 ] : [
|
var dates = isRedis ? [5, 9, 0, 17, 10, 9] : [
|
||||||
new Date(1000 * 5),
|
new Date(1000 * 5),
|
||||||
new Date(1000 * 9),
|
new Date(1000 * 9),
|
||||||
new Date(1000 * 0),
|
new Date(1000 * 0),
|
||||||
new Date(1000 * 17),
|
new Date(1000 * 17),
|
||||||
new Date(1000 * 10),
|
new Date(1000 * 10),
|
||||||
new Date(1000 * 9)
|
new Date(1000 * 9),
|
||||||
];
|
];
|
||||||
titles.forEach(function (t, i) {
|
titles.forEach(function(t, i) {
|
||||||
Post.create({title: t.title, subject: t.subject, date: dates[i]}, done);
|
Post.create({ title: t.title, subject: t.subject, date: dates[i] }, done);
|
||||||
});
|
});
|
||||||
|
|
||||||
var i = 0, tests = 0;
|
var i = 0, tests = 0;
|
||||||
|
@ -643,10 +643,10 @@ function testOrm(dataSource) {
|
||||||
|
|
||||||
function doStringTest() {
|
function doStringTest() {
|
||||||
tests += 1;
|
tests += 1;
|
||||||
Post.all({order: 'title'}, function (err, posts) {
|
Post.all({ order: 'title' }, function(err, posts) {
|
||||||
if (err) console.log(err);
|
if (err) console.log(err);
|
||||||
test.equal(posts.length, 6);
|
test.equal(posts.length, 6);
|
||||||
titles.sort(compare).forEach(function (t, i) {
|
titles.sort(compare).forEach(function(t, i) {
|
||||||
if (posts[i]) test.equal(posts[i].title, t.title);
|
if (posts[i]) test.equal(posts[i].title, t.title);
|
||||||
});
|
});
|
||||||
finished();
|
finished();
|
||||||
|
@ -655,10 +655,10 @@ function testOrm(dataSource) {
|
||||||
|
|
||||||
function doNumberTest() {
|
function doNumberTest() {
|
||||||
tests += 1;
|
tests += 1;
|
||||||
Post.all({order: 'date'}, function (err, posts) {
|
Post.all({ order: 'date' }, function(err, posts) {
|
||||||
if (err) console.log(err);
|
if (err) console.log(err);
|
||||||
test.equal(posts.length, 6);
|
test.equal(posts.length, 6);
|
||||||
dates.sort(numerically).forEach(function (d, i) {
|
dates.sort(numerically).forEach(function(d, i) {
|
||||||
if (posts[i])
|
if (posts[i])
|
||||||
test.equal(posts[i].date.toString(), d.toString(), 'doNumberTest');
|
test.equal(posts[i].date.toString(), d.toString(), 'doNumberTest');
|
||||||
});
|
});
|
||||||
|
@ -668,11 +668,11 @@ function testOrm(dataSource) {
|
||||||
|
|
||||||
function doFilterAndSortTest() {
|
function doFilterAndSortTest() {
|
||||||
tests += 1;
|
tests += 1;
|
||||||
Post.all({where: {date: new Date(1000 * 9)}, order: 'title', limit: 3}, function (err, posts) {
|
Post.all({ where: { date: new Date(1000 * 9) }, order: 'title', limit: 3 }, function(err, posts) {
|
||||||
if (err) console.log(err);
|
if (err) console.log(err);
|
||||||
console.log(posts.length);
|
console.log(posts.length);
|
||||||
test.equal(posts.length, 2, 'Exactly 2 posts returned by query');
|
test.equal(posts.length, 2, 'Exactly 2 posts returned by query');
|
||||||
[ 'Title C', 'Title Z' ].forEach(function (t, i) {
|
['Title C', 'Title Z'].forEach(function(t, i) {
|
||||||
if (posts[i]) {
|
if (posts[i]) {
|
||||||
test.equal(posts[i].title, t, 'doFilterAndSortTest');
|
test.equal(posts[i].title, t, 'doFilterAndSortTest');
|
||||||
}
|
}
|
||||||
|
@ -683,10 +683,10 @@ function testOrm(dataSource) {
|
||||||
|
|
||||||
function doFilterAndSortReverseTest() {
|
function doFilterAndSortReverseTest() {
|
||||||
tests += 1;
|
tests += 1;
|
||||||
Post.all({where: {date: new Date(1000 * 9)}, order: 'title DESC', limit: 3}, function (err, posts) {
|
Post.all({ where: { date: new Date(1000 * 9) }, order: 'title DESC', limit: 3 }, function(err, posts) {
|
||||||
if (err) console.log(err);
|
if (err) console.log(err);
|
||||||
test.equal(posts.length, 2, 'Exactly 2 posts returned by query');
|
test.equal(posts.length, 2, 'Exactly 2 posts returned by query');
|
||||||
[ 'Title Z', 'Title C' ].forEach(function (t, i) {
|
['Title Z', 'Title C'].forEach(function(t, i) {
|
||||||
if (posts[i]) {
|
if (posts[i]) {
|
||||||
test.equal(posts[i].title, t, 'doFilterAndSortReverseTest');
|
test.equal(posts[i].title, t, 'doFilterAndSortReverseTest');
|
||||||
}
|
}
|
||||||
|
@ -697,28 +697,28 @@ function testOrm(dataSource) {
|
||||||
|
|
||||||
function doMultipleSortTest() {
|
function doMultipleSortTest() {
|
||||||
tests += 1;
|
tests += 1;
|
||||||
Post.all({order: "title ASC, subject ASC"}, function (err, posts) {
|
Post.all({ order: 'title ASC, subject ASC' }, function(err, posts) {
|
||||||
if (err) console.log(err);
|
if (err) console.log(err);
|
||||||
test.equal(posts.length, 6);
|
test.equal(posts.length, 6);
|
||||||
test.equal(posts[0].title, "Title A");
|
test.equal(posts[0].title, 'Title A');
|
||||||
test.equal(posts[0].subject, "A");
|
test.equal(posts[0].subject, 'A');
|
||||||
test.equal(posts[1].title, "Title A");
|
test.equal(posts[1].title, 'Title A');
|
||||||
test.equal(posts[1].subject, "B");
|
test.equal(posts[1].subject, 'B');
|
||||||
test.equal(posts[5].title, "Title Z");
|
test.equal(posts[5].title, 'Title Z');
|
||||||
finished();
|
finished();
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
function doMultipleReverseSortTest() {
|
function doMultipleReverseSortTest() {
|
||||||
tests += 1;
|
tests += 1;
|
||||||
Post.all({order: "title ASC, subject DESC"}, function (err, posts) {
|
Post.all({ order: 'title ASC, subject DESC' }, function(err, posts) {
|
||||||
if (err) console.log(err);
|
if (err) console.log(err);
|
||||||
test.equal(posts.length, 6);
|
test.equal(posts.length, 6);
|
||||||
test.equal(posts[0].title, "Title A");
|
test.equal(posts[0].title, 'Title A');
|
||||||
test.equal(posts[0].subject, "B");
|
test.equal(posts[0].subject, 'B');
|
||||||
test.equal(posts[1].title, "Title A");
|
test.equal(posts[1].title, 'Title A');
|
||||||
test.equal(posts[1].subject, "A");
|
test.equal(posts[1].subject, 'A');
|
||||||
test.equal(posts[5].title, "Title Z");
|
test.equal(posts[5].title, 'Title Z');
|
||||||
finished();
|
finished();
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
@ -877,7 +877,7 @@ function testOrm(dataSource) {
|
||||||
// }
|
// }
|
||||||
// });
|
// });
|
||||||
|
|
||||||
it('should handle order clause with direction', function (test) {
|
it('should handle order clause with direction', function(test) {
|
||||||
var wait = 0;
|
var wait = 0;
|
||||||
var emails = [
|
var emails = [
|
||||||
'john@hcompany.com',
|
'john@hcompany.com',
|
||||||
|
@ -886,18 +886,18 @@ function testOrm(dataSource) {
|
||||||
'tin@hcompany.com',
|
'tin@hcompany.com',
|
||||||
'mike@hcompany.com',
|
'mike@hcompany.com',
|
||||||
'susan@hcompany.com',
|
'susan@hcompany.com',
|
||||||
'test@hcompany.com'
|
'test@hcompany.com',
|
||||||
];
|
];
|
||||||
User.destroyAll(function () {
|
User.destroyAll(function() {
|
||||||
emails.forEach(function (email) {
|
emails.forEach(function(email) {
|
||||||
wait += 1;
|
wait += 1;
|
||||||
User.create({email: email, name: 'Nick'}, done);
|
User.create({ email: email, name: 'Nick' }, done);
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
var tests = 2;
|
var tests = 2;
|
||||||
|
|
||||||
function done() {
|
function done() {
|
||||||
process.nextTick(function () {
|
process.nextTick(function() {
|
||||||
if (--wait === 0) {
|
if (--wait === 0) {
|
||||||
doSortTest();
|
doSortTest();
|
||||||
doReverseSortTest();
|
doReverseSortTest();
|
||||||
|
@ -906,9 +906,9 @@ function testOrm(dataSource) {
|
||||||
}
|
}
|
||||||
|
|
||||||
function doSortTest() {
|
function doSortTest() {
|
||||||
User.all({order: 'email ASC', where: {name: 'Nick'}}, function (err, users) {
|
User.all({ order: 'email ASC', where: { name: 'Nick' }}, function(err, users) {
|
||||||
var _emails = emails.sort();
|
var _emails = emails.sort();
|
||||||
users.forEach(function (user, i) {
|
users.forEach(function(user, i) {
|
||||||
test.equal(_emails[i], user.email, 'ASC sorting');
|
test.equal(_emails[i], user.email, 'ASC sorting');
|
||||||
});
|
});
|
||||||
testDone();
|
testDone();
|
||||||
|
@ -916,9 +916,9 @@ function testOrm(dataSource) {
|
||||||
}
|
}
|
||||||
|
|
||||||
function doReverseSortTest() {
|
function doReverseSortTest() {
|
||||||
User.all({order: 'email DESC', where: {name: 'Nick'}}, function (err, users) {
|
User.all({ order: 'email DESC', where: { name: 'Nick' }}, function(err, users) {
|
||||||
var _emails = emails.sort().reverse();
|
var _emails = emails.sort().reverse();
|
||||||
users.forEach(function (user, i) {
|
users.forEach(function(user, i) {
|
||||||
test.equal(_emails[i], user.email, 'DESC sorting');
|
test.equal(_emails[i], user.email, 'DESC sorting');
|
||||||
});
|
});
|
||||||
testDone();
|
testDone();
|
||||||
|
@ -930,12 +930,12 @@ function testOrm(dataSource) {
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
it('should return id in find result even after updateAttributes', function (test) {
|
it('should return id in find result even after updateAttributes', function(test) {
|
||||||
Post.create(function (err, post) {
|
Post.create(function(err, post) {
|
||||||
var id = post.id;
|
var id = post.id;
|
||||||
test.ok(post.published === false);
|
test.ok(post.published === false);
|
||||||
post.updateAttributes({title: 'hey', published: true}, function () {
|
post.updateAttributes({ title: 'hey', published: true }, function() {
|
||||||
Post.find(id, function (err, post) {
|
Post.find(id, function(err, post) {
|
||||||
test.ok(!!post.published, 'Update boolean field');
|
test.ok(!!post.published, 'Update boolean field');
|
||||||
test.ok(post.id);
|
test.ok(post.id);
|
||||||
test.done();
|
test.done();
|
||||||
|
@ -944,8 +944,8 @@ function testOrm(dataSource) {
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
it('should handle belongsTo correctly', function (test) {
|
it('should handle belongsTo correctly', function(test) {
|
||||||
var passport = new Passport({ownerId: 16});
|
var passport = new Passport({ ownerId: 16 });
|
||||||
// sync getter
|
// sync getter
|
||||||
test.equal(passport.owner(), 16);
|
test.equal(passport.owner(), 16);
|
||||||
// sync setter
|
// sync setter
|
||||||
|
@ -954,18 +954,18 @@ function testOrm(dataSource) {
|
||||||
test.done();
|
test.done();
|
||||||
});
|
});
|
||||||
|
|
||||||
it('should query one record', function (test) {
|
it('should query one record', function(test) {
|
||||||
test.expect(4);
|
test.expect(4);
|
||||||
Post.findOne(function (err, post) {
|
Post.findOne(function(err, post) {
|
||||||
test.ok(post && post.id);
|
test.ok(post && post.id);
|
||||||
Post.findOne({ where: { title: 'hey' } }, function (err, post) {
|
Post.findOne({ where: { title: 'hey' }}, function(err, post) {
|
||||||
if (err) {
|
if (err) {
|
||||||
console.log(err);
|
console.log(err);
|
||||||
return test.done();
|
return test.done();
|
||||||
}
|
}
|
||||||
test.equal(post && post.constructor.modelName, 'Post');
|
test.equal(post && post.constructor.modelName, 'Post');
|
||||||
test.equal(post && post.title, 'hey');
|
test.equal(post && post.title, 'hey');
|
||||||
Post.findOne({ where: { title: 'not exists' } }, function (err, post) {
|
Post.findOne({ where: { title: 'not exists' }}, function(err, post) {
|
||||||
test.ok(post === null);
|
test.ok(post === null);
|
||||||
test.done();
|
test.done();
|
||||||
});
|
});
|
||||||
|
@ -1023,13 +1023,13 @@ function testOrm(dataSource) {
|
||||||
// });
|
// });
|
||||||
|
|
||||||
if (dataSource.name !== 'mongoose' && dataSource.name !== 'neo4j')
|
if (dataSource.name !== 'mongoose' && dataSource.name !== 'neo4j')
|
||||||
it('should update or create record', function (test) {
|
it('should update or create record', function(test) {
|
||||||
var newData = {
|
var newData = {
|
||||||
id: 1,
|
id: 1,
|
||||||
title: 'New title (really new)',
|
title: 'New title (really new)',
|
||||||
content: 'Some example content (updated)'
|
content: 'Some example content (updated)',
|
||||||
};
|
};
|
||||||
Post.updateOrCreate(newData, function (err, updatedPost) {
|
Post.updateOrCreate(newData, function(err, updatedPost) {
|
||||||
if (err) throw err;
|
if (err) throw err;
|
||||||
test.ok(updatedPost);
|
test.ok(updatedPost);
|
||||||
if (!updatedPost) throw Error('No post!');
|
if (!updatedPost) throw Error('No post!');
|
||||||
|
@ -1040,7 +1040,7 @@ function testOrm(dataSource) {
|
||||||
test.equal(newData.title, updatedPost.toObject().title);
|
test.equal(newData.title, updatedPost.toObject().title);
|
||||||
test.equal(newData.content, updatedPost.toObject().content);
|
test.equal(newData.content, updatedPost.toObject().content);
|
||||||
|
|
||||||
Post.findById(updatedPost.id, function (err, post) {
|
Post.findById(updatedPost.id, function(err, post) {
|
||||||
if (err) throw err;
|
if (err) throw err;
|
||||||
if (!post) throw Error('No post!');
|
if (!post) throw Error('No post!');
|
||||||
if (dataSource.name !== 'mongodb') {
|
if (dataSource.name !== 'mongodb') {
|
||||||
|
@ -1048,10 +1048,10 @@ function testOrm(dataSource) {
|
||||||
}
|
}
|
||||||
test.equal(newData.title, post.toObject().title);
|
test.equal(newData.title, post.toObject().title);
|
||||||
test.equal(newData.content, post.toObject().content);
|
test.equal(newData.content, post.toObject().content);
|
||||||
Post.updateOrCreate({id: 100001, title: 'hey'}, function (err, post) {
|
Post.updateOrCreate({ id: 100001, title: 'hey' }, function(err, post) {
|
||||||
if (dataSource.name !== 'mongodb') test.equal(post.id, 100001);
|
if (dataSource.name !== 'mongodb') test.equal(post.id, 100001);
|
||||||
test.equal(post.title, 'hey');
|
test.equal(post.title, 'hey');
|
||||||
Post.findById(post.id, function (err, post) {
|
Post.findById(post.id, function(err, post) {
|
||||||
if (!post) throw Error('No post!');
|
if (!post) throw Error('No post!');
|
||||||
test.done();
|
test.done();
|
||||||
});
|
});
|
||||||
|
@ -1060,25 +1060,25 @@ function testOrm(dataSource) {
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
it('should work with custom setters and getters', function (test) {
|
it('should work with custom setters and getters', function(test) {
|
||||||
User.dataSource.defineForeignKey('User', 'passwd');
|
User.dataSource.defineForeignKey('User', 'passwd');
|
||||||
User.setter.passwd = function (pass) {
|
User.setter.passwd = function(pass) {
|
||||||
this._passwd = pass + 'salt';
|
this._passwd = pass + 'salt';
|
||||||
};
|
};
|
||||||
var u = new User({passwd: 'qwerty'});
|
var u = new User({ passwd: 'qwerty' });
|
||||||
test.equal(u.passwd, 'qwertysalt');
|
test.equal(u.passwd, 'qwertysalt');
|
||||||
u.save(function (err, user) {
|
u.save(function(err, user) {
|
||||||
User.findById(user.id, function (err, user) {
|
User.findById(user.id, function(err, user) {
|
||||||
test.ok(user !== u);
|
test.ok(user !== u);
|
||||||
test.equal(user.passwd, 'qwertysalt');
|
test.equal(user.passwd, 'qwertysalt');
|
||||||
User.all({where: {passwd: 'qwertysalt'}}, function (err, users) {
|
User.all({ where: { passwd: 'qwertysalt' }}, function(err, users) {
|
||||||
test.ok(users[0] !== user);
|
test.ok(users[0] !== user);
|
||||||
test.equal(users[0].passwd, 'qwertysalt');
|
test.equal(users[0].passwd, 'qwertysalt');
|
||||||
User.create({passwd: 'asalat'}, function (err, usr) {
|
User.create({ passwd: 'asalat' }, function(err, usr) {
|
||||||
test.equal(usr.passwd, 'asalatsalt');
|
test.equal(usr.passwd, 'asalatsalt');
|
||||||
User.upsert({passwd: 'heyman'}, function (err, us) {
|
User.upsert({ passwd: 'heyman' }, function(err, us) {
|
||||||
test.equal(us.passwd, 'heymansalt');
|
test.equal(us.passwd, 'heymansalt');
|
||||||
User.findById(us.id, function (err, user) {
|
User.findById(us.id, function(err, user) {
|
||||||
test.equal(user.passwd, 'heymansalt');
|
test.equal(user.passwd, 'heymansalt');
|
||||||
test.done();
|
test.done();
|
||||||
});
|
});
|
||||||
|
@ -1089,18 +1089,18 @@ function testOrm(dataSource) {
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
it('should work with typed and untyped nested collections', function (test) {
|
it('should work with typed and untyped nested collections', function(test) {
|
||||||
var post = new Post;
|
var post = new Post;
|
||||||
var like = post.likes.push({foo: 'bar'});
|
var like = post.likes.push({ foo: 'bar' });
|
||||||
test.equal(like.constructor.name, 'ListItem');
|
test.equal(like.constructor.name, 'ListItem');
|
||||||
var related = post.related.push({hello: 'world'});
|
var related = post.related.push({ hello: 'world' });
|
||||||
test.ok(related.someMethod);
|
test.ok(related.someMethod);
|
||||||
post.save(function (err, p) {
|
post.save(function(err, p) {
|
||||||
test.equal(p.likes.nextid, 2);
|
test.equal(p.likes.nextid, 2);
|
||||||
p.likes.push({second: 2});
|
p.likes.push({ second: 2 });
|
||||||
p.likes.push({third: 3});
|
p.likes.push({ third: 3 });
|
||||||
p.save(function (err) {
|
p.save(function(err) {
|
||||||
Post.findById(p.id, function (err, pp) {
|
Post.findById(p.id, function(err, pp) {
|
||||||
test.equal(pp.likes.length, 3);
|
test.equal(pp.likes.length, 3);
|
||||||
test.ok(pp.likes[3].third);
|
test.ok(pp.likes[3].third);
|
||||||
test.ok(pp.likes[2].second);
|
test.ok(pp.likes[2].second);
|
||||||
|
@ -1112,8 +1112,8 @@ function testOrm(dataSource) {
|
||||||
test.equal(pp.likes.length, 1);
|
test.equal(pp.likes.length, 1);
|
||||||
test.ok(!pp.likes[1]);
|
test.ok(!pp.likes[1]);
|
||||||
test.ok(pp.likes[3]);
|
test.ok(pp.likes[3]);
|
||||||
pp.save(function () {
|
pp.save(function() {
|
||||||
Post.findById(p.id, function (err, pp) {
|
Post.findById(p.id, function(err, pp) {
|
||||||
test.equal(pp.likes.length, 1);
|
test.equal(pp.likes.length, 1);
|
||||||
test.ok(!pp.likes[1]);
|
test.ok(!pp.likes[1]);
|
||||||
test.ok(pp.likes[3]);
|
test.ok(pp.likes[3]);
|
||||||
|
@ -1125,13 +1125,13 @@ function testOrm(dataSource) {
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
it('should find or create', function (test) {
|
it('should find or create', function(test) {
|
||||||
var email = 'some email ' + Math.random();
|
var email = 'some email ' + Math.random();
|
||||||
User.findOrCreate({where: {email: email}}, function (err, u, created) {
|
User.findOrCreate({ where: { email: email }}, function(err, u, created) {
|
||||||
test.ok(u);
|
test.ok(u);
|
||||||
test.ok(!u.age);
|
test.ok(!u.age);
|
||||||
test.ok(created);
|
test.ok(created);
|
||||||
User.findOrCreate({where: {email: email}}, {age: 21}, function (err, u2, created) {
|
User.findOrCreate({ where: { email: email }}, { age: 21 }, function(err, u2, created) {
|
||||||
test.equals(u.id.toString(), u2.id.toString(), 'Same user ids');
|
test.equals(u.id.toString(), u2.id.toString(), 'Same user ids');
|
||||||
test.ok(!u2.age);
|
test.ok(!u2.age);
|
||||||
test.ok(!created);
|
test.ok(!created);
|
||||||
|
|
|
@ -8,61 +8,61 @@ var should = require('./init.js');
|
||||||
var async = require('async');
|
var async = require('async');
|
||||||
var db, User, options, filter;
|
var db, User, options, filter;
|
||||||
|
|
||||||
describe('crud-with-options', function () {
|
describe('crud-with-options', function() {
|
||||||
|
|
||||||
before(function (done) {
|
before(function(done) {
|
||||||
db = getSchema();
|
db = getSchema();
|
||||||
User = db.define('User', {
|
User = db.define('User', {
|
||||||
seq: {type: Number, index: true},
|
seq: { type: Number, index: true },
|
||||||
name: {type: String, index: true, sort: true},
|
name: { type: String, index: true, sort: true },
|
||||||
email: {type: String, index: true},
|
email: { type: String, index: true },
|
||||||
birthday: {type: Date, index: true},
|
birthday: { type: Date, index: true },
|
||||||
role: {type: String, index: true},
|
role: { type: String, index: true },
|
||||||
order: {type: Number, index: true, sort: true},
|
order: { type: Number, index: true, sort: true },
|
||||||
vip: {type: Boolean}
|
vip: { type: Boolean },
|
||||||
});
|
});
|
||||||
options = {};
|
options = {};
|
||||||
filter = {fields: ['name', 'id']};
|
filter = { fields: ['name', 'id'] };
|
||||||
|
|
||||||
db.automigrate(['User'], done);
|
db.automigrate(['User'], done);
|
||||||
|
|
||||||
});
|
});
|
||||||
|
|
||||||
describe('findById', function () {
|
describe('findById', function() {
|
||||||
|
|
||||||
before(function (done) {
|
before(function(done) {
|
||||||
User.destroyAll(done);
|
User.destroyAll(done);
|
||||||
});
|
});
|
||||||
|
|
||||||
it('should allow findById(id, options, cb)', function (done) {
|
it('should allow findById(id, options, cb)', function(done) {
|
||||||
User.findById(1, options, function (err, u) {
|
User.findById(1, options, function(err, u) {
|
||||||
should.not.exist(u);
|
should.not.exist(u);
|
||||||
should.not.exist(err);
|
should.not.exist(err);
|
||||||
done();
|
done();
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
it('should allow findById(id, filter, cb)', function (done) {
|
it('should allow findById(id, filter, cb)', function(done) {
|
||||||
User.findById(1, filter, function (err, u) {
|
User.findById(1, filter, function(err, u) {
|
||||||
should.not.exist(u);
|
should.not.exist(u);
|
||||||
should.not.exist(err);
|
should.not.exist(err);
|
||||||
done();
|
done();
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
it('should allow findById(id)', function () {
|
it('should allow findById(id)', function() {
|
||||||
User.findById(1);
|
User.findById(1);
|
||||||
});
|
});
|
||||||
|
|
||||||
it('should allow findById(id, filter)', function () {
|
it('should allow findById(id, filter)', function() {
|
||||||
User.findById(1, filter);
|
User.findById(1, filter);
|
||||||
});
|
});
|
||||||
|
|
||||||
it('should allow findById(id, options)', function () {
|
it('should allow findById(id, options)', function() {
|
||||||
User.findById(1, options);
|
User.findById(1, options);
|
||||||
});
|
});
|
||||||
|
|
||||||
it('should allow findById(id, filter, options)', function () {
|
it('should allow findById(id, filter, options)', function() {
|
||||||
User.findById(1, filter, options);
|
User.findById(1, filter, options);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
@ -72,7 +72,7 @@ describe('crud-with-options', function () {
|
||||||
User.findById(1, '123', function(err, u) {
|
User.findById(1, '123', function(err, u) {
|
||||||
});
|
});
|
||||||
}).should.throw('The filter argument must be an object');
|
}).should.throw('The filter argument must be an object');
|
||||||
done();
|
done();
|
||||||
});
|
});
|
||||||
|
|
||||||
it('should throw when invalid options are provided for findById',
|
it('should throw when invalid options are provided for findById',
|
||||||
|
@ -95,7 +95,7 @@ describe('crud-with-options', function () {
|
||||||
|
|
||||||
it('should allow findById(id, filter, cb) for a matching id',
|
it('should allow findById(id, filter, cb) for a matching id',
|
||||||
function(done) {
|
function(done) {
|
||||||
User.create({name: 'x', email: 'x@y.com'}, function(err, u) {
|
User.create({ name: 'x', email: 'x@y.com' }, function(err, u) {
|
||||||
should.not.exist(err);
|
should.not.exist(err);
|
||||||
should.exist(u.id);
|
should.exist(u.id);
|
||||||
User.findById(u.id, filter, function(err, u) {
|
User.findById(u.id, filter, function(err, u) {
|
||||||
|
@ -111,7 +111,7 @@ describe('crud-with-options', function () {
|
||||||
|
|
||||||
it('should allow findById(id, options, cb) for a matching id',
|
it('should allow findById(id, options, cb) for a matching id',
|
||||||
function(done) {
|
function(done) {
|
||||||
User.create({name: 'y', email: 'y@y.com'}, function(err, u) {
|
User.create({ name: 'y', email: 'y@y.com' }, function(err, u) {
|
||||||
should.not.exist(err);
|
should.not.exist(err);
|
||||||
should.exist(u.id);
|
should.exist(u.id);
|
||||||
User.findById(u.id, options, function(err, u) {
|
User.findById(u.id, options, function(err, u) {
|
||||||
|
@ -127,7 +127,7 @@ describe('crud-with-options', function () {
|
||||||
|
|
||||||
it('should allow findById(id, filter, options, cb) for a matching id',
|
it('should allow findById(id, filter, options, cb) for a matching id',
|
||||||
function(done) {
|
function(done) {
|
||||||
User.create({name: 'z', email: 'z@y.com'}, function(err, u) {
|
User.create({ name: 'z', email: 'z@y.com' }, function(err, u) {
|
||||||
should.not.exist(err);
|
should.not.exist(err);
|
||||||
should.exist(u.id);
|
should.exist(u.id);
|
||||||
User.findById(u.id, filter, options, function(err, u) {
|
User.findById(u.id, filter, options, function(err, u) {
|
||||||
|
@ -143,7 +143,7 @@ describe('crud-with-options', function () {
|
||||||
|
|
||||||
it('should allow promise-style findById',
|
it('should allow promise-style findById',
|
||||||
function(done) {
|
function(done) {
|
||||||
User.create({name: 'w', email: 'w@y.com'}).then(function(u) {
|
User.create({ name: 'w', email: 'w@y.com' }).then(function(u) {
|
||||||
should.exist(u.id);
|
should.exist(u.id);
|
||||||
return User.findById(u.id).then(function(u) {
|
return User.findById(u.id).then(function(u) {
|
||||||
should.exist(u);
|
should.exist(u);
|
||||||
|
@ -189,7 +189,7 @@ describe('crud-with-options', function () {
|
||||||
|
|
||||||
});
|
});
|
||||||
|
|
||||||
describe('findByIds', function () {
|
describe('findByIds', function() {
|
||||||
|
|
||||||
before(function(done) {
|
before(function(done) {
|
||||||
var people = [
|
var people = [
|
||||||
|
@ -198,7 +198,7 @@ describe('crud-with-options', function () {
|
||||||
{ id: 3, name: 'c' },
|
{ id: 3, name: 'c' },
|
||||||
{ id: 4, name: 'd', vip: true },
|
{ id: 4, name: 'd', vip: true },
|
||||||
{ id: 5, name: 'e' },
|
{ id: 5, name: 'e' },
|
||||||
{ id: 6, name: 'f' }
|
{ id: 6, name: 'f' },
|
||||||
];
|
];
|
||||||
// Use automigrate so that serial keys are 1-6
|
// Use automigrate so that serial keys are 1-6
|
||||||
db.automigrate(['User'], function(err) {
|
db.automigrate(['User'], function(err) {
|
||||||
|
@ -208,8 +208,8 @@ describe('crud-with-options', function () {
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
it('should allow findByIds(ids, cb)', function (done) {
|
it('should allow findByIds(ids, cb)', function(done) {
|
||||||
User.findByIds([3, 2, 1], function (err, users) {
|
User.findByIds([3, 2, 1], function(err, users) {
|
||||||
should.exist(users);
|
should.exist(users);
|
||||||
should.not.exist(err);
|
should.not.exist(err);
|
||||||
var names = users.map(function(u) { return u.name; });
|
var names = users.map(function(u) { return u.name; });
|
||||||
|
@ -221,7 +221,7 @@ describe('crud-with-options', function () {
|
||||||
it('should allow findByIds(ids, filter, options, cb)',
|
it('should allow findByIds(ids, filter, options, cb)',
|
||||||
function(done) {
|
function(done) {
|
||||||
User.findByIds([4, 3, 2, 1],
|
User.findByIds([4, 3, 2, 1],
|
||||||
{ where: { vip: true } }, options, function(err, users) {
|
{ where: { vip: true }}, options, function(err, users) {
|
||||||
should.exist(users);
|
should.exist(users);
|
||||||
should.not.exist(err);
|
should.not.exist(err);
|
||||||
var names = users.map(function(u) {
|
var names = users.map(function(u) {
|
||||||
|
@ -234,7 +234,7 @@ describe('crud-with-options', function () {
|
||||||
|
|
||||||
});
|
});
|
||||||
|
|
||||||
describe('find', function () {
|
describe('find', function() {
|
||||||
|
|
||||||
before(seed);
|
before(seed);
|
||||||
|
|
||||||
|
@ -248,7 +248,7 @@ describe('crud-with-options', function () {
|
||||||
});
|
});
|
||||||
|
|
||||||
it('should allow find(filter, cb)', function(done) {
|
it('should allow find(filter, cb)', function(done) {
|
||||||
User.find({limit: 3}, function(err, users) {
|
User.find({ limit: 3 }, function(err, users) {
|
||||||
should.exists(users);
|
should.exists(users);
|
||||||
should.not.exists(err);
|
should.not.exists(err);
|
||||||
users.should.have.lengthOf(3);
|
users.should.have.lengthOf(3);
|
||||||
|
@ -266,15 +266,15 @@ describe('crud-with-options', function () {
|
||||||
});
|
});
|
||||||
|
|
||||||
it('should allow find(filter, options)', function() {
|
it('should allow find(filter, options)', function() {
|
||||||
User.find({limit: 3}, options);
|
User.find({ limit: 3 }, options);
|
||||||
});
|
});
|
||||||
|
|
||||||
it('should allow find(filter)', function() {
|
it('should allow find(filter)', function() {
|
||||||
User.find({limit: 3});
|
User.find({ limit: 3 });
|
||||||
});
|
});
|
||||||
|
|
||||||
it('should skip trailing undefined args', function(done) {
|
it('should skip trailing undefined args', function(done) {
|
||||||
User.find({limit: 3}, function(err, users) {
|
User.find({ limit: 3 }, function(err, users) {
|
||||||
should.exists(users);
|
should.exists(users);
|
||||||
should.not.exists(err);
|
should.not.exists(err);
|
||||||
users.should.have.lengthOf(3);
|
users.should.have.lengthOf(3);
|
||||||
|
@ -292,7 +292,7 @@ describe('crud-with-options', function () {
|
||||||
|
|
||||||
it('should throw on an invalid options arg', function() {
|
it('should throw on an invalid options arg', function() {
|
||||||
(function() {
|
(function() {
|
||||||
User.find({limit: 3}, 'invalid option', function(err, users) {
|
User.find({ limit: 3 }, 'invalid option', function(err, users) {
|
||||||
// noop
|
// noop
|
||||||
});
|
});
|
||||||
}).should.throw('The options argument must be an object');
|
}).should.throw('The options argument must be an object');
|
||||||
|
@ -300,18 +300,18 @@ describe('crud-with-options', function () {
|
||||||
|
|
||||||
it('should throw on an invalid cb arg', function() {
|
it('should throw on an invalid cb arg', function() {
|
||||||
(function() {
|
(function() {
|
||||||
User.find({limit: 3}, {}, 'invalid cb');
|
User.find({ limit: 3 }, {}, 'invalid cb');
|
||||||
}).should.throw('The cb argument must be a function');
|
}).should.throw('The cb argument must be a function');
|
||||||
});
|
});
|
||||||
|
|
||||||
});
|
});
|
||||||
|
|
||||||
describe('count', function () {
|
describe('count', function() {
|
||||||
|
|
||||||
before(seed);
|
before(seed);
|
||||||
|
|
||||||
it('should allow count(cb)', function (done) {
|
it('should allow count(cb)', function(done) {
|
||||||
User.count(function (err, n) {
|
User.count(function(err, n) {
|
||||||
should.not.exist(err);
|
should.not.exist(err);
|
||||||
should.exist(n);
|
should.exist(n);
|
||||||
n.should.equal(6);
|
n.should.equal(6);
|
||||||
|
@ -319,8 +319,8 @@ describe('crud-with-options', function () {
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
it('should allow count(where, cb)', function (done) {
|
it('should allow count(where, cb)', function(done) {
|
||||||
User.count({role: 'lead'}, function (err, n) {
|
User.count({ role: 'lead' }, function(err, n) {
|
||||||
should.not.exist(err);
|
should.not.exist(err);
|
||||||
should.exist(n);
|
should.exist(n);
|
||||||
n.should.equal(2);
|
n.should.equal(2);
|
||||||
|
@ -328,8 +328,8 @@ describe('crud-with-options', function () {
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
it('should allow count(where, options, cb)', function (done) {
|
it('should allow count(where, options, cb)', function(done) {
|
||||||
User.count({role: 'lead'}, options, function (err, n) {
|
User.count({ role: 'lead' }, options, function(err, n) {
|
||||||
should.not.exist(err);
|
should.not.exist(err);
|
||||||
should.exist(n);
|
should.exist(n);
|
||||||
n.should.equal(2);
|
n.should.equal(2);
|
||||||
|
@ -339,13 +339,13 @@ describe('crud-with-options', function () {
|
||||||
|
|
||||||
});
|
});
|
||||||
|
|
||||||
describe('findOne', function () {
|
describe('findOne', function() {
|
||||||
|
|
||||||
before(seed);
|
before(seed);
|
||||||
|
|
||||||
it('should allow findOne(cb)', function (done) {
|
it('should allow findOne(cb)', function(done) {
|
||||||
User.find({order: 'id'}, function (err, users) {
|
User.find({ order: 'id' }, function(err, users) {
|
||||||
User.findOne(function (e, u) {
|
User.findOne(function(e, u) {
|
||||||
should.not.exist(e);
|
should.not.exist(e);
|
||||||
should.exist(u);
|
should.exist(u);
|
||||||
u.id.toString().should.equal(users[0].id.toString());
|
u.id.toString().should.equal(users[0].id.toString());
|
||||||
|
@ -354,8 +354,8 @@ describe('crud-with-options', function () {
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
it('should allow findOne(filter, options, cb)', function (done) {
|
it('should allow findOne(filter, options, cb)', function(done) {
|
||||||
User.findOne({order: 'order'}, options, function (e, u) {
|
User.findOne({ order: 'order' }, options, function(e, u) {
|
||||||
should.not.exist(e);
|
should.not.exist(e);
|
||||||
should.exist(u);
|
should.exist(u);
|
||||||
u.order.should.equal(1);
|
u.order.should.equal(1);
|
||||||
|
@ -364,8 +364,8 @@ describe('crud-with-options', function () {
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
it('should allow findOne(filter, cb)', function (done) {
|
it('should allow findOne(filter, cb)', function(done) {
|
||||||
User.findOne({order: 'order'}, function (e, u) {
|
User.findOne({ order: 'order' }, function(e, u) {
|
||||||
should.not.exist(e);
|
should.not.exist(e);
|
||||||
should.exist(u);
|
should.exist(u);
|
||||||
u.order.should.equal(1);
|
u.order.should.equal(1);
|
||||||
|
@ -374,8 +374,8 @@ describe('crud-with-options', function () {
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
it('should allow trailing undefined args', function (done) {
|
it('should allow trailing undefined args', function(done) {
|
||||||
User.findOne({order: 'order'}, function (e, u) {
|
User.findOne({ order: 'order' }, function(e, u) {
|
||||||
should.not.exist(e);
|
should.not.exist(e);
|
||||||
should.exist(u);
|
should.exist(u);
|
||||||
u.order.should.equal(1);
|
u.order.should.equal(1);
|
||||||
|
@ -386,13 +386,13 @@ describe('crud-with-options', function () {
|
||||||
|
|
||||||
});
|
});
|
||||||
|
|
||||||
describe('exists', function () {
|
describe('exists', function() {
|
||||||
|
|
||||||
before(seed);
|
before(seed);
|
||||||
|
|
||||||
it('should allow exists(id, cb)', function (done) {
|
it('should allow exists(id, cb)', function(done) {
|
||||||
User.findOne(function (e, u) {
|
User.findOne(function(e, u) {
|
||||||
User.exists(u.id, function (err, exists) {
|
User.exists(u.id, function(err, exists) {
|
||||||
should.not.exist(err);
|
should.not.exist(err);
|
||||||
should.exist(exists);
|
should.exist(exists);
|
||||||
exists.should.be.ok;
|
exists.should.be.ok;
|
||||||
|
@ -401,9 +401,9 @@ describe('crud-with-options', function () {
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
it('should allow exists(id, options, cb)', function (done) {
|
it('should allow exists(id, options, cb)', function(done) {
|
||||||
User.destroyAll(function () {
|
User.destroyAll(function() {
|
||||||
User.exists(42, options, function (err, exists) {
|
User.exists(42, options, function(err, exists) {
|
||||||
should.not.exist(err);
|
should.not.exist(err);
|
||||||
exists.should.not.be.ok;
|
exists.should.not.be.ok;
|
||||||
done();
|
done();
|
||||||
|
@ -413,9 +413,9 @@ describe('crud-with-options', function () {
|
||||||
|
|
||||||
});
|
});
|
||||||
|
|
||||||
describe('save', function () {
|
describe('save', function() {
|
||||||
|
|
||||||
it('should allow save(options, cb)', function (done) {
|
it('should allow save(options, cb)', function(done) {
|
||||||
var options = { foo: 'bar' };
|
var options = { foo: 'bar' };
|
||||||
var opts;
|
var opts;
|
||||||
|
|
||||||
|
@ -434,17 +434,17 @@ describe('crud-with-options', function () {
|
||||||
|
|
||||||
});
|
});
|
||||||
|
|
||||||
describe('destroyAll with options', function () {
|
describe('destroyAll with options', function() {
|
||||||
|
|
||||||
beforeEach(seed);
|
beforeEach(seed);
|
||||||
|
|
||||||
it('should allow destroyAll(where, options, cb)', function (done) {
|
it('should allow destroyAll(where, options, cb)', function(done) {
|
||||||
User.destroyAll({name: 'John Lennon'}, options, function (err) {
|
User.destroyAll({ name: 'John Lennon' }, options, function(err) {
|
||||||
should.not.exist(err);
|
should.not.exist(err);
|
||||||
User.find({where: {name: 'John Lennon'}}, function (err, data) {
|
User.find({ where: { name: 'John Lennon' }}, function(err, data) {
|
||||||
should.not.exist(err);
|
should.not.exist(err);
|
||||||
data.length.should.equal(0);
|
data.length.should.equal(0);
|
||||||
User.find({where: {name: 'Paul McCartney'}}, function (err, data) {
|
User.find({ where: { name: 'Paul McCartney' }}, function(err, data) {
|
||||||
should.not.exist(err);
|
should.not.exist(err);
|
||||||
data.length.should.equal(1);
|
data.length.should.equal(1);
|
||||||
done();
|
done();
|
||||||
|
@ -453,13 +453,13 @@ describe('crud-with-options', function () {
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
it('should allow destroyAll(where, cb)', function (done) {
|
it('should allow destroyAll(where, cb)', function(done) {
|
||||||
User.destroyAll({name: 'John Lennon'}, function (err) {
|
User.destroyAll({ name: 'John Lennon' }, function(err) {
|
||||||
should.not.exist(err);
|
should.not.exist(err);
|
||||||
User.find({where: {name: 'John Lennon'}}, function (err, data) {
|
User.find({ where: { name: 'John Lennon' }}, function(err, data) {
|
||||||
should.not.exist(err);
|
should.not.exist(err);
|
||||||
data.length.should.equal(0);
|
data.length.should.equal(0);
|
||||||
User.find({where: {name: 'Paul McCartney'}}, function (err, data) {
|
User.find({ where: { name: 'Paul McCartney' }}, function(err, data) {
|
||||||
should.not.exist(err);
|
should.not.exist(err);
|
||||||
data.length.should.equal(1);
|
data.length.should.equal(1);
|
||||||
done();
|
done();
|
||||||
|
@ -468,13 +468,13 @@ describe('crud-with-options', function () {
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
it('should allow destroyAll(cb)', function (done) {
|
it('should allow destroyAll(cb)', function(done) {
|
||||||
User.destroyAll(function (err) {
|
User.destroyAll(function(err) {
|
||||||
should.not.exist(err);
|
should.not.exist(err);
|
||||||
User.find({where: {name: 'John Lennon'}}, function (err, data) {
|
User.find({ where: { name: 'John Lennon' }}, function(err, data) {
|
||||||
should.not.exist(err);
|
should.not.exist(err);
|
||||||
data.length.should.equal(0);
|
data.length.should.equal(0);
|
||||||
User.find({where: {name: 'Paul McCartney'}}, function (err, data) {
|
User.find({ where: { name: 'Paul McCartney' }}, function(err, data) {
|
||||||
should.not.exist(err);
|
should.not.exist(err);
|
||||||
data.length.should.equal(0);
|
data.length.should.equal(0);
|
||||||
done();
|
done();
|
||||||
|
@ -485,17 +485,17 @@ describe('crud-with-options', function () {
|
||||||
|
|
||||||
});
|
});
|
||||||
|
|
||||||
describe('updateAll ', function () {
|
describe('updateAll ', function() {
|
||||||
|
|
||||||
beforeEach(seed);
|
beforeEach(seed);
|
||||||
|
|
||||||
it('should allow updateAll(where, data, cb)', function (done) {
|
it('should allow updateAll(where, data, cb)', function(done) {
|
||||||
User.update({name: 'John Lennon'}, {name: 'John Smith'}, function (err) {
|
User.update({ name: 'John Lennon' }, { name: 'John Smith' }, function(err) {
|
||||||
should.not.exist(err);
|
should.not.exist(err);
|
||||||
User.find({where: {name: 'John Lennon'}}, function (err, data) {
|
User.find({ where: { name: 'John Lennon' }}, function(err, data) {
|
||||||
should.not.exist(err);
|
should.not.exist(err);
|
||||||
data.length.should.equal(0);
|
data.length.should.equal(0);
|
||||||
User.find({where: {name: 'John Smith'}}, function (err, data) {
|
User.find({ where: { name: 'John Smith' }}, function(err, data) {
|
||||||
should.not.exist(err);
|
should.not.exist(err);
|
||||||
data.length.should.equal(1);
|
data.length.should.equal(1);
|
||||||
done();
|
done();
|
||||||
|
@ -505,13 +505,13 @@ describe('crud-with-options', function () {
|
||||||
});
|
});
|
||||||
|
|
||||||
it('should allow updateAll(where, data, options, cb)', function(done) {
|
it('should allow updateAll(where, data, options, cb)', function(done) {
|
||||||
User.update({name: 'John Lennon'}, {name: 'John Smith'}, options,
|
User.update({ name: 'John Lennon' }, { name: 'John Smith' }, options,
|
||||||
function(err) {
|
function(err) {
|
||||||
should.not.exist(err);
|
should.not.exist(err);
|
||||||
User.find({where: {name: 'John Lennon'}}, function(err, data) {
|
User.find({ where: { name: 'John Lennon' }}, function(err, data) {
|
||||||
should.not.exist(err);
|
should.not.exist(err);
|
||||||
data.length.should.equal(0);
|
data.length.should.equal(0);
|
||||||
User.find({where: {name: 'John Smith'}}, function(err, data) {
|
User.find({ where: { name: 'John Smith' }}, function(err, data) {
|
||||||
should.not.exist(err);
|
should.not.exist(err);
|
||||||
data.length.should.equal(1);
|
data.length.should.equal(1);
|
||||||
done();
|
done();
|
||||||
|
@ -520,12 +520,12 @@ describe('crud-with-options', function () {
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
it('should allow updateAll(data, cb)', function (done) {
|
it('should allow updateAll(data, cb)', function(done) {
|
||||||
User.update({name: 'John Smith'}, function () {
|
User.update({ name: 'John Smith' }, function() {
|
||||||
User.find({where: {name: 'John Lennon'}}, function (err, data) {
|
User.find({ where: { name: 'John Lennon' }}, function(err, data) {
|
||||||
should.not.exist(err);
|
should.not.exist(err);
|
||||||
data.length.should.equal(0);
|
data.length.should.equal(0);
|
||||||
User.find({where: {name: 'John Smith'}}, function (err, data) {
|
User.find({ where: { name: 'John Smith' }}, function(err, data) {
|
||||||
should.not.exist(err);
|
should.not.exist(err);
|
||||||
data.length.should.equal(6);
|
data.length.should.equal(6);
|
||||||
done();
|
done();
|
||||||
|
@ -547,7 +547,7 @@ function seed(done) {
|
||||||
role: 'lead',
|
role: 'lead',
|
||||||
birthday: new Date('1980-12-08'),
|
birthday: new Date('1980-12-08'),
|
||||||
order: 2,
|
order: 2,
|
||||||
vip: true
|
vip: true,
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
seq: 1,
|
seq: 1,
|
||||||
|
@ -556,18 +556,18 @@ function seed(done) {
|
||||||
role: 'lead',
|
role: 'lead',
|
||||||
birthday: new Date('1942-06-18'),
|
birthday: new Date('1942-06-18'),
|
||||||
order: 1,
|
order: 1,
|
||||||
vip: true
|
vip: true,
|
||||||
},
|
},
|
||||||
{seq: 2, name: 'George Harrison', order: 5, vip: false},
|
{ seq: 2, name: 'George Harrison', order: 5, vip: false },
|
||||||
{seq: 3, name: 'Ringo Starr', order: 6, vip: false},
|
{ seq: 3, name: 'Ringo Starr', order: 6, vip: false },
|
||||||
{seq: 4, name: 'Pete Best', order: 4},
|
{ seq: 4, name: 'Pete Best', order: 4 },
|
||||||
{seq: 5, name: 'Stuart Sutcliffe', order: 3, vip: true}
|
{ seq: 5, name: 'Stuart Sutcliffe', order: 3, vip: true },
|
||||||
];
|
];
|
||||||
|
|
||||||
async.series([
|
async.series([
|
||||||
User.destroyAll.bind(User),
|
User.destroyAll.bind(User),
|
||||||
function(cb) {
|
function(cb) {
|
||||||
async.each(beatles, User.create.bind(User), cb);
|
async.each(beatles, User.create.bind(User), cb);
|
||||||
}
|
},
|
||||||
], done);
|
], done);
|
||||||
}
|
}
|
||||||
|
|
|
@ -19,7 +19,7 @@ describe('DataSource', function() {
|
||||||
// this is what LoopBack does
|
// this is what LoopBack does
|
||||||
return new DataSource({
|
return new DataSource({
|
||||||
name: 'dsname',
|
name: 'dsname',
|
||||||
connector: throwingConnector
|
connector: throwingConnector,
|
||||||
});
|
});
|
||||||
}).should.throw(/loopback-connector-throwing/);
|
}).should.throw(/loopback-connector-throwing/);
|
||||||
});
|
});
|
||||||
|
|
|
@ -8,9 +8,9 @@ var should = require('./init.js');
|
||||||
|
|
||||||
var db, Model;
|
var db, Model;
|
||||||
|
|
||||||
describe('datatypes', function () {
|
describe('datatypes', function() {
|
||||||
|
|
||||||
before(function (done) {
|
before(function(done) {
|
||||||
db = getSchema();
|
db = getSchema();
|
||||||
Nested = db.define('Nested', {});
|
Nested = db.define('Nested', {});
|
||||||
|
|
||||||
|
@ -19,45 +19,45 @@ describe('datatypes', function () {
|
||||||
date: Date,
|
date: Date,
|
||||||
num: Number,
|
num: Number,
|
||||||
bool: Boolean,
|
bool: Boolean,
|
||||||
list: {type: [String]},
|
list: { type: [String] },
|
||||||
arr: Array,
|
arr: Array,
|
||||||
nested: Nested
|
nested: Nested,
|
||||||
});
|
});
|
||||||
db.automigrate(['Model'], done);
|
db.automigrate(['Model'], done);
|
||||||
});
|
});
|
||||||
|
|
||||||
it('should return 400 when property of type array is set to string value',
|
it('should return 400 when property of type array is set to string value',
|
||||||
function (done) {
|
function(done) {
|
||||||
var myModel = db.define('myModel', {
|
var myModel = db.define('myModel', {
|
||||||
list: { type: ['object'] }
|
list: { type: ['object'] },
|
||||||
});
|
});
|
||||||
|
|
||||||
(function(){
|
(function() {
|
||||||
myModel.create({ list: 'This string will crash the server' });
|
myModel.create({ list: 'This string will crash the server' });
|
||||||
}).should.throw({ statusCode: 400 });
|
}).should.throw({ statusCode: 400 });
|
||||||
|
|
||||||
done();
|
done();
|
||||||
});
|
});
|
||||||
|
|
||||||
it('should return 400 when property of type array is set to object value',
|
it('should return 400 when property of type array is set to object value',
|
||||||
function (done) {
|
function(done) {
|
||||||
var myModel = db.define('myModel', {
|
var myModel = db.define('myModel', {
|
||||||
list: { type: ['object'] }
|
list: { type: ['object'] },
|
||||||
});
|
});
|
||||||
|
|
||||||
(function(){
|
(function() {
|
||||||
myModel.create({ list: { key: 'This string will crash the server' } });
|
myModel.create({ list: { key: 'This string will crash the server' }});
|
||||||
}).should.throw({ statusCode: 400 });
|
}).should.throw({ statusCode: 400 });
|
||||||
|
|
||||||
done();
|
done();
|
||||||
});
|
});
|
||||||
|
|
||||||
it('should keep types when get read data from db', function (done) {
|
it('should keep types when get read data from db', function(done) {
|
||||||
var d = new Date, id;
|
var d = new Date, id;
|
||||||
|
|
||||||
Model.create({
|
Model.create({
|
||||||
str: 'hello', date: d, num: '3', bool: 1, list: ['test'], arr: [1, 'str']
|
str: 'hello', date: d, num: '3', bool: 1, list: ['test'], arr: [1, 'str'],
|
||||||
}, function (err, m) {
|
}, function(err, m) {
|
||||||
should.not.exists(err);
|
should.not.exists(err);
|
||||||
should.exist(m && m.id);
|
should.exist(m && m.id);
|
||||||
m.str.should.be.type('string');
|
m.str.should.be.type('string');
|
||||||
|
@ -71,7 +71,7 @@ describe('datatypes', function () {
|
||||||
});
|
});
|
||||||
|
|
||||||
function testFind(next) {
|
function testFind(next) {
|
||||||
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.type('string');
|
m.str.should.be.type('string');
|
||||||
|
@ -87,7 +87,7 @@ describe('datatypes', function () {
|
||||||
}
|
}
|
||||||
|
|
||||||
function testAll() {
|
function testAll() {
|
||||||
Model.findOne(function (err, m) {
|
Model.findOne(function(err, m) {
|
||||||
should.not.exist(err);
|
should.not.exist(err);
|
||||||
should.exist(m);
|
should.exist(m);
|
||||||
m.str.should.be.type('string');
|
m.str.should.be.type('string');
|
||||||
|
@ -101,11 +101,11 @@ describe('datatypes', function () {
|
||||||
|
|
||||||
});
|
});
|
||||||
|
|
||||||
it('should respect data types when updating attributes', function (done) {
|
it('should respect data types when updating attributes', function(done) {
|
||||||
var d = new Date, id;
|
var d = new Date, id;
|
||||||
|
|
||||||
Model.create({
|
Model.create({
|
||||||
str: 'hello', date: d, num: '3', bool: 1}, function(err, m) {
|
str: 'hello', date: d, num: '3', bool: 1 }, function(err, m) {
|
||||||
should.not.exist(err);
|
should.not.exist(err);
|
||||||
should.exist(m && m.id);
|
should.exist(m && m.id);
|
||||||
|
|
||||||
|
@ -114,7 +114,7 @@ describe('datatypes', function () {
|
||||||
m.num.should.be.type('number');
|
m.num.should.be.type('number');
|
||||||
m.bool.should.be.type('boolean');
|
m.bool.should.be.type('boolean');
|
||||||
id = m.id;
|
id = m.id;
|
||||||
testDataInDB(function () {
|
testDataInDB(function() {
|
||||||
testUpdate(function() {
|
testUpdate(function() {
|
||||||
testDataInDB(done);
|
testDataInDB(done);
|
||||||
});
|
});
|
||||||
|
@ -127,8 +127,8 @@ describe('datatypes', function () {
|
||||||
|
|
||||||
// update using updateAttributes
|
// update using updateAttributes
|
||||||
m.updateAttributes({
|
m.updateAttributes({
|
||||||
id: m.id, num: '10'
|
id: m.id, num: '10',
|
||||||
}, function (err, m) {
|
}, function(err, m) {
|
||||||
should.not.exist(err);
|
should.not.exist(err);
|
||||||
m.num.should.be.type('number');
|
m.num.should.be.type('number');
|
||||||
done();
|
done();
|
||||||
|
@ -154,18 +154,18 @@ describe('datatypes', function () {
|
||||||
});
|
});
|
||||||
|
|
||||||
it('should not coerce nested objects into ModelConstructor types', function() {
|
it('should not coerce nested objects into ModelConstructor types', function() {
|
||||||
var coerced = Model._coerce({ nested: { foo: 'bar' } });
|
var coerced = Model._coerce({ nested: { foo: 'bar' }});
|
||||||
coerced.nested.constructor.name.should.equal('Object');
|
coerced.nested.constructor.name.should.equal('Object');
|
||||||
});
|
});
|
||||||
|
|
||||||
it('rejects array value converted to NaN for a required property',
|
it('rejects array value converted to NaN for a required property',
|
||||||
function(done) {
|
function(done) {
|
||||||
db = getSchema();
|
db = getSchema();
|
||||||
Model = db.define('RequiredNumber', {
|
Model = db.define('RequiredNumber', {
|
||||||
num: { type: Number, required: true }
|
num: { type: Number, required: true },
|
||||||
});
|
});
|
||||||
db.automigrate(['Model'], function () {
|
db.automigrate(['Model'], function() {
|
||||||
Model.create({ num: [1,2,3] }, function(err, inst) {
|
Model.create({ num: [1, 2, 3] }, function(err, inst) {
|
||||||
should.exist(err);
|
should.exist(err);
|
||||||
err.should.have.property('name').equal('ValidationError');
|
err.should.have.property('name').equal('ValidationError');
|
||||||
done();
|
done();
|
||||||
|
@ -180,10 +180,10 @@ describe('datatypes', function () {
|
||||||
'TestModel',
|
'TestModel',
|
||||||
{
|
{
|
||||||
desc: { type: String, required: false },
|
desc: { type: String, required: false },
|
||||||
stars: { type: Number, required: false }
|
stars: { type: Number, required: false },
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
persistUndefinedAsNull: true
|
persistUndefinedAsNull: true,
|
||||||
});
|
});
|
||||||
|
|
||||||
isStrict = TestModel.definition.settings.strict;
|
isStrict = TestModel.definition.settings.strict;
|
||||||
|
@ -212,7 +212,7 @@ describe('datatypes', function () {
|
||||||
delete EXPECTED.extra;
|
delete EXPECTED.extra;
|
||||||
}
|
}
|
||||||
|
|
||||||
var data ={ desc: undefined, extra: undefined };
|
var data = { desc: undefined, extra: undefined };
|
||||||
TestModel.create(data, function(err, created) {
|
TestModel.create(data, function(err, created) {
|
||||||
if (err) return done(err);
|
if (err) return done(err);
|
||||||
|
|
||||||
|
@ -271,14 +271,14 @@ describe('datatypes', function () {
|
||||||
if (TestModel.dataSource.connector.all.length === 4) {
|
if (TestModel.dataSource.connector.all.length === 4) {
|
||||||
TestModel.dataSource.connector.all(
|
TestModel.dataSource.connector.all(
|
||||||
TestModel.modelName,
|
TestModel.modelName,
|
||||||
{where: {id: created.id}},
|
{ where: { id: created.id }},
|
||||||
{},
|
{},
|
||||||
cb
|
cb
|
||||||
);
|
);
|
||||||
} else {
|
} else {
|
||||||
TestModel.dataSource.connector.all(
|
TestModel.dataSource.connector.all(
|
||||||
TestModel.modelName,
|
TestModel.modelName,
|
||||||
{where: {id: created.id}},
|
{ where: { id: created.id }},
|
||||||
cb
|
cb
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
@ -294,7 +294,7 @@ describe('datatypes', function () {
|
||||||
inst.__data.dx = undefined;
|
inst.__data.dx = undefined;
|
||||||
|
|
||||||
inst.toObject(false).should.have.properties({
|
inst.toObject(false).should.have.properties({
|
||||||
desc: null, stars: null, extra: null, dx: null
|
desc: null, stars: null, extra: null, dx: null,
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
|
@ -18,108 +18,108 @@ var db, Category, Product, Tool, Widget, Thing, Person;
|
||||||
var setupProducts = function(ids, done) {
|
var setupProducts = function(ids, done) {
|
||||||
async.series([
|
async.series([
|
||||||
function(next) {
|
function(next) {
|
||||||
Tool.create({name: 'Tool Z'}, function(err, inst) {
|
Tool.create({ name: 'Tool Z' }, function(err, inst) {
|
||||||
ids.toolZ = inst.id;
|
ids.toolZ = inst.id;
|
||||||
next();
|
next();
|
||||||
});
|
});
|
||||||
},
|
},
|
||||||
function(next) {
|
function(next) {
|
||||||
Widget.create({name: 'Widget Z'}, function(err, inst) {
|
Widget.create({ name: 'Widget Z' }, function(err, inst) {
|
||||||
ids.widgetZ = inst.id;
|
ids.widgetZ = inst.id;
|
||||||
next();
|
next();
|
||||||
});
|
});
|
||||||
},
|
},
|
||||||
function(next) {
|
function(next) {
|
||||||
Tool.create({name: 'Tool A', active: false}, function(err, inst) {
|
Tool.create({ name: 'Tool A', active: false }, function(err, inst) {
|
||||||
ids.toolA = inst.id;
|
ids.toolA = inst.id;
|
||||||
next();
|
next();
|
||||||
});
|
});
|
||||||
},
|
},
|
||||||
function(next) {
|
function(next) {
|
||||||
Widget.create({name: 'Widget A'}, function(err, inst) {
|
Widget.create({ name: 'Widget A' }, function(err, inst) {
|
||||||
ids.widgetA = inst.id;
|
ids.widgetA = inst.id;
|
||||||
next();
|
next();
|
||||||
});
|
});
|
||||||
},
|
},
|
||||||
function(next) {
|
function(next) {
|
||||||
Widget.create({name: 'Widget B', active: false}, function(err, inst) {
|
Widget.create({ name: 'Widget B', active: false }, function(err, inst) {
|
||||||
ids.widgetB = inst.id;
|
ids.widgetB = inst.id;
|
||||||
next();
|
next();
|
||||||
});
|
});
|
||||||
}
|
},
|
||||||
], done);
|
], done);
|
||||||
};
|
};
|
||||||
|
|
||||||
describe('default scope', function () {
|
describe('default scope', function() {
|
||||||
|
|
||||||
before(function (done) {
|
before(function(done) {
|
||||||
db = getSchema();
|
db = getSchema();
|
||||||
|
|
||||||
Category = db.define('Category', {
|
Category = db.define('Category', {
|
||||||
name: String
|
name: String,
|
||||||
});
|
});
|
||||||
|
|
||||||
Product = db.define('Product', {
|
Product = db.define('Product', {
|
||||||
name: String,
|
name: String,
|
||||||
kind: String,
|
kind: String,
|
||||||
description: String,
|
description: String,
|
||||||
active: { type: Boolean, default: true }
|
active: { type: Boolean, default: true },
|
||||||
}, {
|
}, {
|
||||||
scope: { order: 'name' },
|
scope: { order: 'name' },
|
||||||
scopes: { active: { where: { active: true } } }
|
scopes: { active: { where: { active: true }}},
|
||||||
});
|
});
|
||||||
|
|
||||||
Product.lookupModel = function(data) {
|
Product.lookupModel = function(data) {
|
||||||
var m = this.dataSource.models[data.kind];
|
var m = this.dataSource.models[data.kind];
|
||||||
if (m.base === this) return m;
|
if (m.base === this) return m;
|
||||||
return this;
|
return this;
|
||||||
};
|
};
|
||||||
|
|
||||||
Tool = db.define('Tool', Product.definition.properties, {
|
Tool = db.define('Tool', Product.definition.properties, {
|
||||||
base: 'Product',
|
base: 'Product',
|
||||||
scope: { where: { kind: 'Tool' }, order: 'name' },
|
scope: { where: { kind: 'Tool' }, order: 'name' },
|
||||||
scopes: { active: { where: { active: true } } },
|
scopes: { active: { where: { active: true }}},
|
||||||
mongodb: { collection: 'Product' },
|
mongodb: { collection: 'Product' },
|
||||||
memory: { collection: 'Product' }
|
memory: { collection: 'Product' },
|
||||||
});
|
});
|
||||||
|
|
||||||
Widget = db.define('Widget', Product.definition.properties, {
|
Widget = db.define('Widget', Product.definition.properties, {
|
||||||
base: 'Product',
|
base: 'Product',
|
||||||
properties: { kind: 'Widget' },
|
properties: { kind: 'Widget' },
|
||||||
scope: { where: { kind: 'Widget' }, order: 'name' },
|
scope: { where: { kind: 'Widget' }, order: 'name' },
|
||||||
scopes: { active: { where: { active: true } } },
|
scopes: { active: { where: { active: true }}},
|
||||||
mongodb: { collection: 'Product' },
|
mongodb: { collection: 'Product' },
|
||||||
memory: { collection: 'Product' }
|
memory: { collection: 'Product' },
|
||||||
});
|
});
|
||||||
|
|
||||||
Person = db.define('Person', { name: String }, {
|
Person = db.define('Person', { name: String }, {
|
||||||
scope: { include: 'things' }
|
scope: { include: 'things' },
|
||||||
});
|
});
|
||||||
|
|
||||||
// inst is only valid for instance methods
|
// inst is only valid for instance methods
|
||||||
// like save, updateAttributes
|
// like save, updateAttributes
|
||||||
|
|
||||||
var scopeFn = function(target, inst) {
|
var scopeFn = function(target, inst) {
|
||||||
return { where: { kind: this.modelName } };
|
return { where: { kind: this.modelName }};
|
||||||
};
|
};
|
||||||
|
|
||||||
var propertiesFn = function(target, inst) {
|
var propertiesFn = function(target, inst) {
|
||||||
return { kind: this.modelName };
|
return { kind: this.modelName };
|
||||||
};
|
};
|
||||||
|
|
||||||
Thing = db.define('Thing', Product.definition.properties, {
|
Thing = db.define('Thing', Product.definition.properties, {
|
||||||
base: 'Product',
|
base: 'Product',
|
||||||
attributes: propertiesFn,
|
attributes: propertiesFn,
|
||||||
scope: scopeFn,
|
scope: scopeFn,
|
||||||
mongodb: { collection: 'Product' },
|
mongodb: { collection: 'Product' },
|
||||||
memory: { collection: 'Product' }
|
memory: { collection: 'Product' },
|
||||||
});
|
});
|
||||||
|
|
||||||
Category.hasMany(Product);
|
Category.hasMany(Product);
|
||||||
Category.hasMany(Tool, {scope: {order: 'name DESC'}});
|
Category.hasMany(Tool, { scope: { order: 'name DESC' }});
|
||||||
Category.hasMany(Widget);
|
Category.hasMany(Widget);
|
||||||
Category.hasMany(Thing);
|
Category.hasMany(Thing);
|
||||||
|
|
||||||
Product.belongsTo(Category);
|
Product.belongsTo(Category);
|
||||||
Tool.belongsTo(Category);
|
Tool.belongsTo(Category);
|
||||||
Widget.belongsTo(Category);
|
Widget.belongsTo(Category);
|
||||||
|
@ -127,31 +127,31 @@ describe('default scope', function () {
|
||||||
|
|
||||||
Person.hasMany(Thing);
|
Person.hasMany(Thing);
|
||||||
Thing.belongsTo(Person);
|
Thing.belongsTo(Person);
|
||||||
|
|
||||||
db.automigrate(done);
|
db.automigrate(done);
|
||||||
});
|
});
|
||||||
|
|
||||||
describe('manipulation', function() {
|
describe('manipulation', function() {
|
||||||
|
|
||||||
var ids = {};
|
var ids = {};
|
||||||
|
|
||||||
before(function(done) {
|
before(function(done) {
|
||||||
db.automigrate(done);
|
db.automigrate(done);
|
||||||
});
|
});
|
||||||
|
|
||||||
it('should return a scoped instance', function() {
|
it('should return a scoped instance', function() {
|
||||||
var p = new Tool({name: 'Product A', kind:'ignored'});
|
var p = new Tool({ name: 'Product A', kind:'ignored' });
|
||||||
p.name.should.equal('Product A');
|
p.name.should.equal('Product A');
|
||||||
p.kind.should.equal('Tool');
|
p.kind.should.equal('Tool');
|
||||||
p.setAttributes({ kind: 'ignored' });
|
p.setAttributes({ kind: 'ignored' });
|
||||||
p.kind.should.equal('Tool');
|
p.kind.should.equal('Tool');
|
||||||
|
|
||||||
p.setAttribute('kind', 'other'); // currently not enforced
|
p.setAttribute('kind', 'other'); // currently not enforced
|
||||||
p.kind.should.equal('other');
|
p.kind.should.equal('other');
|
||||||
});
|
});
|
||||||
|
|
||||||
it('should create a scoped instance - tool', function(done) {
|
it('should create a scoped instance - tool', function(done) {
|
||||||
Tool.create({name: 'Product A', kind: 'ignored'}, function(err, p) {
|
Tool.create({ name: 'Product A', kind: 'ignored' }, function(err, p) {
|
||||||
should.not.exist(err);
|
should.not.exist(err);
|
||||||
p.name.should.equal('Product A');
|
p.name.should.equal('Product A');
|
||||||
p.kind.should.equal('Tool');
|
p.kind.should.equal('Tool');
|
||||||
|
@ -159,9 +159,9 @@ describe('default scope', function () {
|
||||||
done();
|
done();
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
it('should create a scoped instance - widget', function(done) {
|
it('should create a scoped instance - widget', function(done) {
|
||||||
Widget.create({name: 'Product B', kind: 'ignored'}, function(err, p) {
|
Widget.create({ name: 'Product B', kind: 'ignored' }, function(err, p) {
|
||||||
should.not.exist(err);
|
should.not.exist(err);
|
||||||
p.name.should.equal('Product B');
|
p.name.should.equal('Product B');
|
||||||
p.kind.should.equal('Widget');
|
p.kind.should.equal('Widget');
|
||||||
|
@ -169,10 +169,10 @@ describe('default scope', function () {
|
||||||
done();
|
done();
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
it('should update a scoped instance - updateAttributes', function(done) {
|
it('should update a scoped instance - updateAttributes', function(done) {
|
||||||
Tool.findById(ids.productA, function(err, p) {
|
Tool.findById(ids.productA, function(err, p) {
|
||||||
p.updateAttributes({description: 'A thing...', kind: 'ingored'}, function(err, inst) {
|
p.updateAttributes({ description: 'A thing...', kind: 'ingored' }, function(err, inst) {
|
||||||
should.not.exist(err);
|
should.not.exist(err);
|
||||||
p.name.should.equal('Product A');
|
p.name.should.equal('Product A');
|
||||||
p.kind.should.equal('Tool');
|
p.kind.should.equal('Tool');
|
||||||
|
@ -181,7 +181,7 @@ describe('default scope', function () {
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
it('should update a scoped instance - save', function(done) {
|
it('should update a scoped instance - save', function(done) {
|
||||||
Tool.findById(ids.productA, function(err, p) {
|
Tool.findById(ids.productA, function(err, p) {
|
||||||
p.description = 'Something...';
|
p.description = 'Something...';
|
||||||
|
@ -198,28 +198,28 @@ describe('default scope', function () {
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
it('should update a scoped instance - updateOrCreate', function(done) {
|
it('should update a scoped instance - updateOrCreate', function(done) {
|
||||||
var data = {id: ids.productA, description: 'Anything...', kind: 'ingored'};
|
var data = { id: ids.productA, description: 'Anything...', kind: 'ingored' };
|
||||||
Tool.updateOrCreate(data, function(err, p) {
|
Tool.updateOrCreate(data, function(err, p) {
|
||||||
should.not.exist(err);
|
should.not.exist(err);
|
||||||
p.name.should.equal('Product A');
|
p.name.should.equal('Product A');
|
||||||
p.kind.should.equal('Tool');
|
p.kind.should.equal('Tool');
|
||||||
p.description.should.equal('Anything...');
|
p.description.should.equal('Anything...');
|
||||||
done();
|
done();
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
});
|
});
|
||||||
|
|
||||||
describe('findById', function() {
|
describe('findById', function() {
|
||||||
|
|
||||||
var ids = {};
|
var ids = {};
|
||||||
|
|
||||||
before(function (done) {
|
before(function(done) {
|
||||||
db.automigrate(setupProducts.bind(null, ids, done));
|
db.automigrate(setupProducts.bind(null, ids, done));
|
||||||
});
|
});
|
||||||
|
|
||||||
it('should apply default scope', function(done) {
|
it('should apply default scope', function(done) {
|
||||||
Product.findById(ids.toolA, function(err, inst) {
|
Product.findById(ids.toolA, function(err, inst) {
|
||||||
should.not.exist(err);
|
should.not.exist(err);
|
||||||
|
@ -228,7 +228,7 @@ describe('default scope', function () {
|
||||||
done();
|
done();
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
it('should apply default scope - tool', function(done) {
|
it('should apply default scope - tool', function(done) {
|
||||||
Tool.findById(ids.toolA, function(err, inst) {
|
Tool.findById(ids.toolA, function(err, inst) {
|
||||||
should.not.exist(err);
|
should.not.exist(err);
|
||||||
|
@ -236,7 +236,7 @@ describe('default scope', function () {
|
||||||
done();
|
done();
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
it('should apply default scope (no match)', function(done) {
|
it('should apply default scope (no match)', function(done) {
|
||||||
Widget.findById(ids.toolA, function(err, inst) {
|
Widget.findById(ids.toolA, function(err, inst) {
|
||||||
should.not.exist(err);
|
should.not.exist(err);
|
||||||
|
@ -244,17 +244,17 @@ describe('default scope', function () {
|
||||||
done();
|
done();
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
});
|
});
|
||||||
|
|
||||||
describe('find', function() {
|
describe('find', function() {
|
||||||
|
|
||||||
var ids = {};
|
var ids = {};
|
||||||
|
|
||||||
before(function (done) {
|
before(function(done) {
|
||||||
db.automigrate(setupProducts.bind(null, ids, done));
|
db.automigrate(setupProducts.bind(null, ids, done));
|
||||||
});
|
});
|
||||||
|
|
||||||
it('should apply default scope - order', function(done) {
|
it('should apply default scope - order', function(done) {
|
||||||
Product.find(function(err, products) {
|
Product.find(function(err, products) {
|
||||||
should.not.exist(err);
|
should.not.exist(err);
|
||||||
|
@ -264,17 +264,17 @@ describe('default scope', function () {
|
||||||
products[2].name.should.equal('Widget A');
|
products[2].name.should.equal('Widget A');
|
||||||
products[3].name.should.equal('Widget B');
|
products[3].name.should.equal('Widget B');
|
||||||
products[4].name.should.equal('Widget Z');
|
products[4].name.should.equal('Widget Z');
|
||||||
|
|
||||||
products[0].should.be.instanceof(Product);
|
products[0].should.be.instanceof(Product);
|
||||||
products[0].should.be.instanceof(Tool);
|
products[0].should.be.instanceof(Tool);
|
||||||
|
|
||||||
products[2].should.be.instanceof(Product);
|
products[2].should.be.instanceof(Product);
|
||||||
products[2].should.be.instanceof(Widget);
|
products[2].should.be.instanceof(Widget);
|
||||||
|
|
||||||
done();
|
done();
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
it('should apply default scope - order override', function(done) {
|
it('should apply default scope - order override', function(done) {
|
||||||
Product.find({ order: 'name DESC' }, function(err, products) {
|
Product.find({ order: 'name DESC' }, function(err, products) {
|
||||||
should.not.exist(err);
|
should.not.exist(err);
|
||||||
|
@ -287,7 +287,7 @@ describe('default scope', function () {
|
||||||
done();
|
done();
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
it('should apply default scope - tool', function(done) {
|
it('should apply default scope - tool', function(done) {
|
||||||
Tool.find(function(err, products) {
|
Tool.find(function(err, products) {
|
||||||
should.not.exist(err);
|
should.not.exist(err);
|
||||||
|
@ -297,9 +297,9 @@ describe('default scope', function () {
|
||||||
done();
|
done();
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
it('should apply default scope - where (widget)', function(done) {
|
it('should apply default scope - where (widget)', function(done) {
|
||||||
Widget.find({ where: { active: true } }, function(err, products) {
|
Widget.find({ where: { active: true }}, function(err, products) {
|
||||||
should.not.exist(err);
|
should.not.exist(err);
|
||||||
products.should.have.length(2);
|
products.should.have.length(2);
|
||||||
products[0].name.should.equal('Widget A');
|
products[0].name.should.equal('Widget A');
|
||||||
|
@ -307,7 +307,7 @@ describe('default scope', function () {
|
||||||
done();
|
done();
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
it('should apply default scope - order (widget)', function(done) {
|
it('should apply default scope - order (widget)', function(done) {
|
||||||
Widget.find({ order: 'name DESC' }, function(err, products) {
|
Widget.find({ order: 'name DESC' }, function(err, products) {
|
||||||
should.not.exist(err);
|
should.not.exist(err);
|
||||||
|
@ -318,17 +318,17 @@ describe('default scope', function () {
|
||||||
done();
|
done();
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
});
|
});
|
||||||
|
|
||||||
describe('exists', function() {
|
describe('exists', function() {
|
||||||
|
|
||||||
var ids = {};
|
var ids = {};
|
||||||
|
|
||||||
before(function (done) {
|
before(function(done) {
|
||||||
db.automigrate(setupProducts.bind(null, ids, done));
|
db.automigrate(setupProducts.bind(null, ids, done));
|
||||||
});
|
});
|
||||||
|
|
||||||
it('should apply default scope', function(done) {
|
it('should apply default scope', function(done) {
|
||||||
Product.exists(ids.widgetA, function(err, exists) {
|
Product.exists(ids.widgetA, function(err, exists) {
|
||||||
should.not.exist(err);
|
should.not.exist(err);
|
||||||
|
@ -336,7 +336,7 @@ describe('default scope', function () {
|
||||||
done();
|
done();
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
it('should apply default scope - tool', function(done) {
|
it('should apply default scope - tool', function(done) {
|
||||||
Tool.exists(ids.toolZ, function(err, exists) {
|
Tool.exists(ids.toolZ, function(err, exists) {
|
||||||
should.not.exist(err);
|
should.not.exist(err);
|
||||||
|
@ -344,7 +344,7 @@ describe('default scope', function () {
|
||||||
done();
|
done();
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
it('should apply default scope - widget', function(done) {
|
it('should apply default scope - widget', function(done) {
|
||||||
Widget.exists(ids.widgetA, function(err, exists) {
|
Widget.exists(ids.widgetA, function(err, exists) {
|
||||||
should.not.exist(err);
|
should.not.exist(err);
|
||||||
|
@ -352,7 +352,7 @@ describe('default scope', function () {
|
||||||
done();
|
done();
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
it('should apply default scope - tool (no match)', function(done) {
|
it('should apply default scope - tool (no match)', function(done) {
|
||||||
Tool.exists(ids.widgetA, function(err, exists) {
|
Tool.exists(ids.widgetA, function(err, exists) {
|
||||||
should.not.exist(err);
|
should.not.exist(err);
|
||||||
|
@ -360,7 +360,7 @@ describe('default scope', function () {
|
||||||
done();
|
done();
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
it('should apply default scope - widget (no match)', function(done) {
|
it('should apply default scope - widget (no match)', function(done) {
|
||||||
Widget.exists(ids.toolZ, function(err, exists) {
|
Widget.exists(ids.toolZ, function(err, exists) {
|
||||||
should.not.exist(err);
|
should.not.exist(err);
|
||||||
|
@ -368,17 +368,17 @@ describe('default scope', function () {
|
||||||
done();
|
done();
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
});
|
});
|
||||||
|
|
||||||
describe('count', function() {
|
describe('count', function() {
|
||||||
|
|
||||||
var ids = {};
|
var ids = {};
|
||||||
|
|
||||||
before(function (done) {
|
before(function(done) {
|
||||||
db.automigrate(setupProducts.bind(null, ids, done));
|
db.automigrate(setupProducts.bind(null, ids, done));
|
||||||
});
|
});
|
||||||
|
|
||||||
it('should apply default scope - order', function(done) {
|
it('should apply default scope - order', function(done) {
|
||||||
Product.count(function(err, count) {
|
Product.count(function(err, count) {
|
||||||
should.not.exist(err);
|
should.not.exist(err);
|
||||||
|
@ -386,7 +386,7 @@ describe('default scope', function () {
|
||||||
done();
|
done();
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
it('should apply default scope - tool', function(done) {
|
it('should apply default scope - tool', function(done) {
|
||||||
Tool.count(function(err, count) {
|
Tool.count(function(err, count) {
|
||||||
should.not.exist(err);
|
should.not.exist(err);
|
||||||
|
@ -394,7 +394,7 @@ describe('default scope', function () {
|
||||||
done();
|
done();
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
it('should apply default scope - widget', function(done) {
|
it('should apply default scope - widget', function(done) {
|
||||||
Widget.count(function(err, count) {
|
Widget.count(function(err, count) {
|
||||||
should.not.exist(err);
|
should.not.exist(err);
|
||||||
|
@ -402,29 +402,29 @@ describe('default scope', function () {
|
||||||
done();
|
done();
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
it('should apply default scope - where', function(done) {
|
it('should apply default scope - where', function(done) {
|
||||||
Widget.count({name: 'Widget Z'}, function(err, count) {
|
Widget.count({ name: 'Widget Z' }, function(err, count) {
|
||||||
should.not.exist(err);
|
should.not.exist(err);
|
||||||
count.should.equal(1);
|
count.should.equal(1);
|
||||||
done();
|
done();
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
it('should apply default scope - no match', function(done) {
|
it('should apply default scope - no match', function(done) {
|
||||||
Tool.count({name: 'Widget Z'}, function(err, count) {
|
Tool.count({ name: 'Widget Z' }, function(err, count) {
|
||||||
should.not.exist(err);
|
should.not.exist(err);
|
||||||
count.should.equal(0);
|
count.should.equal(0);
|
||||||
done();
|
done();
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
});
|
});
|
||||||
|
|
||||||
describe('removeById', function() {
|
describe('removeById', function() {
|
||||||
|
|
||||||
var ids = {};
|
var ids = {};
|
||||||
|
|
||||||
function isDeleted(id, done) {
|
function isDeleted(id, done) {
|
||||||
Product.exists(id, function(err, exists) {
|
Product.exists(id, function(err, exists) {
|
||||||
should.not.exist(err);
|
should.not.exist(err);
|
||||||
|
@ -432,25 +432,25 @@ describe('default scope', function () {
|
||||||
done();
|
done();
|
||||||
});
|
});
|
||||||
};
|
};
|
||||||
|
|
||||||
before(function (done) {
|
before(function(done) {
|
||||||
db.automigrate(setupProducts.bind(null, ids, done));
|
db.automigrate(setupProducts.bind(null, ids, done));
|
||||||
});
|
});
|
||||||
|
|
||||||
it('should apply default scope', function(done) {
|
it('should apply default scope', function(done) {
|
||||||
Product.removeById(ids.widgetZ, function(err) {
|
Product.removeById(ids.widgetZ, function(err) {
|
||||||
should.not.exist(err);
|
should.not.exist(err);
|
||||||
isDeleted(ids.widgetZ, done);
|
isDeleted(ids.widgetZ, done);
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
it('should apply default scope - tool', function(done) {
|
it('should apply default scope - tool', function(done) {
|
||||||
Tool.removeById(ids.toolA, function(err) {
|
Tool.removeById(ids.toolA, function(err) {
|
||||||
should.not.exist(err);
|
should.not.exist(err);
|
||||||
isDeleted(ids.toolA, done);
|
isDeleted(ids.toolA, done);
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
it('should apply default scope - no match', function(done) {
|
it('should apply default scope - no match', function(done) {
|
||||||
Tool.removeById(ids.widgetA, function(err) {
|
Tool.removeById(ids.widgetA, function(err) {
|
||||||
should.not.exist(err);
|
should.not.exist(err);
|
||||||
|
@ -461,14 +461,14 @@ describe('default scope', function () {
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
it('should apply default scope - widget', function(done) {
|
it('should apply default scope - widget', function(done) {
|
||||||
Widget.removeById(ids.widgetA, function(err) {
|
Widget.removeById(ids.widgetA, function(err) {
|
||||||
should.not.exist(err);
|
should.not.exist(err);
|
||||||
isDeleted(ids.widgetA, done);
|
isDeleted(ids.widgetA, done);
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
it('should apply default scope - verify', function(done) {
|
it('should apply default scope - verify', function(done) {
|
||||||
Product.find(function(err, products) {
|
Product.find(function(err, products) {
|
||||||
should.not.exist(err);
|
should.not.exist(err);
|
||||||
|
@ -478,21 +478,21 @@ describe('default scope', function () {
|
||||||
done();
|
done();
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
});
|
});
|
||||||
|
|
||||||
describe('update', function() {
|
describe('update', function() {
|
||||||
|
|
||||||
var ids = {};
|
var ids = {};
|
||||||
|
|
||||||
before(function (done) {
|
before(function(done) {
|
||||||
db.automigrate(setupProducts.bind(null, ids, done));
|
db.automigrate(setupProducts.bind(null, ids, done));
|
||||||
});
|
});
|
||||||
|
|
||||||
it('should apply default scope', function(done) {
|
it('should apply default scope', function(done) {
|
||||||
Widget.update({active: false},{active: true, kind: 'ignored'}, function(err) {
|
Widget.update({ active: false }, { active: true, kind: 'ignored' }, function(err) {
|
||||||
should.not.exist(err);
|
should.not.exist(err);
|
||||||
Widget.find({where: { active: true }}, function(err, products) {
|
Widget.find({ where: { active: true }}, function(err, products) {
|
||||||
should.not.exist(err);
|
should.not.exist(err);
|
||||||
products.should.have.length(3);
|
products.should.have.length(3);
|
||||||
products[0].name.should.equal('Widget A');
|
products[0].name.should.equal('Widget A');
|
||||||
|
@ -502,9 +502,9 @@ describe('default scope', function () {
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
it('should apply default scope - no match', function(done) {
|
it('should apply default scope - no match', function(done) {
|
||||||
Tool.update({name: 'Widget A'},{name: 'Ignored'}, function(err) {
|
Tool.update({ name: 'Widget A' }, { name: 'Ignored' }, function(err) {
|
||||||
should.not.exist(err);
|
should.not.exist(err);
|
||||||
Product.findById(ids.widgetA, function(err, product) {
|
Product.findById(ids.widgetA, function(err, product) {
|
||||||
should.not.exist(err);
|
should.not.exist(err);
|
||||||
|
@ -513,9 +513,9 @@ describe('default scope', function () {
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
it('should have updated within scope', function(done) {
|
it('should have updated within scope', function(done) {
|
||||||
Product.find({where: {active: true}}, function(err, products) {
|
Product.find({ where: { active: true }}, function(err, products) {
|
||||||
should.not.exist(err);
|
should.not.exist(err);
|
||||||
products.should.have.length(4);
|
products.should.have.length(4);
|
||||||
products[0].name.should.equal('Tool Z');
|
products[0].name.should.equal('Tool Z');
|
||||||
|
@ -525,19 +525,19 @@ describe('default scope', function () {
|
||||||
done();
|
done();
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
});
|
});
|
||||||
|
|
||||||
describe('remove', function() {
|
describe('remove', function() {
|
||||||
|
|
||||||
var ids = {};
|
var ids = {};
|
||||||
|
|
||||||
before(function (done) {
|
before(function(done) {
|
||||||
db.automigrate(setupProducts.bind(null, ids, done));
|
db.automigrate(setupProducts.bind(null, ids, done));
|
||||||
});
|
});
|
||||||
|
|
||||||
it('should apply default scope - custom where', function(done) {
|
it('should apply default scope - custom where', function(done) {
|
||||||
Widget.remove({name: 'Widget A'}, function(err) {
|
Widget.remove({ name: 'Widget A' }, function(err) {
|
||||||
should.not.exist(err);
|
should.not.exist(err);
|
||||||
Product.find(function(err, products) {
|
Product.find(function(err, products) {
|
||||||
products.should.have.length(4);
|
products.should.have.length(4);
|
||||||
|
@ -549,9 +549,9 @@ describe('default scope', function () {
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
it('should apply default scope - custom where (no match)', function(done) {
|
it('should apply default scope - custom where (no match)', function(done) {
|
||||||
Tool.remove({name: 'Widget Z'}, function(err) {
|
Tool.remove({ name: 'Widget Z' }, function(err) {
|
||||||
should.not.exist(err);
|
should.not.exist(err);
|
||||||
Product.find(function(err, products) {
|
Product.find(function(err, products) {
|
||||||
products.should.have.length(4);
|
products.should.have.length(4);
|
||||||
|
@ -563,7 +563,7 @@ describe('default scope', function () {
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
it('should apply default scope - deleteAll', function(done) {
|
it('should apply default scope - deleteAll', function(done) {
|
||||||
Tool.deleteAll(function(err) {
|
Tool.deleteAll(function(err) {
|
||||||
should.not.exist(err);
|
should.not.exist(err);
|
||||||
|
@ -575,9 +575,9 @@ describe('default scope', function () {
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
it('should create a scoped instance - tool', function(done) {
|
it('should create a scoped instance - tool', function(done) {
|
||||||
Tool.create({name: 'Tool B'}, function(err, p) {
|
Tool.create({ name: 'Tool B' }, function(err, p) {
|
||||||
should.not.exist(err);
|
should.not.exist(err);
|
||||||
Product.find(function(err, products) {
|
Product.find(function(err, products) {
|
||||||
products.should.have.length(3);
|
products.should.have.length(3);
|
||||||
|
@ -588,7 +588,7 @@ describe('default scope', function () {
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
it('should apply default scope - destroyAll', function(done) {
|
it('should apply default scope - destroyAll', function(done) {
|
||||||
Widget.destroyAll(function(err) {
|
Widget.destroyAll(function(err) {
|
||||||
should.not.exist(err);
|
should.not.exist(err);
|
||||||
|
@ -599,17 +599,17 @@ describe('default scope', function () {
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
});
|
});
|
||||||
|
|
||||||
describe('scopes', function() {
|
describe('scopes', function() {
|
||||||
|
|
||||||
var ids = {};
|
var ids = {};
|
||||||
|
|
||||||
before(function (done) {
|
before(function(done) {
|
||||||
db.automigrate(setupProducts.bind(null, ids, done));
|
db.automigrate(setupProducts.bind(null, ids, done));
|
||||||
});
|
});
|
||||||
|
|
||||||
it('should merge with default scope', function(done) {
|
it('should merge with default scope', function(done) {
|
||||||
Product.active(function(err, products) {
|
Product.active(function(err, products) {
|
||||||
should.not.exist(err);
|
should.not.exist(err);
|
||||||
|
@ -620,7 +620,7 @@ describe('default scope', function () {
|
||||||
done();
|
done();
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
it('should merge with default scope - tool', function(done) {
|
it('should merge with default scope - tool', function(done) {
|
||||||
Tool.active(function(err, products) {
|
Tool.active(function(err, products) {
|
||||||
should.not.exist(err);
|
should.not.exist(err);
|
||||||
|
@ -629,7 +629,7 @@ describe('default scope', function () {
|
||||||
done();
|
done();
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
it('should merge with default scope - widget', function(done) {
|
it('should merge with default scope - widget', function(done) {
|
||||||
Widget.active(function(err, products) {
|
Widget.active(function(err, products) {
|
||||||
should.not.exist(err);
|
should.not.exist(err);
|
||||||
|
@ -639,89 +639,89 @@ describe('default scope', function () {
|
||||||
done();
|
done();
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
});
|
});
|
||||||
|
|
||||||
describe('scope function', function() {
|
describe('scope function', function() {
|
||||||
|
|
||||||
before(function(done) {
|
before(function(done) {
|
||||||
db.automigrate(done);
|
db.automigrate(done);
|
||||||
});
|
});
|
||||||
|
|
||||||
it('should create a scoped instance - widget', function(done) {
|
it('should create a scoped instance - widget', function(done) {
|
||||||
Widget.create({name: 'Product', kind:'ignored'}, function(err, p) {
|
Widget.create({ name: 'Product', kind:'ignored' }, function(err, p) {
|
||||||
p.name.should.equal('Product');
|
p.name.should.equal('Product');
|
||||||
p.kind.should.equal('Widget');
|
p.kind.should.equal('Widget');
|
||||||
done();
|
done();
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
it('should create a scoped instance - thing', function(done) {
|
it('should create a scoped instance - thing', function(done) {
|
||||||
Thing.create({name: 'Product', kind:'ignored'}, function(err, p) {
|
Thing.create({ name: 'Product', kind:'ignored' }, function(err, p) {
|
||||||
p.name.should.equal('Product');
|
p.name.should.equal('Product');
|
||||||
p.kind.should.equal('Thing');
|
p.kind.should.equal('Thing');
|
||||||
done();
|
done();
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
it('should find a scoped instance - widget', function(done) {
|
it('should find a scoped instance - widget', function(done) {
|
||||||
Widget.findOne({where: {name: 'Product'}}, function(err, p) {
|
Widget.findOne({ where: { name: 'Product' }}, function(err, p) {
|
||||||
p.name.should.equal('Product');
|
p.name.should.equal('Product');
|
||||||
p.kind.should.equal('Widget');
|
p.kind.should.equal('Widget');
|
||||||
done();
|
done();
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
it('should find a scoped instance - thing', function(done) {
|
it('should find a scoped instance - thing', function(done) {
|
||||||
Thing.findOne({where: {name: 'Product'}}, function(err, p) {
|
Thing.findOne({ where: { name: 'Product' }}, function(err, p) {
|
||||||
p.name.should.equal('Product');
|
p.name.should.equal('Product');
|
||||||
p.kind.should.equal('Thing');
|
p.kind.should.equal('Thing');
|
||||||
done();
|
done();
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
it('should find a scoped instance - thing', function(done) {
|
it('should find a scoped instance - thing', function(done) {
|
||||||
Product.find({where: {name: 'Product'}}, function(err, products) {
|
Product.find({ where: { name: 'Product' }}, function(err, products) {
|
||||||
products.should.have.length(2);
|
products.should.have.length(2);
|
||||||
products[0].name.should.equal('Product');
|
products[0].name.should.equal('Product');
|
||||||
products[1].name.should.equal('Product');
|
products[1].name.should.equal('Product');
|
||||||
var kinds = products.map(function(p) { return p.kind; })
|
var kinds = products.map(function(p) { return p.kind; });
|
||||||
kinds.sort();
|
kinds.sort();
|
||||||
kinds.should.eql(['Thing', 'Widget']);
|
kinds.should.eql(['Thing', 'Widget']);
|
||||||
done();
|
done();
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
});
|
});
|
||||||
|
|
||||||
describe('relations', function() {
|
describe('relations', function() {
|
||||||
|
|
||||||
var ids = {};
|
var ids = {};
|
||||||
|
|
||||||
before(function (done) {
|
before(function(done) {
|
||||||
db.automigrate(done);
|
db.automigrate(done);
|
||||||
});
|
});
|
||||||
|
|
||||||
before(function (done) {
|
before(function(done) {
|
||||||
Category.create({name: 'Category A'}, function(err, cat) {
|
Category.create({ name: 'Category A' }, function(err, cat) {
|
||||||
ids.categoryA = cat.id;
|
ids.categoryA = cat.id;
|
||||||
async.series([
|
async.series([
|
||||||
function(next) {
|
function(next) {
|
||||||
cat.widgets.create({name: 'Widget B', kind: 'ignored'}, next);
|
cat.widgets.create({ name: 'Widget B', kind: 'ignored' }, next);
|
||||||
},
|
},
|
||||||
function(next) {
|
function(next) {
|
||||||
cat.widgets.create({name: 'Widget A'}, next);
|
cat.widgets.create({ name: 'Widget A' }, next);
|
||||||
},
|
},
|
||||||
function(next) {
|
function(next) {
|
||||||
cat.tools.create({name: 'Tool A'}, next);
|
cat.tools.create({ name: 'Tool A' }, next);
|
||||||
},
|
},
|
||||||
function(next) {
|
function(next) {
|
||||||
cat.things.create({name: 'Thing A'}, next);
|
cat.things.create({ name: 'Thing A' }, next);
|
||||||
}
|
},
|
||||||
], done);
|
], done);
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
it('should apply default scope - products', function(done) {
|
it('should apply default scope - products', function(done) {
|
||||||
Category.findById(ids.categoryA, function(err, cat) {
|
Category.findById(ids.categoryA, function(err, cat) {
|
||||||
should.not.exist(err);
|
should.not.exist(err);
|
||||||
|
@ -732,21 +732,21 @@ describe('default scope', function () {
|
||||||
products[1].name.should.equal('Tool A');
|
products[1].name.should.equal('Tool A');
|
||||||
products[2].name.should.equal('Widget A');
|
products[2].name.should.equal('Widget A');
|
||||||
products[3].name.should.equal('Widget B');
|
products[3].name.should.equal('Widget B');
|
||||||
|
|
||||||
products[0].should.be.instanceof(Product);
|
products[0].should.be.instanceof(Product);
|
||||||
products[0].should.be.instanceof(Thing);
|
products[0].should.be.instanceof(Thing);
|
||||||
|
|
||||||
products[1].should.be.instanceof(Product);
|
products[1].should.be.instanceof(Product);
|
||||||
products[1].should.be.instanceof(Tool);
|
products[1].should.be.instanceof(Tool);
|
||||||
|
|
||||||
products[2].should.be.instanceof(Product);
|
products[2].should.be.instanceof(Product);
|
||||||
products[2].should.be.instanceof(Widget);
|
products[2].should.be.instanceof(Widget);
|
||||||
|
|
||||||
done();
|
done();
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
it('should apply default scope - widgets', function(done) {
|
it('should apply default scope - widgets', function(done) {
|
||||||
Category.findById(ids.categoryA, function(err, cat) {
|
Category.findById(ids.categoryA, function(err, cat) {
|
||||||
should.not.exist(err);
|
should.not.exist(err);
|
||||||
|
@ -763,7 +763,7 @@ describe('default scope', function () {
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
it('should apply default scope - tools', function(done) {
|
it('should apply default scope - tools', function(done) {
|
||||||
Category.findById(ids.categoryA, function(err, cat) {
|
Category.findById(ids.categoryA, function(err, cat) {
|
||||||
should.not.exist(err);
|
should.not.exist(err);
|
||||||
|
@ -779,7 +779,7 @@ describe('default scope', function () {
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
it('should apply default scope - things', function(done) {
|
it('should apply default scope - things', function(done) {
|
||||||
Category.findById(ids.categoryA, function(err, cat) {
|
Category.findById(ids.categoryA, function(err, cat) {
|
||||||
should.not.exist(err);
|
should.not.exist(err);
|
||||||
|
@ -795,13 +795,13 @@ describe('default scope', function () {
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
it('should create related item with default scope', function(done) {
|
it('should create related item with default scope', function(done) {
|
||||||
Category.findById(ids.categoryA, function(err, cat) {
|
Category.findById(ids.categoryA, function(err, cat) {
|
||||||
cat.tools.create({name: 'Tool B'}, done);
|
cat.tools.create({ name: 'Tool B' }, done);
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
it('should use relation scope order', function(done) {
|
it('should use relation scope order', function(done) {
|
||||||
Category.findById(ids.categoryA, function(err, cat) {
|
Category.findById(ids.categoryA, function(err, cat) {
|
||||||
should.not.exist(err);
|
should.not.exist(err);
|
||||||
|
@ -819,11 +819,11 @@ describe('default scope', function () {
|
||||||
|
|
||||||
describe('with include option', function() {
|
describe('with include option', function() {
|
||||||
|
|
||||||
before(function (done) {
|
before(function(done) {
|
||||||
db.automigrate(done);
|
db.automigrate(done);
|
||||||
});
|
});
|
||||||
|
|
||||||
before(function (done) {
|
before(function(done) {
|
||||||
Person.create({ id: 1, name: 'Person A' }, function(err, person) {
|
Person.create({ id: 1, name: 'Person A' }, function(err, person) {
|
||||||
person.things.create({ name: 'Thing A' }, done);
|
person.things.create({ name: 'Thing A' }, done);
|
||||||
});
|
});
|
||||||
|
|
|
@ -8,45 +8,45 @@ var should = require('./init.js');
|
||||||
|
|
||||||
var db = getSchema();
|
var db = getSchema();
|
||||||
|
|
||||||
describe('defaults', function () {
|
describe('defaults', function() {
|
||||||
var Server;
|
var Server;
|
||||||
|
|
||||||
before(function () {
|
before(function() {
|
||||||
Server = db.define('Server', {
|
Server = db.define('Server', {
|
||||||
host: String,
|
host: String,
|
||||||
port: {type: Number, default: 80},
|
port: { type: Number, default: 80 },
|
||||||
createdAt: {type: Date, default: '$now'}
|
createdAt: { type: Date, default: '$now' },
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
it('should apply defaults on new', function () {
|
it('should apply defaults on new', function() {
|
||||||
var s = new Server;
|
var s = new Server;
|
||||||
s.port.should.equal(80);
|
s.port.should.equal(80);
|
||||||
});
|
});
|
||||||
|
|
||||||
it('should apply defaults on create', function (done) {
|
it('should apply defaults on create', function(done) {
|
||||||
Server.create(function (err, s) {
|
Server.create(function(err, s) {
|
||||||
s.port.should.equal(80);
|
s.port.should.equal(80);
|
||||||
done();
|
done();
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
it('should apply defaults on read', function (done) {
|
it('should apply defaults on read', function(done) {
|
||||||
db.defineProperty('Server', 'host', {
|
db.defineProperty('Server', 'host', {
|
||||||
type: String,
|
type: String,
|
||||||
default: 'localhost'
|
default: 'localhost',
|
||||||
});
|
});
|
||||||
Server.all(function (err, servers) {
|
Server.all(function(err, servers) {
|
||||||
(new String('localhost')).should.equal(servers[0].host);
|
(new String('localhost')).should.equal(servers[0].host);
|
||||||
done();
|
done();
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
it('should ignore defaults with limited fields', function (done) {
|
it('should ignore defaults with limited fields', function(done) {
|
||||||
Server.create({ host: 'localhost', port: 8080 }, function(err, s) {
|
Server.create({ host: 'localhost', port: 8080 }, function(err, s) {
|
||||||
should.not.exist(err);
|
should.not.exist(err);
|
||||||
s.port.should.equal(8080);
|
s.port.should.equal(8080);
|
||||||
Server.find({ fields: ['host'] }, function (err, servers) {
|
Server.find({ fields: ['host'] }, function(err, servers) {
|
||||||
servers[0].host.should.equal('localhost');
|
servers[0].host.should.equal('localhost');
|
||||||
servers[0].should.have.property('host');
|
servers[0].should.have.property('host');
|
||||||
servers[0].should.have.property('port', undefined);
|
servers[0].should.have.property('port', undefined);
|
||||||
|
@ -55,17 +55,17 @@ describe('defaults', function () {
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
it('should apply defaults in upsert create', function (done) {
|
it('should apply defaults in upsert create', function(done) {
|
||||||
Server.upsert({port: 8181 }, function(err, server) {
|
Server.upsert({ port: 8181 }, function(err, server) {
|
||||||
should.not.exist(err);
|
should.not.exist(err);
|
||||||
should.exist(server.createdAt);
|
should.exist(server.createdAt);
|
||||||
done();
|
done();
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
it('should preserve defaults in upsert update', function (done) {
|
it('should preserve defaults in upsert update', function(done) {
|
||||||
Server.findOne({}, function(err, server) {
|
Server.findOne({}, function(err, server) {
|
||||||
Server.upsert({id:server.id, port: 1337 }, function(err, s) {
|
Server.upsert({ id:server.id, port: 1337 }, function(err, s) {
|
||||||
should.not.exist(err);
|
should.not.exist(err);
|
||||||
(Number(1337)).should.equal(s.port);
|
(Number(1337)).should.equal(s.port);
|
||||||
server.createdAt.should.eql(s.createdAt);
|
server.createdAt.should.eql(s.createdAt);
|
||||||
|
|
|
@ -11,11 +11,11 @@ describe('Memory connector with mocked discovery', function() {
|
||||||
var ds;
|
var ds;
|
||||||
|
|
||||||
before(function() {
|
before(function() {
|
||||||
ds = new DataSource({connector: 'memory'});
|
ds = new DataSource({ connector: 'memory' });
|
||||||
|
|
||||||
var models = [{type: 'table', name: 'CUSTOMER', owner: 'STRONGLOOP'},
|
var models = [{ type: 'table', name: 'CUSTOMER', owner: 'STRONGLOOP' },
|
||||||
{type: 'table', name: 'INVENTORY', owner: 'STRONGLOOP'},
|
{ type: 'table', name: 'INVENTORY', owner: 'STRONGLOOP' },
|
||||||
{type: 'table', name: 'LOCATION', owner: 'STRONGLOOP'}];
|
{ type: 'table', name: 'LOCATION', owner: 'STRONGLOOP' }];
|
||||||
|
|
||||||
ds.discoverModelDefinitions = function(options, cb) {
|
ds.discoverModelDefinitions = function(options, cb) {
|
||||||
process.nextTick(function() {
|
process.nextTick(function() {
|
||||||
|
@ -31,7 +31,7 @@ describe('Memory connector with mocked discovery', function() {
|
||||||
dataLength: 20,
|
dataLength: 20,
|
||||||
dataPrecision: null,
|
dataPrecision: null,
|
||||||
dataScale: null,
|
dataScale: null,
|
||||||
nullable: 0
|
nullable: 0,
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
owner: 'STRONGLOOP',
|
owner: 'STRONGLOOP',
|
||||||
|
@ -41,7 +41,7 @@ describe('Memory connector with mocked discovery', function() {
|
||||||
dataLength: 20,
|
dataLength: 20,
|
||||||
dataPrecision: null,
|
dataPrecision: null,
|
||||||
dataScale: null,
|
dataScale: null,
|
||||||
nullable: 0
|
nullable: 0,
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
owner: 'STRONGLOOP',
|
owner: 'STRONGLOOP',
|
||||||
|
@ -51,7 +51,7 @@ describe('Memory connector with mocked discovery', function() {
|
||||||
dataLength: null,
|
dataLength: null,
|
||||||
dataPrecision: 10,
|
dataPrecision: 10,
|
||||||
dataScale: 0,
|
dataScale: 0,
|
||||||
nullable: 1
|
nullable: 1,
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
owner: 'STRONGLOOP',
|
owner: 'STRONGLOOP',
|
||||||
|
@ -61,7 +61,7 @@ describe('Memory connector with mocked discovery', function() {
|
||||||
dataLength: null,
|
dataLength: null,
|
||||||
dataPrecision: 10,
|
dataPrecision: 10,
|
||||||
dataScale: 0,
|
dataScale: 0,
|
||||||
nullable: 1
|
nullable: 1,
|
||||||
}];
|
}];
|
||||||
|
|
||||||
ds.discoverModelProperties = function(modelName, options, cb) {
|
ds.discoverModelProperties = function(modelName, options, cb) {
|
||||||
|
@ -88,7 +88,7 @@ describe('Memory connector with mocked discovery', function() {
|
||||||
nameMapper: function(type, name) {
|
nameMapper: function(type, name) {
|
||||||
// Convert all names to lower case
|
// Convert all names to lower case
|
||||||
return name.toLowerCase();
|
return name.toLowerCase();
|
||||||
}
|
},
|
||||||
}, function(err, schemas) {
|
}, function(err, schemas) {
|
||||||
if (err) return done(err);
|
if (err) return done(err);
|
||||||
schemas.should.have.property('STRONGLOOP.INVENTORY');
|
schemas.should.have.property('STRONGLOOP.INVENTORY');
|
||||||
|
@ -102,7 +102,7 @@ describe('Memory connector with mocked discovery', function() {
|
||||||
|
|
||||||
it('should not convert table/column names with null custom mapper',
|
it('should not convert table/column names with null custom mapper',
|
||||||
function(done) {
|
function(done) {
|
||||||
ds.discoverSchemas('INVENTORY', {nameMapper: null}, function(err, schemas) {
|
ds.discoverSchemas('INVENTORY', { nameMapper: null }, function(err, schemas) {
|
||||||
if (err) return done(err);
|
if (err) return done(err);
|
||||||
schemas.should.have.property('STRONGLOOP.INVENTORY');
|
schemas.should.have.property('STRONGLOOP.INVENTORY');
|
||||||
var s = schemas['STRONGLOOP.INVENTORY'];
|
var s = schemas['STRONGLOOP.INVENTORY'];
|
||||||
|
@ -117,16 +117,16 @@ describe('Memory connector with mocked discovery', function() {
|
||||||
function(done) {
|
function(done) {
|
||||||
var models = {
|
var models = {
|
||||||
inventory: {
|
inventory: {
|
||||||
product: {type: 'string'},
|
product: { type: 'string' },
|
||||||
location: {type: 'string'}
|
location: { type: 'string' },
|
||||||
}
|
},
|
||||||
};
|
};
|
||||||
ds.connector.discoverSchemas = function(modelName, options, cb) {
|
ds.connector.discoverSchemas = function(modelName, options, cb) {
|
||||||
process.nextTick(function() {
|
process.nextTick(function() {
|
||||||
cb(null, models);
|
cb(null, models);
|
||||||
});
|
});
|
||||||
};
|
};
|
||||||
ds.discoverSchemas('INVENTORY', {nameMapper: null}, function(err, schemas) {
|
ds.discoverSchemas('INVENTORY', { nameMapper: null }, function(err, schemas) {
|
||||||
if (err) return done(err);
|
if (err) return done(err);
|
||||||
schemas.should.be.eql(models);
|
schemas.should.be.eql(models);
|
||||||
done();
|
done();
|
||||||
|
@ -137,9 +137,9 @@ describe('Memory connector with mocked discovery', function() {
|
||||||
function(done) {
|
function(done) {
|
||||||
var models = {
|
var models = {
|
||||||
inventory: {
|
inventory: {
|
||||||
product: {type: 'string'},
|
product: { type: 'string' },
|
||||||
location: {type: 'string'}
|
location: { type: 'string' },
|
||||||
}
|
},
|
||||||
};
|
};
|
||||||
ds.connector.discoverSchemas = function(modelName, options, cb) {
|
ds.connector.discoverSchemas = function(modelName, options, cb) {
|
||||||
process.nextTick(function() {
|
process.nextTick(function() {
|
||||||
|
@ -174,9 +174,9 @@ describe('Memory connector with mocked discovery', function() {
|
||||||
.catch(function(err) {
|
.catch(function(err) {
|
||||||
done(err);
|
done(err);
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
describe('discoverSchema', function(){
|
describe('discoverSchema', function() {
|
||||||
var models;
|
var models;
|
||||||
var schema;
|
var schema;
|
||||||
before(function() {
|
before(function() {
|
||||||
|
@ -184,7 +184,7 @@ describe('Memory connector with mocked discovery', function() {
|
||||||
name: 'Inventory',
|
name: 'Inventory',
|
||||||
options: {
|
options: {
|
||||||
idInjection: false,
|
idInjection: false,
|
||||||
memory: { schema: 'STRONGLOOP', table: 'INVENTORY' }
|
memory: { schema: 'STRONGLOOP', table: 'INVENTORY' },
|
||||||
},
|
},
|
||||||
properties: {
|
properties: {
|
||||||
available: {
|
available: {
|
||||||
|
@ -195,12 +195,12 @@ describe('Memory connector with mocked discovery', function() {
|
||||||
dataPrecision: 10,
|
dataPrecision: 10,
|
||||||
dataScale: 0,
|
dataScale: 0,
|
||||||
dataType: 'int',
|
dataType: 'int',
|
||||||
nullable: 1
|
nullable: 1,
|
||||||
},
|
},
|
||||||
precision: 10,
|
precision: 10,
|
||||||
required: false,
|
required: false,
|
||||||
scale: 0,
|
scale: 0,
|
||||||
type: undefined
|
type: undefined,
|
||||||
},
|
},
|
||||||
locationId: {
|
locationId: {
|
||||||
length: 20,
|
length: 20,
|
||||||
|
@ -210,12 +210,12 @@ describe('Memory connector with mocked discovery', function() {
|
||||||
dataPrecision: null,
|
dataPrecision: null,
|
||||||
dataScale: null,
|
dataScale: null,
|
||||||
dataType: 'varchar',
|
dataType: 'varchar',
|
||||||
nullable: 0
|
nullable: 0,
|
||||||
},
|
},
|
||||||
precision: null,
|
precision: null,
|
||||||
required: true,
|
required: true,
|
||||||
scale: null,
|
scale: null,
|
||||||
type: undefined
|
type: undefined,
|
||||||
},
|
},
|
||||||
productId: {
|
productId: {
|
||||||
length: 20,
|
length: 20,
|
||||||
|
@ -225,12 +225,12 @@ describe('Memory connector with mocked discovery', function() {
|
||||||
dataPrecision: null,
|
dataPrecision: null,
|
||||||
dataScale: null,
|
dataScale: null,
|
||||||
dataType: 'varchar',
|
dataType: 'varchar',
|
||||||
nullable: 0
|
nullable: 0,
|
||||||
},
|
},
|
||||||
precision: null,
|
precision: null,
|
||||||
required: true,
|
required: true,
|
||||||
scale: null,
|
scale: null,
|
||||||
type: undefined
|
type: undefined,
|
||||||
},
|
},
|
||||||
total: {
|
total: {
|
||||||
length: null,
|
length: null,
|
||||||
|
@ -240,15 +240,15 @@ describe('Memory connector with mocked discovery', function() {
|
||||||
dataPrecision: 10,
|
dataPrecision: 10,
|
||||||
dataScale: 0,
|
dataScale: 0,
|
||||||
dataType: 'int',
|
dataType: 'int',
|
||||||
nullable: 1
|
nullable: 1,
|
||||||
},
|
},
|
||||||
precision: 10,
|
precision: 10,
|
||||||
required: false,
|
required: false,
|
||||||
scale: 0,
|
scale: 0,
|
||||||
type: undefined
|
type: undefined,
|
||||||
}
|
},
|
||||||
}
|
},
|
||||||
} ;
|
};
|
||||||
});
|
});
|
||||||
|
|
||||||
it('should discover schema using `discoverSchema`', function(done) {
|
it('should discover schema using `discoverSchema`', function(done) {
|
||||||
|
@ -275,21 +275,21 @@ describe('Memory connector with mocked discovery', function() {
|
||||||
schemas.should.be.eql(schema);
|
schemas.should.be.eql(schema);
|
||||||
done();
|
done();
|
||||||
})
|
})
|
||||||
.catch(function(err){
|
.catch(function(err) {
|
||||||
done(err);
|
done(err);
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
describe('discoverModelDefinitions', function(){
|
describe('discoverModelDefinitions', function() {
|
||||||
var ds;
|
var ds;
|
||||||
before(function(){
|
before(function() {
|
||||||
ds = new DataSource({connector: 'memory'});
|
ds = new DataSource({ connector: 'memory' });
|
||||||
|
|
||||||
var models = [{type: 'table', name: 'CUSTOMER', owner: 'STRONGLOOP'},
|
var models = [{ type: 'table', name: 'CUSTOMER', owner: 'STRONGLOOP' },
|
||||||
{type: 'table', name: 'INVENTORY', owner: 'STRONGLOOP'},
|
{ type: 'table', name: 'INVENTORY', owner: 'STRONGLOOP' },
|
||||||
{type: 'table', name: 'LOCATION', owner: 'STRONGLOOP'}];
|
{ type: 'table', name: 'LOCATION', owner: 'STRONGLOOP' }];
|
||||||
|
|
||||||
ds.connector.discoverModelDefinitions = function(options, cb) {
|
ds.connector.discoverModelDefinitions = function(options, cb) {
|
||||||
process.nextTick(function() {
|
process.nextTick(function() {
|
||||||
|
@ -307,7 +307,7 @@ describe('discoverModelDefinitions', function(){
|
||||||
});
|
});
|
||||||
|
|
||||||
tableNames.should.be.eql(
|
tableNames.should.be.eql(
|
||||||
["CUSTOMER", "INVENTORY", "LOCATION"]
|
['CUSTOMER', 'INVENTORY', 'LOCATION']
|
||||||
);
|
);
|
||||||
done();
|
done();
|
||||||
});
|
});
|
||||||
|
@ -322,7 +322,7 @@ describe('discoverModelDefinitions', function(){
|
||||||
});
|
});
|
||||||
|
|
||||||
tableNames.should.be.eql(
|
tableNames.should.be.eql(
|
||||||
["CUSTOMER", "INVENTORY", "LOCATION"]
|
['CUSTOMER', 'INVENTORY', 'LOCATION']
|
||||||
);
|
);
|
||||||
done();
|
done();
|
||||||
};
|
};
|
||||||
|
@ -338,21 +338,21 @@ describe('discoverModelDefinitions', function(){
|
||||||
});
|
});
|
||||||
|
|
||||||
tableNames.should.be.eql(
|
tableNames.should.be.eql(
|
||||||
["CUSTOMER", "INVENTORY", "LOCATION"]
|
['CUSTOMER', 'INVENTORY', 'LOCATION']
|
||||||
);
|
);
|
||||||
done();
|
done();
|
||||||
})
|
})
|
||||||
.catch(function(err){
|
.catch(function(err) {
|
||||||
done(err);
|
done(err);
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
describe('discoverModelProperties', function(){
|
describe('discoverModelProperties', function() {
|
||||||
var ds;
|
var ds;
|
||||||
var modelProperties;
|
var modelProperties;
|
||||||
before(function(){
|
before(function() {
|
||||||
ds = new DataSource({connector: 'memory'});
|
ds = new DataSource({ connector: 'memory' });
|
||||||
|
|
||||||
modelProperties = [{
|
modelProperties = [{
|
||||||
owner: 'STRONGLOOP',
|
owner: 'STRONGLOOP',
|
||||||
|
@ -362,38 +362,38 @@ describe('discoverModelProperties', function(){
|
||||||
dataLength: 20,
|
dataLength: 20,
|
||||||
dataPrecision: null,
|
dataPrecision: null,
|
||||||
dataScale: null,
|
dataScale: null,
|
||||||
nullable: 0
|
nullable: 0,
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
owner: 'STRONGLOOP',
|
owner: 'STRONGLOOP',
|
||||||
tableName: 'INVENTORY',
|
tableName: 'INVENTORY',
|
||||||
columnName: 'LOCATION_ID',
|
columnName: 'LOCATION_ID',
|
||||||
dataType: 'varchar',
|
dataType: 'varchar',
|
||||||
dataLength: 20,
|
dataLength: 20,
|
||||||
dataPrecision: null,
|
dataPrecision: null,
|
||||||
dataScale: null,
|
dataScale: null,
|
||||||
nullable: 0
|
nullable: 0,
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
owner: 'STRONGLOOP',
|
owner: 'STRONGLOOP',
|
||||||
tableName: 'INVENTORY',
|
tableName: 'INVENTORY',
|
||||||
columnName: 'AVAILABLE',
|
columnName: 'AVAILABLE',
|
||||||
dataType: 'int',
|
dataType: 'int',
|
||||||
dataLength: null,
|
dataLength: null,
|
||||||
dataPrecision: 10,
|
dataPrecision: 10,
|
||||||
dataScale: 0,
|
dataScale: 0,
|
||||||
nullable: 1
|
nullable: 1,
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
owner: 'STRONGLOOP',
|
owner: 'STRONGLOOP',
|
||||||
tableName: 'INVENTORY',
|
tableName: 'INVENTORY',
|
||||||
columnName: 'TOTAL',
|
columnName: 'TOTAL',
|
||||||
dataType: 'int',
|
dataType: 'int',
|
||||||
dataLength: null,
|
dataLength: null,
|
||||||
dataPrecision: 10,
|
dataPrecision: 10,
|
||||||
dataScale: 0,
|
dataScale: 0,
|
||||||
nullable: 1
|
nullable: 1,
|
||||||
}];
|
}];
|
||||||
|
|
||||||
ds.connector.discoverModelProperties = function(modelName, options, cb) {
|
ds.connector.discoverModelProperties = function(modelName, options, cb) {
|
||||||
process.nextTick(function() {
|
process.nextTick(function() {
|
||||||
|
@ -404,11 +404,11 @@ describe('discoverModelProperties', function(){
|
||||||
|
|
||||||
it('should callback function, passed as options parameter', function(done) {
|
it('should callback function, passed as options parameter', function(done) {
|
||||||
var options = function(err, schemas) {
|
var options = function(err, schemas) {
|
||||||
if (err) return done(err);
|
if (err) return done(err);
|
||||||
|
|
||||||
schemas.should.be.eql(modelProperties);
|
schemas.should.be.eql(modelProperties);
|
||||||
done();
|
done();
|
||||||
};
|
};
|
||||||
|
|
||||||
ds.discoverModelProperties('INVENTORY', options);
|
ds.discoverModelProperties('INVENTORY', options);
|
||||||
});
|
});
|
||||||
|
@ -428,32 +428,32 @@ describe('discoverModelProperties', function(){
|
||||||
schemas.should.be.eql(modelProperties);
|
schemas.should.be.eql(modelProperties);
|
||||||
done();
|
done();
|
||||||
})
|
})
|
||||||
.catch(function(err){
|
.catch(function(err) {
|
||||||
done(err);
|
done(err);
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
describe('discoverPrimaryKeys', function(){
|
describe('discoverPrimaryKeys', function() {
|
||||||
var ds;
|
var ds;
|
||||||
var modelProperties;
|
var modelProperties;
|
||||||
before(function(){
|
before(function() {
|
||||||
ds = new DataSource({connector: 'memory'});
|
ds = new DataSource({ connector: 'memory' });
|
||||||
|
|
||||||
primaryKeys = [
|
primaryKeys = [
|
||||||
{
|
{
|
||||||
owner: 'STRONGLOOP',
|
owner: 'STRONGLOOP',
|
||||||
tableName: 'INVENTORY',
|
tableName: 'INVENTORY',
|
||||||
columnName: 'PRODUCT_ID',
|
columnName: 'PRODUCT_ID',
|
||||||
keySeq: 1,
|
keySeq: 1,
|
||||||
pkName: 'ID_PK'
|
pkName: 'ID_PK',
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
owner: 'STRONGLOOP',
|
owner: 'STRONGLOOP',
|
||||||
tableName: 'INVENTORY',
|
tableName: 'INVENTORY',
|
||||||
columnName: 'LOCATION_ID',
|
columnName: 'LOCATION_ID',
|
||||||
keySeq: 2,
|
keySeq: 2,
|
||||||
pkName: 'ID_PK'
|
pkName: 'ID_PK',
|
||||||
}];
|
}];
|
||||||
|
|
||||||
ds.connector.discoverPrimaryKeys = function(modelName, options, cb) {
|
ds.connector.discoverPrimaryKeys = function(modelName, options, cb) {
|
||||||
|
@ -488,19 +488,19 @@ describe('discoverPrimaryKeys', function(){
|
||||||
modelPrimaryKeys.should.be.eql(primaryKeys);
|
modelPrimaryKeys.should.be.eql(primaryKeys);
|
||||||
done();
|
done();
|
||||||
})
|
})
|
||||||
.catch(function(err){
|
.catch(function(err) {
|
||||||
done(err);
|
done(err);
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
describe('discoverForeignKeys', function(){
|
describe('discoverForeignKeys', function() {
|
||||||
var ds;
|
var ds;
|
||||||
var modelProperties;
|
var modelProperties;
|
||||||
before(function(){
|
before(function() {
|
||||||
ds = new DataSource({connector: 'memory'});
|
ds = new DataSource({ connector: 'memory' });
|
||||||
|
|
||||||
foreignKeys = [{
|
foreignKeys = [{
|
||||||
fkOwner: 'STRONGLOOP',
|
fkOwner: 'STRONGLOOP',
|
||||||
fkName: 'PRODUCT_FK',
|
fkName: 'PRODUCT_FK',
|
||||||
fkTableName: 'INVENTORY',
|
fkTableName: 'INVENTORY',
|
||||||
|
@ -509,7 +509,7 @@ describe('discoverForeignKeys', function(){
|
||||||
pkOwner: 'STRONGLOOP',
|
pkOwner: 'STRONGLOOP',
|
||||||
pkName: 'PRODUCT_PK',
|
pkName: 'PRODUCT_PK',
|
||||||
pkTableName: 'PRODUCT',
|
pkTableName: 'PRODUCT',
|
||||||
pkColumnName: 'ID'
|
pkColumnName: 'ID',
|
||||||
}];
|
}];
|
||||||
|
|
||||||
ds.connector.discoverForeignKeys = function(modelName, options, cb) {
|
ds.connector.discoverForeignKeys = function(modelName, options, cb) {
|
||||||
|
@ -545,17 +545,17 @@ describe('discoverForeignKeys', function(){
|
||||||
modelForeignKeys.should.be.eql(foreignKeys);
|
modelForeignKeys.should.be.eql(foreignKeys);
|
||||||
done();
|
done();
|
||||||
})
|
})
|
||||||
.catch(function(err){
|
.catch(function(err) {
|
||||||
done(err);
|
done(err);
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
describe('discoverExportedForeignKeys', function(){
|
describe('discoverExportedForeignKeys', function() {
|
||||||
var ds;
|
var ds;
|
||||||
var modelProperties;
|
var modelProperties;
|
||||||
before(function(){
|
before(function() {
|
||||||
ds = new DataSource({connector: 'memory'});
|
ds = new DataSource({ connector: 'memory' });
|
||||||
|
|
||||||
exportedForeignKeys = [{
|
exportedForeignKeys = [{
|
||||||
fkName: 'PRODUCT_FK',
|
fkName: 'PRODUCT_FK',
|
||||||
|
@ -566,7 +566,7 @@ describe('discoverExportedForeignKeys', function(){
|
||||||
pkName: 'PRODUCT_PK',
|
pkName: 'PRODUCT_PK',
|
||||||
pkOwner: 'STRONGLOOP',
|
pkOwner: 'STRONGLOOP',
|
||||||
pkTableName: 'PRODUCT',
|
pkTableName: 'PRODUCT',
|
||||||
pkColumnName: 'ID'
|
pkColumnName: 'ID',
|
||||||
}];
|
}];
|
||||||
|
|
||||||
ds.connector.discoverExportedForeignKeys = function(modelName, options, cb) {
|
ds.connector.discoverExportedForeignKeys = function(modelName, options, cb) {
|
||||||
|
@ -602,7 +602,7 @@ describe('discoverExportedForeignKeys', function(){
|
||||||
modelForeignKeys.should.be.eql(exportedForeignKeys);
|
modelForeignKeys.should.be.eql(exportedForeignKeys);
|
||||||
done();
|
done();
|
||||||
})
|
})
|
||||||
.catch(function(err){
|
.catch(function(err) {
|
||||||
done(err);
|
done(err);
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
|
@ -11,9 +11,9 @@ describe('events', function() {
|
||||||
this.db = getSchema();
|
this.db = getSchema();
|
||||||
this.TestModel = this.db.define('TestModel');
|
this.TestModel = this.db.define('TestModel');
|
||||||
this.db.automigrate(function(err) {
|
this.db.automigrate(function(err) {
|
||||||
if(err) return done(err);
|
if (err) return done(err);
|
||||||
test.TestModel.create(function(err, inst) {
|
test.TestModel.create(function(err, inst) {
|
||||||
if(err) return done(err);
|
if (err) return done(err);
|
||||||
test.inst = inst;
|
test.inst = inst;
|
||||||
done();
|
done();
|
||||||
});
|
});
|
||||||
|
@ -23,30 +23,30 @@ describe('events', function() {
|
||||||
listener.apply(this, arguments);
|
listener.apply(this, arguments);
|
||||||
done();
|
done();
|
||||||
});
|
});
|
||||||
}
|
};
|
||||||
});
|
});
|
||||||
|
|
||||||
describe('changed', function() {
|
describe('changed', function() {
|
||||||
it('should be emitted after save', function(done) {
|
it('should be emitted after save', function(done) {
|
||||||
var model = new this.TestModel({name: 'foobar'});
|
var model = new this.TestModel({ name: 'foobar' });
|
||||||
this.shouldEmitEvent('changed', assertValidChangedArgs, done);
|
this.shouldEmitEvent('changed', assertValidChangedArgs, done);
|
||||||
model.save();
|
model.save();
|
||||||
});
|
});
|
||||||
it('should be emitted after upsert', function(done) {
|
it('should be emitted after upsert', function(done) {
|
||||||
this.shouldEmitEvent('changed', assertValidChangedArgs, done);
|
this.shouldEmitEvent('changed', assertValidChangedArgs, done);
|
||||||
this.TestModel.upsert({name: 'batbaz'});
|
this.TestModel.upsert({ name: 'batbaz' });
|
||||||
});
|
});
|
||||||
it('should be emitted after create', function(done) {
|
it('should be emitted after create', function(done) {
|
||||||
this.shouldEmitEvent('changed', assertValidChangedArgs, done);
|
this.shouldEmitEvent('changed', assertValidChangedArgs, done);
|
||||||
this.TestModel.create({name: '...'});
|
this.TestModel.create({ name: '...' });
|
||||||
});
|
});
|
||||||
it('should be emitted after updateAttributes', function(done) {
|
it('should be emitted after updateAttributes', function(done) {
|
||||||
var test = this;
|
var test = this;
|
||||||
this.TestModel.create({name: 'bazzy'}, function(err, model) {
|
this.TestModel.create({ name: 'bazzy' }, function(err, model) {
|
||||||
// prevent getting the changed event from "create"
|
// prevent getting the changed event from "create"
|
||||||
process.nextTick(function() {
|
process.nextTick(function() {
|
||||||
test.shouldEmitEvent('changed', assertValidChangedArgs, done);
|
test.shouldEmitEvent('changed', assertValidChangedArgs, done);
|
||||||
model.updateAttributes({name: 'foo'});
|
model.updateAttributes({ name: 'foo' });
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
@ -68,7 +68,7 @@ describe('events', function() {
|
||||||
this.shouldEmitEvent('deletedAll', function(where) {
|
this.shouldEmitEvent('deletedAll', function(where) {
|
||||||
where.name.should.equal('foo');
|
where.name.should.equal('foo');
|
||||||
}, done);
|
}, done);
|
||||||
this.TestModel.destroyAll({name: 'foo'});
|
this.TestModel.destroyAll({ name: 'foo' });
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
|
@ -11,39 +11,39 @@ require('should');
|
||||||
var GeoPoint = require('../lib/geo').GeoPoint;
|
var GeoPoint = require('../lib/geo').GeoPoint;
|
||||||
var DELTA = 0.0000001;
|
var DELTA = 0.0000001;
|
||||||
|
|
||||||
describe('GeoPoint', function () {
|
describe('GeoPoint', function() {
|
||||||
|
|
||||||
describe('constructor', function() {
|
describe('constructor', function() {
|
||||||
|
|
||||||
it('should support a valid array', function () {
|
it('should support a valid array', function() {
|
||||||
var point = new GeoPoint([-34, 150]);
|
var point = new GeoPoint([-34, 150]);
|
||||||
|
|
||||||
point.lat.should.equal(-34);
|
point.lat.should.equal(-34);
|
||||||
point.lng.should.equal(150);
|
point.lng.should.equal(150);
|
||||||
});
|
});
|
||||||
|
|
||||||
it('should support a valid object', function () {
|
it('should support a valid object', function() {
|
||||||
var point = new GeoPoint({ lat: -34, lng: 150 });
|
var point = new GeoPoint({ lat: -34, lng: 150 });
|
||||||
|
|
||||||
point.lat.should.equal(-34);
|
point.lat.should.equal(-34);
|
||||||
point.lng.should.equal(150);
|
point.lng.should.equal(150);
|
||||||
});
|
});
|
||||||
|
|
||||||
it('should support valid string geo coordinates', function () {
|
it('should support valid string geo coordinates', function() {
|
||||||
var point = new GeoPoint('-34,150');
|
var point = new GeoPoint('-34,150');
|
||||||
|
|
||||||
point.lat.should.equal(-34);
|
point.lat.should.equal(-34);
|
||||||
point.lng.should.equal(150);
|
point.lng.should.equal(150);
|
||||||
});
|
});
|
||||||
|
|
||||||
it('should support coordinates as inline parameters', function () {
|
it('should support coordinates as inline parameters', function() {
|
||||||
var point = new GeoPoint(-34, 150);
|
var point = new GeoPoint(-34, 150);
|
||||||
|
|
||||||
point.lat.should.equal(-34);
|
point.lat.should.equal(-34);
|
||||||
point.lng.should.equal(150);
|
point.lng.should.equal(150);
|
||||||
});
|
});
|
||||||
|
|
||||||
it('should reject invalid parameters', function () {
|
it('should reject invalid parameters', function() {
|
||||||
/*jshint -W024 */
|
/*jshint -W024 */
|
||||||
var fn = function() {
|
var fn = function() {
|
||||||
new GeoPoint('150,-34');
|
new GeoPoint('150,-34');
|
||||||
|
@ -63,7 +63,7 @@ describe('GeoPoint', function () {
|
||||||
fn = function() {
|
fn = function() {
|
||||||
new GeoPoint({
|
new GeoPoint({
|
||||||
lat: 150,
|
lat: 150,
|
||||||
lng: null
|
lng: null,
|
||||||
});
|
});
|
||||||
};
|
};
|
||||||
fn.should.throw();
|
fn.should.throw();
|
||||||
|
@ -91,19 +91,19 @@ describe('GeoPoint', function () {
|
||||||
|
|
||||||
});
|
});
|
||||||
|
|
||||||
describe('distance calculation between two points', function () {
|
describe('distance calculation between two points', function() {
|
||||||
|
|
||||||
var here = new GeoPoint({ lat: 40.77492964101182, lng: -73.90950187151662 });
|
var here = new GeoPoint({ lat: 40.77492964101182, lng: -73.90950187151662 });
|
||||||
var there = new GeoPoint({ lat: 40.7753227, lng: -73.909217 });
|
var there = new GeoPoint({ lat: 40.7753227, lng: -73.909217 });
|
||||||
|
|
||||||
it('should return value in miles by default', function () {
|
it('should return value in miles by default', function() {
|
||||||
|
|
||||||
var distance = GeoPoint.distanceBetween(here, there);
|
var distance = GeoPoint.distanceBetween(here, there);
|
||||||
distance.should.be.a.Number;
|
distance.should.be.a.Number;
|
||||||
distance.should.be.approximately(0.03097916611592679, DELTA);
|
distance.should.be.approximately(0.03097916611592679, DELTA);
|
||||||
});
|
});
|
||||||
|
|
||||||
it('should return value using specified unit', function () {
|
it('should return value using specified unit', function() {
|
||||||
|
|
||||||
/* Supported units:
|
/* Supported units:
|
||||||
* - `radians`
|
* - `radians`
|
||||||
|
@ -114,27 +114,27 @@ describe('GeoPoint', function () {
|
||||||
* - `degrees`
|
* - `degrees`
|
||||||
*/
|
*/
|
||||||
|
|
||||||
var distance = here.distanceTo(there, { type: 'radians'});
|
var distance = here.distanceTo(there, { type: 'radians' });
|
||||||
distance.should.be.a.Number;
|
distance.should.be.a.Number;
|
||||||
distance.should.be.approximately(0.000007825491914348416, DELTA);
|
distance.should.be.approximately(0.000007825491914348416, DELTA);
|
||||||
|
|
||||||
distance = here.distanceTo(there, { type: 'kilometers'});
|
distance = here.distanceTo(there, { type: 'kilometers' });
|
||||||
distance.should.be.a.Number;
|
distance.should.be.a.Number;
|
||||||
distance.should.be.approximately(0.04985613511367009, DELTA);
|
distance.should.be.approximately(0.04985613511367009, DELTA);
|
||||||
|
|
||||||
distance = here.distanceTo(there, { type: 'meters'});
|
distance = here.distanceTo(there, { type: 'meters' });
|
||||||
distance.should.be.a.Number;
|
distance.should.be.a.Number;
|
||||||
distance.should.be.approximately(49.856135113670085, DELTA);
|
distance.should.be.approximately(49.856135113670085, DELTA);
|
||||||
|
|
||||||
distance = here.distanceTo(there, { type: 'miles'});
|
distance = here.distanceTo(there, { type: 'miles' });
|
||||||
distance.should.be.a.Number;
|
distance.should.be.a.Number;
|
||||||
distance.should.be.approximately(0.03097916611592679, DELTA);
|
distance.should.be.approximately(0.03097916611592679, DELTA);
|
||||||
|
|
||||||
distance = here.distanceTo(there, { type: 'feet'});
|
distance = here.distanceTo(there, { type: 'feet' });
|
||||||
distance.should.be.a.Number;
|
distance.should.be.a.Number;
|
||||||
distance.should.be.approximately(163.56999709209347, DELTA);
|
distance.should.be.approximately(163.56999709209347, DELTA);
|
||||||
|
|
||||||
distance = here.distanceTo(there, { type: 'degrees'});
|
distance = here.distanceTo(there, { type: 'degrees' });
|
||||||
distance.should.be.a.Number;
|
distance.should.be.a.Number;
|
||||||
distance.should.be.approximately(0.0004483676593058972, DELTA);
|
distance.should.be.approximately(0.0004483676593058972, DELTA);
|
||||||
});
|
});
|
||||||
|
|
|
@ -13,42 +13,42 @@ var j = require('../'),
|
||||||
|
|
||||||
db, User;
|
db, User;
|
||||||
|
|
||||||
describe('hooks', function () {
|
describe('hooks', function() {
|
||||||
|
|
||||||
before(function (done) {
|
before(function(done) {
|
||||||
db = getSchema();
|
db = getSchema();
|
||||||
|
|
||||||
User = db.define('User', {
|
User = db.define('User', {
|
||||||
email: {type: String, index: true},
|
email: { type: String, index: true },
|
||||||
name: String,
|
name: String,
|
||||||
password: String,
|
password: String,
|
||||||
state: String
|
state: String,
|
||||||
});
|
});
|
||||||
|
|
||||||
db.automigrate('User', done);
|
db.automigrate('User', done);
|
||||||
});
|
});
|
||||||
|
|
||||||
describe('initialize', function () {
|
describe('initialize', function() {
|
||||||
|
|
||||||
afterEach(function () {
|
afterEach(function() {
|
||||||
User.afterInitialize = null;
|
User.afterInitialize = null;
|
||||||
});
|
});
|
||||||
|
|
||||||
it('should be triggered on new', function (done) {
|
it('should be triggered on new', function(done) {
|
||||||
User.afterInitialize = function () {
|
User.afterInitialize = function() {
|
||||||
done();
|
done();
|
||||||
};
|
};
|
||||||
new User;
|
new User;
|
||||||
});
|
});
|
||||||
|
|
||||||
it('should be triggered on create', function (done) {
|
it('should be triggered on create', function(done) {
|
||||||
var user;
|
var user;
|
||||||
User.afterInitialize = function () {
|
User.afterInitialize = function() {
|
||||||
if (this.name === 'Nickolay') {
|
if (this.name === 'Nickolay') {
|
||||||
this.name += ' Rozental';
|
this.name += ' Rozental';
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
User.create({name: 'Nickolay'}, function (err, u) {
|
User.create({ name: 'Nickolay' }, function(err, u) {
|
||||||
u.id.should.be.ok;
|
u.id.should.be.ok;
|
||||||
u.name.should.equal('Nickolay Rozental');
|
u.name.should.equal('Nickolay Rozental');
|
||||||
done();
|
done();
|
||||||
|
@ -57,116 +57,116 @@ describe('hooks', function () {
|
||||||
|
|
||||||
});
|
});
|
||||||
|
|
||||||
describe('create', function () {
|
describe('create', function() {
|
||||||
|
|
||||||
afterEach(removeHooks('Create'));
|
afterEach(removeHooks('Create'));
|
||||||
|
|
||||||
it('should be triggered on create', function (done) {
|
it('should be triggered on create', function(done) {
|
||||||
addHooks('Create', done);
|
addHooks('Create', done);
|
||||||
User.create();
|
User.create();
|
||||||
});
|
});
|
||||||
|
|
||||||
it('should not be triggered on new', function () {
|
it('should not be triggered on new', function() {
|
||||||
User.beforeCreate = function (next) {
|
User.beforeCreate = function(next) {
|
||||||
should.fail('This should not be called');
|
should.fail('This should not be called');
|
||||||
next();
|
next();
|
||||||
};
|
};
|
||||||
var u = new User;
|
var u = new User;
|
||||||
});
|
});
|
||||||
|
|
||||||
it('should be triggered on new+save', function (done) {
|
it('should be triggered on new+save', function(done) {
|
||||||
addHooks('Create', done);
|
addHooks('Create', done);
|
||||||
(new User).save();
|
(new User).save();
|
||||||
});
|
});
|
||||||
|
|
||||||
it('afterCreate should not be triggered on failed create', function (done) {
|
it('afterCreate should not be triggered on failed create', function(done) {
|
||||||
var old = User.dataSource.connector.create;
|
var old = User.dataSource.connector.create;
|
||||||
User.dataSource.connector.create = function (modelName, id, cb) {
|
User.dataSource.connector.create = function(modelName, id, cb) {
|
||||||
cb(new Error('error'));
|
cb(new Error('error'));
|
||||||
}
|
};
|
||||||
|
|
||||||
User.afterCreate = function () {
|
User.afterCreate = function() {
|
||||||
throw new Error('shouldn\'t be called');
|
throw new Error('shouldn\'t be called');
|
||||||
};
|
};
|
||||||
User.create(function (err, user) {
|
User.create(function(err, user) {
|
||||||
User.dataSource.connector.create = old;
|
User.dataSource.connector.create = old;
|
||||||
done();
|
done();
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
it('afterCreate should not be triggered on failed beforeCreate', function (done) {
|
it('afterCreate should not be triggered on failed beforeCreate', function(done) {
|
||||||
User.beforeCreate = function (next, data) {
|
User.beforeCreate = function(next, data) {
|
||||||
// Skip next()
|
// Skip next()
|
||||||
next(new Error('fail in beforeCreate'));
|
next(new Error('fail in beforeCreate'));
|
||||||
};
|
};
|
||||||
|
|
||||||
var old = User.dataSource.connector.create;
|
var old = User.dataSource.connector.create;
|
||||||
User.dataSource.connector.create = function (modelName, id, cb) {
|
User.dataSource.connector.create = function(modelName, id, cb) {
|
||||||
throw new Error('shouldn\'t be called');
|
|
||||||
}
|
|
||||||
|
|
||||||
User.afterCreate = function () {
|
|
||||||
throw new Error('shouldn\'t be called');
|
throw new Error('shouldn\'t be called');
|
||||||
};
|
};
|
||||||
User.create(function (err, user) {
|
|
||||||
|
User.afterCreate = function() {
|
||||||
|
throw new Error('shouldn\'t be called');
|
||||||
|
};
|
||||||
|
User.create(function(err, user) {
|
||||||
User.dataSource.connector.create = old;
|
User.dataSource.connector.create = old;
|
||||||
done();
|
done();
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
describe('save', function () {
|
describe('save', function() {
|
||||||
afterEach(removeHooks('Save'));
|
afterEach(removeHooks('Save'));
|
||||||
|
|
||||||
it('should be triggered on create', function (done) {
|
it('should be triggered on create', function(done) {
|
||||||
addHooks('Save', done);
|
addHooks('Save', done);
|
||||||
User.create();
|
User.create();
|
||||||
});
|
});
|
||||||
|
|
||||||
it('should be triggered on new+save', function (done) {
|
it('should be triggered on new+save', function(done) {
|
||||||
addHooks('Save', done);
|
addHooks('Save', done);
|
||||||
(new User).save();
|
(new User).save();
|
||||||
});
|
});
|
||||||
|
|
||||||
it('should be triggered on updateAttributes', function (done) {
|
it('should be triggered on updateAttributes', function(done) {
|
||||||
User.create(function (err, user) {
|
User.create(function(err, user) {
|
||||||
addHooks('Save', done);
|
addHooks('Save', done);
|
||||||
user.updateAttributes({name: 'Anatoliy'});
|
user.updateAttributes({ name: 'Anatoliy' });
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
it('should be triggered on save', function (done) {
|
it('should be triggered on save', function(done) {
|
||||||
User.create(function (err, user) {
|
User.create(function(err, user) {
|
||||||
addHooks('Save', done);
|
addHooks('Save', done);
|
||||||
user.name = 'Hamburger';
|
user.name = 'Hamburger';
|
||||||
user.save();
|
user.save();
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
it('should save full object', function (done) {
|
it('should save full object', function(done) {
|
||||||
User.create(function (err, user) {
|
User.create(function(err, user) {
|
||||||
User.beforeSave = function (next, data) {
|
User.beforeSave = function(next, data) {
|
||||||
data.should.have.keys('id', 'name', 'email',
|
data.should.have.keys('id', 'name', 'email',
|
||||||
'password', 'state')
|
'password', 'state');
|
||||||
done();
|
done();
|
||||||
};
|
};
|
||||||
user.save();
|
user.save();
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
it('should save actual modifications to database', function (done) {
|
it('should save actual modifications to database', function(done) {
|
||||||
User.beforeSave = function (next, data) {
|
User.beforeSave = function(next, data) {
|
||||||
data.password = 'hash';
|
data.password = 'hash';
|
||||||
next();
|
next();
|
||||||
};
|
};
|
||||||
User.destroyAll(function () {
|
User.destroyAll(function() {
|
||||||
User.create({
|
User.create({
|
||||||
email: 'james.bond@example.com',
|
email: 'james.bond@example.com',
|
||||||
password: '53cr3t'
|
password: '53cr3t',
|
||||||
}, function () {
|
}, function() {
|
||||||
User.findOne({
|
User.findOne({
|
||||||
where: {email: 'james.bond@example.com'}
|
where: { email: 'james.bond@example.com' },
|
||||||
}, function (err, jb) {
|
}, function(err, jb) {
|
||||||
jb.password.should.equal('hash');
|
jb.password.should.equal('hash');
|
||||||
done();
|
done();
|
||||||
});
|
});
|
||||||
|
@ -174,22 +174,22 @@ describe('hooks', function () {
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
it('should save actual modifications on updateAttributes', function (done) {
|
it('should save actual modifications on updateAttributes', function(done) {
|
||||||
User.beforeSave = function (next, data) {
|
User.beforeSave = function(next, data) {
|
||||||
data.password = 'hash';
|
data.password = 'hash';
|
||||||
next();
|
next();
|
||||||
};
|
};
|
||||||
User.destroyAll(function () {
|
User.destroyAll(function() {
|
||||||
User.create({
|
User.create({
|
||||||
email: 'james.bond@example.com'
|
email: 'james.bond@example.com',
|
||||||
}, function (err, u) {
|
}, function(err, u) {
|
||||||
u.updateAttribute('password', 'new password', function (e, u) {
|
u.updateAttribute('password', 'new password', function(e, u) {
|
||||||
should.not.exist(e);
|
should.not.exist(e);
|
||||||
should.exist(u);
|
should.exist(u);
|
||||||
u.password.should.equal('hash');
|
u.password.should.equal('hash');
|
||||||
User.findOne({
|
User.findOne({
|
||||||
where: {email: 'james.bond@example.com'}
|
where: { email: 'james.bond@example.com' },
|
||||||
}, function (err, jb) {
|
}, function(err, jb) {
|
||||||
jb.password.should.equal('hash');
|
jb.password.should.equal('hash');
|
||||||
done();
|
done();
|
||||||
});
|
});
|
||||||
|
@ -198,9 +198,9 @@ describe('hooks', function () {
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
it('beforeSave should be able to skip next', function (done) {
|
it('beforeSave should be able to skip next', function(done) {
|
||||||
User.create(function (err, user) {
|
User.create(function(err, user) {
|
||||||
User.beforeSave = function (next, data) {
|
User.beforeSave = function(next, data) {
|
||||||
next(null, 'XYZ');
|
next(null, 'XYZ');
|
||||||
};
|
};
|
||||||
user.save(function(err, result) {
|
user.save(function(err, result) {
|
||||||
|
@ -212,97 +212,97 @@ describe('hooks', function () {
|
||||||
|
|
||||||
});
|
});
|
||||||
|
|
||||||
describe('update', function () {
|
describe('update', function() {
|
||||||
afterEach(removeHooks('Update'));
|
afterEach(removeHooks('Update'));
|
||||||
|
|
||||||
it('should not be triggered on create', function () {
|
it('should not be triggered on create', function() {
|
||||||
User.beforeUpdate = function (next) {
|
User.beforeUpdate = function(next) {
|
||||||
should.fail('This should not be called');
|
should.fail('This should not be called');
|
||||||
next();
|
next();
|
||||||
};
|
};
|
||||||
User.create();
|
User.create();
|
||||||
});
|
});
|
||||||
|
|
||||||
it('should not be triggered on new+save', function () {
|
it('should not be triggered on new+save', function() {
|
||||||
User.beforeUpdate = function (next) {
|
User.beforeUpdate = function(next) {
|
||||||
should.fail('This should not be called');
|
should.fail('This should not be called');
|
||||||
next();
|
next();
|
||||||
};
|
};
|
||||||
(new User).save();
|
(new User).save();
|
||||||
});
|
});
|
||||||
|
|
||||||
it('should be triggered on updateAttributes', function (done) {
|
it('should be triggered on updateAttributes', function(done) {
|
||||||
User.create(function (err, user) {
|
User.create(function(err, user) {
|
||||||
addHooks('Update', done);
|
addHooks('Update', done);
|
||||||
user.updateAttributes({name: 'Anatoliy'});
|
user.updateAttributes({ name: 'Anatoliy' });
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
it('should be triggered on save', function (done) {
|
it('should be triggered on save', function(done) {
|
||||||
User.create(function (err, user) {
|
User.create(function(err, user) {
|
||||||
addHooks('Update', done);
|
addHooks('Update', done);
|
||||||
user.name = 'Hamburger';
|
user.name = 'Hamburger';
|
||||||
user.save();
|
user.save();
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
it('should update limited set of fields', function (done) {
|
it('should update limited set of fields', function(done) {
|
||||||
User.create(function (err, user) {
|
User.create(function(err, user) {
|
||||||
User.beforeUpdate = function (next, data) {
|
User.beforeUpdate = function(next, data) {
|
||||||
data.should.have.keys('name', 'email');
|
data.should.have.keys('name', 'email');
|
||||||
done();
|
done();
|
||||||
};
|
};
|
||||||
user.updateAttributes({name: 1, email: 2});
|
user.updateAttributes({ name: 1, email: 2 });
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
it('should not trigger after-hook on failed save', function (done) {
|
it('should not trigger after-hook on failed save', function(done) {
|
||||||
User.afterUpdate = function () {
|
User.afterUpdate = function() {
|
||||||
should.fail('afterUpdate shouldn\'t be called');
|
should.fail('afterUpdate shouldn\'t be called');
|
||||||
};
|
};
|
||||||
User.create(function (err, user) {
|
User.create(function(err, user) {
|
||||||
var save = User.dataSource.connector.save;
|
var save = User.dataSource.connector.save;
|
||||||
User.dataSource.connector.save = function (modelName, id, cb) {
|
User.dataSource.connector.save = function(modelName, id, cb) {
|
||||||
User.dataSource.connector.save = save;
|
User.dataSource.connector.save = save;
|
||||||
cb(new Error('Error'));
|
cb(new Error('Error'));
|
||||||
}
|
};
|
||||||
|
|
||||||
user.save(function (err) {
|
user.save(function(err) {
|
||||||
done();
|
done();
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
describe('destroy', function () {
|
describe('destroy', function() {
|
||||||
|
|
||||||
afterEach(removeHooks('Destroy'));
|
afterEach(removeHooks('Destroy'));
|
||||||
|
|
||||||
it('should be triggered on destroy', function (done) {
|
it('should be triggered on destroy', function(done) {
|
||||||
var hook = 'not called';
|
var hook = 'not called';
|
||||||
User.beforeDestroy = function (next) {
|
User.beforeDestroy = function(next) {
|
||||||
hook = 'called';
|
hook = 'called';
|
||||||
next();
|
next();
|
||||||
};
|
};
|
||||||
User.afterDestroy = function (next) {
|
User.afterDestroy = function(next) {
|
||||||
hook.should.eql('called');
|
hook.should.eql('called');
|
||||||
next();
|
next();
|
||||||
};
|
};
|
||||||
User.create(function (err, user) {
|
User.create(function(err, user) {
|
||||||
user.destroy(done);
|
user.destroy(done);
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
it('should not trigger after-hook on failed destroy', function (done) {
|
it('should not trigger after-hook on failed destroy', function(done) {
|
||||||
var destroy = User.dataSource.connector.destroy;
|
var destroy = User.dataSource.connector.destroy;
|
||||||
User.dataSource.connector.destroy = function (modelName, id, cb) {
|
User.dataSource.connector.destroy = function(modelName, id, cb) {
|
||||||
cb(new Error('error'));
|
cb(new Error('error'));
|
||||||
}
|
|
||||||
User.afterDestroy = function () {
|
|
||||||
should.fail('afterDestroy shouldn\'t be called')
|
|
||||||
};
|
};
|
||||||
User.create(function (err, user) {
|
User.afterDestroy = function() {
|
||||||
user.destroy(function (err) {
|
should.fail('afterDestroy shouldn\'t be called');
|
||||||
|
};
|
||||||
|
User.create(function(err, user) {
|
||||||
|
user.destroy(function(err) {
|
||||||
User.dataSource.connector.destroy = destroy;
|
User.dataSource.connector.destroy = destroy;
|
||||||
done();
|
done();
|
||||||
});
|
});
|
||||||
|
@ -311,64 +311,64 @@ describe('hooks', function () {
|
||||||
|
|
||||||
});
|
});
|
||||||
|
|
||||||
describe('lifecycle', function () {
|
describe('lifecycle', function() {
|
||||||
var life = [], user;
|
var life = [], user;
|
||||||
before(function (done) {
|
before(function(done) {
|
||||||
User.beforeSave = function (d) {
|
User.beforeSave = function(d) {
|
||||||
life.push('beforeSave');
|
life.push('beforeSave');
|
||||||
d();
|
d();
|
||||||
};
|
};
|
||||||
User.beforeCreate = function (d) {
|
User.beforeCreate = function(d) {
|
||||||
life.push('beforeCreate');
|
life.push('beforeCreate');
|
||||||
d();
|
d();
|
||||||
};
|
};
|
||||||
User.beforeUpdate = function (d) {
|
User.beforeUpdate = function(d) {
|
||||||
life.push('beforeUpdate');
|
life.push('beforeUpdate');
|
||||||
d();
|
d();
|
||||||
};
|
};
|
||||||
User.beforeDestroy = function (d) {
|
User.beforeDestroy = function(d) {
|
||||||
life.push('beforeDestroy');
|
life.push('beforeDestroy');
|
||||||
d();
|
d();
|
||||||
};
|
};
|
||||||
User.beforeValidate = function (d) {
|
User.beforeValidate = function(d) {
|
||||||
life.push('beforeValidate');
|
life.push('beforeValidate');
|
||||||
d();
|
d();
|
||||||
};
|
};
|
||||||
User.afterInitialize = function () {
|
User.afterInitialize = function() {
|
||||||
life.push('afterInitialize');
|
life.push('afterInitialize');
|
||||||
};
|
};
|
||||||
User.afterSave = function (d) {
|
User.afterSave = function(d) {
|
||||||
life.push('afterSave');
|
life.push('afterSave');
|
||||||
d();
|
d();
|
||||||
};
|
};
|
||||||
User.afterCreate = function (d) {
|
User.afterCreate = function(d) {
|
||||||
life.push('afterCreate');
|
life.push('afterCreate');
|
||||||
d();
|
d();
|
||||||
};
|
};
|
||||||
User.afterUpdate = function (d) {
|
User.afterUpdate = function(d) {
|
||||||
life.push('afterUpdate');
|
life.push('afterUpdate');
|
||||||
d();
|
d();
|
||||||
};
|
};
|
||||||
User.afterDestroy = function (d) {
|
User.afterDestroy = function(d) {
|
||||||
life.push('afterDestroy');
|
life.push('afterDestroy');
|
||||||
d();
|
d();
|
||||||
};
|
};
|
||||||
User.afterValidate = function (d) {
|
User.afterValidate = function(d) {
|
||||||
life.push('afterValidate');
|
life.push('afterValidate');
|
||||||
d();
|
d();
|
||||||
};
|
};
|
||||||
User.create(function (e, u) {
|
User.create(function(e, u) {
|
||||||
user = u;
|
user = u;
|
||||||
life = [];
|
life = [];
|
||||||
done();
|
done();
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
beforeEach(function () {
|
beforeEach(function() {
|
||||||
life = [];
|
life = [];
|
||||||
});
|
});
|
||||||
|
|
||||||
it('should describe create sequence', function (done) {
|
it('should describe create sequence', function(done) {
|
||||||
User.create(function () {
|
User.create(function() {
|
||||||
life.should.eql([
|
life.should.eql([
|
||||||
'afterInitialize',
|
'afterInitialize',
|
||||||
'beforeValidate',
|
'beforeValidate',
|
||||||
|
@ -376,15 +376,15 @@ describe('hooks', function () {
|
||||||
'beforeCreate',
|
'beforeCreate',
|
||||||
'beforeSave',
|
'beforeSave',
|
||||||
'afterSave',
|
'afterSave',
|
||||||
'afterCreate'
|
'afterCreate',
|
||||||
]);
|
]);
|
||||||
done();
|
done();
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
it('should describe new+save sequence', function (done) {
|
it('should describe new+save sequence', function(done) {
|
||||||
var u = new User;
|
var u = new User;
|
||||||
u.save(function () {
|
u.save(function() {
|
||||||
life.should.eql([
|
life.should.eql([
|
||||||
'afterInitialize',
|
'afterInitialize',
|
||||||
'beforeValidate',
|
'beforeValidate',
|
||||||
|
@ -392,14 +392,14 @@ describe('hooks', function () {
|
||||||
'beforeCreate',
|
'beforeCreate',
|
||||||
'beforeSave',
|
'beforeSave',
|
||||||
'afterSave',
|
'afterSave',
|
||||||
'afterCreate'
|
'afterCreate',
|
||||||
]);
|
]);
|
||||||
done();
|
done();
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
it('should describe updateAttributes sequence', function (done) {
|
it('should describe updateAttributes sequence', function(done) {
|
||||||
user.updateAttributes({name: 'Antony'}, function () {
|
user.updateAttributes({ name: 'Antony' }, function() {
|
||||||
life.should.eql([
|
life.should.eql([
|
||||||
'beforeValidate',
|
'beforeValidate',
|
||||||
'afterValidate',
|
'afterValidate',
|
||||||
|
@ -412,25 +412,25 @@ describe('hooks', function () {
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
it('should describe isValid sequence', function (done) {
|
it('should describe isValid sequence', function(done) {
|
||||||
should.not.exist(
|
should.not.exist(
|
||||||
user.constructor._validations,
|
user.constructor._validations,
|
||||||
'Expected user to have no validations, but she have');
|
'Expected user to have no validations, but she have');
|
||||||
user.isValid(function (valid) {
|
user.isValid(function(valid) {
|
||||||
valid.should.be.true;
|
valid.should.be.true;
|
||||||
life.should.eql([
|
life.should.eql([
|
||||||
'beforeValidate',
|
'beforeValidate',
|
||||||
'afterValidate'
|
'afterValidate',
|
||||||
]);
|
]);
|
||||||
done();
|
done();
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
it('should describe destroy sequence', function (done) {
|
it('should describe destroy sequence', function(done) {
|
||||||
user.destroy(function () {
|
user.destroy(function() {
|
||||||
life.should.eql([
|
life.should.eql([
|
||||||
'beforeDestroy',
|
'beforeDestroy',
|
||||||
'afterDestroy'
|
'afterDestroy',
|
||||||
]);
|
]);
|
||||||
done();
|
done();
|
||||||
});
|
});
|
||||||
|
@ -443,12 +443,12 @@ describe('hooks', function () {
|
||||||
|
|
||||||
function addHooks(name, done) {
|
function addHooks(name, done) {
|
||||||
var called = false, random = String(Math.floor(Math.random() * 1000));
|
var called = false, random = String(Math.floor(Math.random() * 1000));
|
||||||
User['before' + name] = function (next, data) {
|
User['before' + name] = function(next, data) {
|
||||||
called = true;
|
called = true;
|
||||||
data.email = random;
|
data.email = random;
|
||||||
next();
|
next();
|
||||||
};
|
};
|
||||||
User['after' + name] = function (next) {
|
User['after' + name] = function(next) {
|
||||||
(new Boolean(called)).should.equal(true);
|
(new Boolean(called)).should.equal(true);
|
||||||
this.should.have.property('email', random);
|
this.should.have.property('email', random);
|
||||||
done();
|
done();
|
||||||
|
@ -456,7 +456,7 @@ function addHooks(name, done) {
|
||||||
}
|
}
|
||||||
|
|
||||||
function removeHooks(name) {
|
function removeHooks(name) {
|
||||||
return function () {
|
return function() {
|
||||||
User['after' + name] = null;
|
User['after' + name] = null;
|
||||||
User['before' + name] = null;
|
User['before' + name] = null;
|
||||||
};
|
};
|
||||||
|
|
|
@ -12,14 +12,14 @@ var DataSource = require('../').DataSource;
|
||||||
|
|
||||||
var db, User, Profile, AccessToken, Post, Passport, City, Street, Building, Assembly, Part;
|
var db, User, Profile, AccessToken, Post, Passport, City, Street, Building, Assembly, Part;
|
||||||
|
|
||||||
describe('include', function () {
|
describe('include', function() {
|
||||||
|
|
||||||
before(setup);
|
before(setup);
|
||||||
|
|
||||||
it('should fetch belongsTo relation', function (done) {
|
it('should fetch belongsTo relation', function(done) {
|
||||||
Passport.find({include: 'owner'}, function (err, passports) {
|
Passport.find({ include: 'owner' }, function(err, passports) {
|
||||||
passports.length.should.be.ok;
|
passports.length.should.be.ok;
|
||||||
passports.forEach(function (p) {
|
passports.forEach(function(p) {
|
||||||
p.__cachedRelations.should.have.property('owner');
|
p.__cachedRelations.should.have.property('owner');
|
||||||
|
|
||||||
// The relation should be promoted as the 'owner' property
|
// The relation should be promoted as the 'owner' property
|
||||||
|
@ -39,19 +39,19 @@ describe('include', function () {
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
it('should fetch hasMany relation', function (done) {
|
it('should fetch hasMany relation', function(done) {
|
||||||
User.find({include: 'posts'}, function (err, users) {
|
User.find({ include: 'posts' }, function(err, users) {
|
||||||
should.not.exist(err);
|
should.not.exist(err);
|
||||||
should.exist(users);
|
should.exist(users);
|
||||||
users.length.should.be.ok;
|
users.length.should.be.ok;
|
||||||
users.forEach(function (u) {
|
users.forEach(function(u) {
|
||||||
// The relation should be promoted as the 'owner' property
|
// The relation should be promoted as the 'owner' property
|
||||||
u.should.have.property('posts');
|
u.should.have.property('posts');
|
||||||
// The __cachedRelations should be removed from json output
|
// The __cachedRelations should be removed from json output
|
||||||
u.toJSON().should.not.have.property('__cachedRelations');
|
u.toJSON().should.not.have.property('__cachedRelations');
|
||||||
|
|
||||||
u.__cachedRelations.should.have.property('posts');
|
u.__cachedRelations.should.have.property('posts');
|
||||||
u.__cachedRelations.posts.forEach(function (p) {
|
u.__cachedRelations.posts.forEach(function(p) {
|
||||||
p.userId.should.eql(u.id);
|
p.userId.should.eql(u.id);
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
@ -59,13 +59,13 @@ describe('include', function () {
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
it('should fetch Passport - Owner - Posts', function (done) {
|
it('should fetch Passport - Owner - Posts', function(done) {
|
||||||
Passport.find({include: {owner: 'posts'}}, function (err, passports) {
|
Passport.find({ include: { owner: 'posts' }}, function(err, passports) {
|
||||||
|
|
||||||
should.not.exist(err);
|
should.not.exist(err);
|
||||||
should.exist(passports);
|
should.exist(passports);
|
||||||
passports.length.should.be.ok;
|
passports.length.should.be.ok;
|
||||||
passports.forEach(function (p) {
|
passports.forEach(function(p) {
|
||||||
p.__cachedRelations.should.have.property('owner');
|
p.__cachedRelations.should.have.property('owner');
|
||||||
|
|
||||||
// The relation should be promoted as the 'owner' property
|
// The relation should be promoted as the 'owner' property
|
||||||
|
@ -82,7 +82,7 @@ describe('include', function () {
|
||||||
user.__cachedRelations.should.have.property('posts');
|
user.__cachedRelations.should.have.property('posts');
|
||||||
user.should.have.property('posts');
|
user.should.have.property('posts');
|
||||||
user.toJSON().should.have.property('posts').and.be.an.Array;
|
user.toJSON().should.have.property('posts').and.be.an.Array;
|
||||||
user.__cachedRelations.posts.forEach(function (pp) {
|
user.__cachedRelations.posts.forEach(function(pp) {
|
||||||
pp.userId.should.eql(user.id);
|
pp.userId.should.eql(user.id);
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
@ -91,8 +91,8 @@ describe('include', function () {
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
it('should fetch Passport - Owner - empty Posts', function (done) {
|
it('should fetch Passport - Owner - empty Posts', function(done) {
|
||||||
Passport.findOne({where: {number: '4'}, include: {owner: 'posts'}}, function (err, passport) {
|
Passport.findOne({ where: { number: '4' }, include: { owner: 'posts' }}, function(err, passport) {
|
||||||
should.not.exist(err);
|
should.not.exist(err);
|
||||||
should.exist(passport);
|
should.exist(passport);
|
||||||
passport.__cachedRelations.should.have.property('owner');
|
passport.__cachedRelations.should.have.property('owner');
|
||||||
|
@ -113,8 +113,8 @@ describe('include', function () {
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
it('should fetch Passport - Owner - Posts - alternate syntax', function (done) {
|
it('should fetch Passport - Owner - Posts - alternate syntax', function(done) {
|
||||||
Passport.find({include: {owner: {relation: 'posts'}}}, function (err, passports) {
|
Passport.find({ include: { owner: { relation: 'posts' }}}, function(err, passports) {
|
||||||
should.not.exist(err);
|
should.not.exist(err);
|
||||||
should.exist(passports);
|
should.exist(passports);
|
||||||
passports.length.should.be.ok;
|
passports.length.should.be.ok;
|
||||||
|
@ -124,14 +124,14 @@ describe('include', function () {
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
it('should fetch Passports - User - Posts - User', function (done) {
|
it('should fetch Passports - User - Posts - User', function(done) {
|
||||||
Passport.find({
|
Passport.find({
|
||||||
include: {owner: {posts: 'author'}}
|
include: { owner: { posts: 'author' }},
|
||||||
}, function (err, passports) {
|
}, function(err, passports) {
|
||||||
should.not.exist(err);
|
should.not.exist(err);
|
||||||
should.exist(passports);
|
should.exist(passports);
|
||||||
passports.length.should.be.ok;
|
passports.length.should.be.ok;
|
||||||
passports.forEach(function (p) {
|
passports.forEach(function(p) {
|
||||||
p.__cachedRelations.should.have.property('owner');
|
p.__cachedRelations.should.have.property('owner');
|
||||||
var user = p.__cachedRelations.owner;
|
var user = p.__cachedRelations.owner;
|
||||||
if (!p.ownerId) {
|
if (!p.ownerId) {
|
||||||
|
@ -140,7 +140,7 @@ describe('include', function () {
|
||||||
should.exist(user);
|
should.exist(user);
|
||||||
user.id.should.eql(p.ownerId);
|
user.id.should.eql(p.ownerId);
|
||||||
user.__cachedRelations.should.have.property('posts');
|
user.__cachedRelations.should.have.property('posts');
|
||||||
user.__cachedRelations.posts.forEach(function (pp) {
|
user.__cachedRelations.posts.forEach(function(pp) {
|
||||||
pp.should.have.property('id');
|
pp.should.have.property('id');
|
||||||
pp.userId.should.eql(user.id);
|
pp.userId.should.eql(user.id);
|
||||||
pp.should.have.property('author');
|
pp.should.have.property('author');
|
||||||
|
@ -154,13 +154,13 @@ describe('include', function () {
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
it('should fetch Passports with include scope on Posts', function (done) {
|
it('should fetch Passports with include scope on Posts', function(done) {
|
||||||
Passport.find({
|
Passport.find({
|
||||||
include: {owner: {relation: 'posts', scope:{
|
include: { owner: { relation: 'posts', scope:{
|
||||||
fields: ['title'], include: ['author'],
|
fields: ['title'], include: ['author'],
|
||||||
order: 'title DESC'
|
order: 'title DESC',
|
||||||
}}}
|
}}},
|
||||||
}, function (err, passports) {
|
}, function(err, passports) {
|
||||||
should.not.exist(err);
|
should.not.exist(err);
|
||||||
should.exist(passports);
|
should.exist(passports);
|
||||||
passports.length.should.equal(4);
|
passports.length.should.equal(4);
|
||||||
|
@ -196,11 +196,11 @@ describe('include', function () {
|
||||||
relation: 'posts', scope: {
|
relation: 'posts', scope: {
|
||||||
fields: ['title'], include: ['author'],
|
fields: ['title'], include: ['author'],
|
||||||
order: 'title DESC',
|
order: 'title DESC',
|
||||||
limit: 2
|
limit: 2,
|
||||||
}
|
},
|
||||||
}
|
},
|
||||||
},
|
},
|
||||||
limit: 1
|
limit: 1,
|
||||||
}, function(err, passports) {
|
}, function(err, passports) {
|
||||||
if (err) return done(err);
|
if (err) return done(err);
|
||||||
passports.length.should.equal(1);
|
passports.length.should.equal(1);
|
||||||
|
@ -209,29 +209,29 @@ describe('include', function () {
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
it('should fetch Users with include scope on Posts - belongsTo', function (done) {
|
it('should fetch Users with include scope on Posts - belongsTo', function(done) {
|
||||||
Post.find({
|
Post.find({
|
||||||
include: { relation: 'author', scope:{ fields: ['name'] }}
|
include: { relation: 'author', scope:{ fields: ['name'] }},
|
||||||
}, function (err, posts) {
|
}, function(err, posts) {
|
||||||
should.not.exist(err);
|
should.not.exist(err);
|
||||||
should.exist(posts);
|
should.exist(posts);
|
||||||
posts.length.should.equal(5);
|
posts.length.should.equal(5);
|
||||||
|
|
||||||
var author = posts[0].author();
|
var author = posts[0].author();
|
||||||
author.name.should.equal('User A');
|
author.name.should.equal('User A');
|
||||||
author.should.have.property('id');
|
author.should.have.property('id');
|
||||||
author.should.have.property('age', undefined);
|
author.should.have.property('age', undefined);
|
||||||
|
|
||||||
done();
|
done();
|
||||||
});
|
|
||||||
});
|
});
|
||||||
|
});
|
||||||
|
|
||||||
it('should fetch Users with include scope on Posts - hasMany', function (done) {
|
it('should fetch Users with include scope on Posts - hasMany', function(done) {
|
||||||
User.find({
|
User.find({
|
||||||
include: {relation: 'posts', scope:{
|
include: { relation: 'posts', scope:{
|
||||||
order: 'title DESC'
|
order: 'title DESC',
|
||||||
}}
|
}},
|
||||||
}, function (err, users) {
|
}, function(err, users) {
|
||||||
should.not.exist(err);
|
should.not.exist(err);
|
||||||
should.exist(users);
|
should.exist(users);
|
||||||
users.length.should.equal(5);
|
users.length.should.equal(5);
|
||||||
|
@ -256,12 +256,12 @@ describe('include', function () {
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
it('should fetch Users with include scope on Passports - hasMany', function (done) {
|
it('should fetch Users with include scope on Passports - hasMany', function(done) {
|
||||||
User.find({
|
User.find({
|
||||||
include: {relation: 'passports', scope:{
|
include: { relation: 'passports', scope:{
|
||||||
where: { number: '2' }
|
where: { number: '2' },
|
||||||
}}
|
}},
|
||||||
}, function (err, users) {
|
}, function(err, users) {
|
||||||
should.not.exist(err);
|
should.not.exist(err);
|
||||||
should.exist(users);
|
should.exist(users);
|
||||||
users.length.should.equal(5);
|
users.length.should.equal(5);
|
||||||
|
@ -277,12 +277,12 @@ describe('include', function () {
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
it('should fetch User - Posts AND Passports', function (done) {
|
it('should fetch User - Posts AND Passports', function(done) {
|
||||||
User.find({include: ['posts', 'passports']}, function (err, users) {
|
User.find({ include: ['posts', 'passports'] }, function(err, users) {
|
||||||
should.not.exist(err);
|
should.not.exist(err);
|
||||||
should.exist(users);
|
should.exist(users);
|
||||||
users.length.should.be.ok;
|
users.length.should.be.ok;
|
||||||
users.forEach(function (user) {
|
users.forEach(function(user) {
|
||||||
// The relation should be promoted as the 'owner' property
|
// The relation should be promoted as the 'owner' property
|
||||||
user.should.have.property('posts');
|
user.should.have.property('posts');
|
||||||
user.should.have.property('passports');
|
user.should.have.property('passports');
|
||||||
|
@ -298,10 +298,10 @@ describe('include', function () {
|
||||||
|
|
||||||
user.__cachedRelations.should.have.property('posts');
|
user.__cachedRelations.should.have.property('posts');
|
||||||
user.__cachedRelations.should.have.property('passports');
|
user.__cachedRelations.should.have.property('passports');
|
||||||
user.__cachedRelations.posts.forEach(function (p) {
|
user.__cachedRelations.posts.forEach(function(p) {
|
||||||
p.userId.should.eql(user.id);
|
p.userId.should.eql(user.id);
|
||||||
});
|
});
|
||||||
user.__cachedRelations.passports.forEach(function (pp) {
|
user.__cachedRelations.passports.forEach(function(pp) {
|
||||||
pp.ownerId.should.eql(user.id);
|
pp.ownerId.should.eql(user.id);
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
@ -311,12 +311,12 @@ describe('include', function () {
|
||||||
|
|
||||||
it('should fetch User - Posts AND Passports in relation syntax',
|
it('should fetch User - Posts AND Passports in relation syntax',
|
||||||
function(done) {
|
function(done) {
|
||||||
User.find({include: [
|
User.find({ include: [
|
||||||
{relation: 'posts', scope: {
|
{ relation: 'posts', scope: {
|
||||||
where: {title: 'Post A'}
|
where: { title: 'Post A' },
|
||||||
}},
|
}},
|
||||||
'passports'
|
'passports',
|
||||||
]}, function(err, users) {
|
] }, function(err, users) {
|
||||||
should.not.exist(err);
|
should.not.exist(err);
|
||||||
should.exist(users);
|
should.exist(users);
|
||||||
users.length.should.be.ok;
|
users.length.should.be.ok;
|
||||||
|
@ -348,12 +348,12 @@ describe('include', function () {
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
it('should not fetch User - AccessTokens', function (done) {
|
it('should not fetch User - AccessTokens', function(done) {
|
||||||
User.find({include: ['accesstokens']}, function (err, users) {
|
User.find({ include: ['accesstokens'] }, function(err, users) {
|
||||||
should.not.exist(err);
|
should.not.exist(err);
|
||||||
should.exist(users);
|
should.exist(users);
|
||||||
users.length.should.be.ok;
|
users.length.should.be.ok;
|
||||||
users.forEach(function (user) {
|
users.forEach(function(user) {
|
||||||
var userObj = user.toJSON();
|
var userObj = user.toJSON();
|
||||||
userObj.should.not.have.property('accesstokens');
|
userObj.should.not.have.property('accesstokens');
|
||||||
});
|
});
|
||||||
|
@ -361,20 +361,20 @@ describe('include', function () {
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
it('should support hasAndBelongsToMany', function (done) {
|
it('should support hasAndBelongsToMany', function(done) {
|
||||||
Assembly.create({name: 'car'}, function (err, assembly) {
|
Assembly.create({ name: 'car' }, function(err, assembly) {
|
||||||
Part.create({partNumber: 'engine'}, function (err, part) {
|
Part.create({ partNumber: 'engine' }, function(err, part) {
|
||||||
assembly.parts.add(part, function (err, data) {
|
assembly.parts.add(part, function(err, data) {
|
||||||
assembly.parts(function (err, parts) {
|
assembly.parts(function(err, parts) {
|
||||||
should.not.exist(err);
|
should.not.exist(err);
|
||||||
should.exists(parts);
|
should.exists(parts);
|
||||||
parts.length.should.equal(1);
|
parts.length.should.equal(1);
|
||||||
parts[0].partNumber.should.equal('engine');
|
parts[0].partNumber.should.equal('engine');
|
||||||
|
|
||||||
// Create a part
|
// Create a part
|
||||||
assembly.parts.create({partNumber: 'door'}, function (err, part4) {
|
assembly.parts.create({ partNumber: 'door' }, function(err, part4) {
|
||||||
|
|
||||||
Assembly.find({include: 'parts'}, function (err, assemblies) {
|
Assembly.find({ include: 'parts' }, function(err, assemblies) {
|
||||||
assemblies.length.should.equal(1);
|
assemblies.length.should.equal(1);
|
||||||
assemblies[0].parts().length.should.equal(2);
|
assemblies[0].parts().length.should.equal(2);
|
||||||
done();
|
done();
|
||||||
|
@ -387,13 +387,13 @@ describe('include', function () {
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
it('should fetch User - Profile (HasOne)', function (done) {
|
it('should fetch User - Profile (HasOne)', function(done) {
|
||||||
User.find({include: ['profile']}, function (err, users) {
|
User.find({ include: ['profile'] }, function(err, users) {
|
||||||
should.not.exist(err);
|
should.not.exist(err);
|
||||||
should.exist(users);
|
should.exist(users);
|
||||||
users.length.should.be.ok;
|
users.length.should.be.ok;
|
||||||
var usersWithProfile = 0;
|
var usersWithProfile = 0;
|
||||||
users.forEach(function (user) {
|
users.forEach(function(user) {
|
||||||
// The relation should be promoted as the 'owner' property
|
// The relation should be promoted as the 'owner' property
|
||||||
user.should.have.property('profile');
|
user.should.have.property('profile');
|
||||||
var userObj = user.toJSON();
|
var userObj = user.toJSON();
|
||||||
|
@ -421,10 +421,10 @@ describe('include', function () {
|
||||||
|
|
||||||
// Not implemented correctly, see: loopback-datasource-juggler/issues/166
|
// Not implemented correctly, see: loopback-datasource-juggler/issues/166
|
||||||
// fixed by DB optimization
|
// fixed by DB optimization
|
||||||
it('should support include scope on hasAndBelongsToMany', function (done) {
|
it('should support include scope on hasAndBelongsToMany', function(done) {
|
||||||
Assembly.find({include: { relation: 'parts', scope: {
|
Assembly.find({ include: { relation: 'parts', scope: {
|
||||||
where: { partNumber: 'engine' }
|
where: { partNumber: 'engine' },
|
||||||
}}}, function (err, assemblies) {
|
}}}, function(err, assemblies) {
|
||||||
assemblies.length.should.equal(1);
|
assemblies.length.should.equal(1);
|
||||||
var parts = assemblies[0].parts();
|
var parts = assemblies[0].parts();
|
||||||
parts.should.have.length(1);
|
parts.should.have.length(1);
|
||||||
|
@ -435,7 +435,7 @@ describe('include', function () {
|
||||||
|
|
||||||
it('should save related items separately', function(done) {
|
it('should save related items separately', function(done) {
|
||||||
User.find({
|
User.find({
|
||||||
include: 'posts'
|
include: 'posts',
|
||||||
})
|
})
|
||||||
.then(function(users) {
|
.then(function(users) {
|
||||||
var posts = users[0].posts();
|
var posts = users[0].posts();
|
||||||
|
@ -444,7 +444,7 @@ describe('include', function () {
|
||||||
})
|
})
|
||||||
.then(function(updatedUser) {
|
.then(function(updatedUser) {
|
||||||
return User.findById(updatedUser.id, {
|
return User.findById(updatedUser.id, {
|
||||||
include: 'posts'
|
include: 'posts',
|
||||||
});
|
});
|
||||||
})
|
})
|
||||||
.then(function(user) {
|
.then(function(user) {
|
||||||
|
@ -455,7 +455,7 @@ describe('include', function () {
|
||||||
.catch(done);
|
.catch(done);
|
||||||
});
|
});
|
||||||
|
|
||||||
describe('performance', function () {
|
describe('performance', function() {
|
||||||
var all;
|
var all;
|
||||||
beforeEach(function() {
|
beforeEach(function() {
|
||||||
this.called = 0;
|
this.called = 0;
|
||||||
|
@ -469,11 +469,11 @@ describe('include', function () {
|
||||||
afterEach(function() {
|
afterEach(function() {
|
||||||
db.connector.all = all;
|
db.connector.all = all;
|
||||||
});
|
});
|
||||||
it('including belongsTo should make only 2 db calls', function (done) {
|
it('including belongsTo should make only 2 db calls', function(done) {
|
||||||
var self = this;
|
var self = this;
|
||||||
Passport.find({include: 'owner'}, function (err, passports) {
|
Passport.find({ include: 'owner' }, function(err, passports) {
|
||||||
passports.length.should.be.ok;
|
passports.length.should.be.ok;
|
||||||
passports.forEach(function (p) {
|
passports.forEach(function(p) {
|
||||||
p.__cachedRelations.should.have.property('owner');
|
p.__cachedRelations.should.have.property('owner');
|
||||||
// The relation should be promoted as the 'owner' property
|
// The relation should be promoted as the 'owner' property
|
||||||
p.should.have.property('owner');
|
p.should.have.property('owner');
|
||||||
|
@ -492,16 +492,16 @@ describe('include', function () {
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
it('including hasManyThrough should make only 3 db calls', function (done) {
|
it('including hasManyThrough should make only 3 db calls', function(done) {
|
||||||
var self = this;
|
var self = this;
|
||||||
Assembly.create([{name: 'sedan'}, {name: 'hatchback'},
|
Assembly.create([{ name: 'sedan' }, { name: 'hatchback' },
|
||||||
{name: 'SUV'}],
|
{ name: 'SUV' }],
|
||||||
function (err, assemblies) {
|
function(err, assemblies) {
|
||||||
Part.create([{partNumber: 'engine'}, {partNumber: 'bootspace'},
|
Part.create([{ partNumber: 'engine' }, { partNumber: 'bootspace' },
|
||||||
{partNumber: 'silencer'}],
|
{ partNumber: 'silencer' }],
|
||||||
function (err, parts) {
|
function(err, parts) {
|
||||||
async.each(parts, function (part, next) {
|
async.each(parts, function(part, next) {
|
||||||
async.each(assemblies, function (assembly, next) {
|
async.each(assemblies, function(assembly, next) {
|
||||||
if (assembly.name === 'SUV') {
|
if (assembly.name === 'SUV') {
|
||||||
return next();
|
return next();
|
||||||
}
|
}
|
||||||
|
@ -509,20 +509,20 @@ describe('include', function () {
|
||||||
part.partNumber === 'bootspace') {
|
part.partNumber === 'bootspace') {
|
||||||
return next();
|
return next();
|
||||||
}
|
}
|
||||||
assembly.parts.add(part, function (err, data) {
|
assembly.parts.add(part, function(err, data) {
|
||||||
next();
|
next();
|
||||||
});
|
});
|
||||||
}, next);
|
}, next);
|
||||||
}, function (err) {
|
}, function(err) {
|
||||||
self.called = 0;
|
self.called = 0;
|
||||||
Assembly.find({
|
Assembly.find({
|
||||||
where: {
|
where: {
|
||||||
name: {
|
name: {
|
||||||
inq: ['sedan', 'hatchback', 'SUV']
|
inq: ['sedan', 'hatchback', 'SUV'],
|
||||||
}
|
},
|
||||||
},
|
},
|
||||||
include: 'parts'
|
include: 'parts',
|
||||||
}, function (err, result) {
|
}, function(err, result) {
|
||||||
should.not.exist(err);
|
should.not.exist(err);
|
||||||
should.exists(result);
|
should.exists(result);
|
||||||
result.length.should.equal(3);
|
result.length.should.equal(3);
|
||||||
|
@ -545,13 +545,13 @@ describe('include', function () {
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
it('including hasMany should make only 2 db calls', function (done) {
|
it('including hasMany should make only 2 db calls', function(done) {
|
||||||
var self = this;
|
var self = this;
|
||||||
User.find({include: ['posts', 'passports']}, function (err, users) {
|
User.find({ include: ['posts', 'passports'] }, function(err, users) {
|
||||||
should.not.exist(err);
|
should.not.exist(err);
|
||||||
should.exist(users);
|
should.exist(users);
|
||||||
users.length.should.be.ok;
|
users.length.should.be.ok;
|
||||||
users.forEach(function (user) {
|
users.forEach(function(user) {
|
||||||
// The relation should be promoted as the 'owner' property
|
// The relation should be promoted as the 'owner' property
|
||||||
user.should.have.property('posts');
|
user.should.have.property('posts');
|
||||||
user.should.have.property('passports');
|
user.should.have.property('passports');
|
||||||
|
@ -567,10 +567,10 @@ describe('include', function () {
|
||||||
|
|
||||||
user.__cachedRelations.should.have.property('posts');
|
user.__cachedRelations.should.have.property('posts');
|
||||||
user.__cachedRelations.should.have.property('passports');
|
user.__cachedRelations.should.have.property('passports');
|
||||||
user.__cachedRelations.posts.forEach(function (p) {
|
user.__cachedRelations.posts.forEach(function(p) {
|
||||||
p.userId.should.eql(user.id);
|
p.userId.should.eql(user.id);
|
||||||
});
|
});
|
||||||
user.__cachedRelations.passports.forEach(function (pp) {
|
user.__cachedRelations.passports.forEach(function(pp) {
|
||||||
pp.ownerId.should.eql(user.id);
|
pp.ownerId.should.eql(user.id);
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
@ -581,15 +581,15 @@ describe('include', function () {
|
||||||
|
|
||||||
|
|
||||||
it('should not make n+1 db calls in relation syntax',
|
it('should not make n+1 db calls in relation syntax',
|
||||||
function (done) {
|
function(done) {
|
||||||
var self = this;
|
var self = this;
|
||||||
User.find({include: [{ relation: 'posts', scope: {
|
User.find({ include: [{ relation: 'posts', scope: {
|
||||||
where: {title: 'Post A'}
|
where: { title: 'Post A' },
|
||||||
}}, 'passports']}, function (err, users) {
|
}}, 'passports'] }, function(err, users) {
|
||||||
should.not.exist(err);
|
should.not.exist(err);
|
||||||
should.exist(users);
|
should.exist(users);
|
||||||
users.length.should.be.ok;
|
users.length.should.be.ok;
|
||||||
users.forEach(function (user) {
|
users.forEach(function(user) {
|
||||||
// The relation should be promoted as the 'owner' property
|
// The relation should be promoted as the 'owner' property
|
||||||
user.should.have.property('posts');
|
user.should.have.property('posts');
|
||||||
user.should.have.property('passports');
|
user.should.have.property('passports');
|
||||||
|
@ -605,11 +605,11 @@ describe('include', function () {
|
||||||
|
|
||||||
user.__cachedRelations.should.have.property('posts');
|
user.__cachedRelations.should.have.property('posts');
|
||||||
user.__cachedRelations.should.have.property('passports');
|
user.__cachedRelations.should.have.property('passports');
|
||||||
user.__cachedRelations.posts.forEach(function (p) {
|
user.__cachedRelations.posts.forEach(function(p) {
|
||||||
p.userId.should.eql(user.id);
|
p.userId.should.eql(user.id);
|
||||||
p.title.should.be.equal('Post A');
|
p.title.should.be.equal('Post A');
|
||||||
});
|
});
|
||||||
user.__cachedRelations.passports.forEach(function (pp) {
|
user.__cachedRelations.passports.forEach(function(pp) {
|
||||||
pp.ownerId.should.eql(user.id);
|
pp.ownerId.should.eql(user.id);
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
@ -627,44 +627,44 @@ function setup(done) {
|
||||||
Building = db.define('Building');
|
Building = db.define('Building');
|
||||||
User = db.define('User', {
|
User = db.define('User', {
|
||||||
name: String,
|
name: String,
|
||||||
age: Number
|
age: Number,
|
||||||
});
|
});
|
||||||
Profile = db.define('Profile', {
|
Profile = db.define('Profile', {
|
||||||
profileName: String
|
profileName: String,
|
||||||
});
|
});
|
||||||
AccessToken = db.define('AccessToken', {
|
AccessToken = db.define('AccessToken', {
|
||||||
token: String
|
token: String,
|
||||||
});
|
});
|
||||||
Passport = db.define('Passport', {
|
Passport = db.define('Passport', {
|
||||||
number: String
|
number: String,
|
||||||
});
|
});
|
||||||
Post = db.define('Post', {
|
Post = db.define('Post', {
|
||||||
title: String
|
title: String,
|
||||||
});
|
});
|
||||||
|
|
||||||
Passport.belongsTo('owner', {model: User});
|
Passport.belongsTo('owner', { model: User });
|
||||||
User.hasMany('passports', {foreignKey: 'ownerId'});
|
User.hasMany('passports', { foreignKey: 'ownerId' });
|
||||||
User.hasMany('posts', {foreignKey: 'userId'});
|
User.hasMany('posts', { foreignKey: 'userId' });
|
||||||
User.hasMany('accesstokens', {
|
User.hasMany('accesstokens', {
|
||||||
foreignKey: 'userId',
|
foreignKey: 'userId',
|
||||||
options: {disableInclude: true}
|
options: { disableInclude: true },
|
||||||
});
|
});
|
||||||
Profile.belongsTo('user', {model: User});
|
Profile.belongsTo('user', { model: User });
|
||||||
User.hasOne('profile', {foreignKey: 'userId'});
|
User.hasOne('profile', { foreignKey: 'userId' });
|
||||||
Post.belongsTo('author', {model: User, foreignKey: 'userId'});
|
Post.belongsTo('author', { model: User, foreignKey: 'userId' });
|
||||||
|
|
||||||
Assembly = db.define('Assembly', {
|
Assembly = db.define('Assembly', {
|
||||||
name: String
|
name: String,
|
||||||
});
|
});
|
||||||
|
|
||||||
Part = db.define('Part', {
|
Part = db.define('Part', {
|
||||||
partNumber: String
|
partNumber: String,
|
||||||
});
|
});
|
||||||
|
|
||||||
Assembly.hasAndBelongsToMany(Part);
|
Assembly.hasAndBelongsToMany(Part);
|
||||||
Part.hasAndBelongsToMany(Assembly);
|
Part.hasAndBelongsToMany(Assembly);
|
||||||
|
|
||||||
db.automigrate(function () {
|
db.automigrate(function() {
|
||||||
var createdUsers = [];
|
var createdUsers = [];
|
||||||
var createdPassports = [];
|
var createdPassports = [];
|
||||||
var createdProfiles = [];
|
var createdProfiles = [];
|
||||||
|
@ -674,13 +674,13 @@ function setup(done) {
|
||||||
clearAndCreate(
|
clearAndCreate(
|
||||||
User,
|
User,
|
||||||
[
|
[
|
||||||
{name: 'User A', age: 21},
|
{ name: 'User A', age: 21 },
|
||||||
{name: 'User B', age: 22},
|
{ name: 'User B', age: 22 },
|
||||||
{name: 'User C', age: 23},
|
{ name: 'User C', age: 23 },
|
||||||
{name: 'User D', age: 24},
|
{ name: 'User D', age: 24 },
|
||||||
{name: 'User E', age: 25}
|
{ name: 'User E', age: 25 },
|
||||||
],
|
],
|
||||||
function (items) {
|
function(items) {
|
||||||
createdUsers = items;
|
createdUsers = items;
|
||||||
createPassports();
|
createPassports();
|
||||||
createAccessTokens();
|
createAccessTokens();
|
||||||
|
@ -692,10 +692,10 @@ function setup(done) {
|
||||||
clearAndCreate(
|
clearAndCreate(
|
||||||
AccessToken,
|
AccessToken,
|
||||||
[
|
[
|
||||||
{token: '1', userId: createdUsers[0].id},
|
{ token: '1', userId: createdUsers[0].id },
|
||||||
{token: '2', userId: createdUsers[1].id}
|
{ token: '2', userId: createdUsers[1].id },
|
||||||
],
|
],
|
||||||
function (items) {}
|
function(items) {}
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -703,12 +703,12 @@ function setup(done) {
|
||||||
clearAndCreate(
|
clearAndCreate(
|
||||||
Passport,
|
Passport,
|
||||||
[
|
[
|
||||||
{number: '1', ownerId: createdUsers[0].id},
|
{ number: '1', ownerId: createdUsers[0].id },
|
||||||
{number: '2', ownerId: createdUsers[1].id},
|
{ number: '2', ownerId: createdUsers[1].id },
|
||||||
{number: '3'},
|
{ number: '3' },
|
||||||
{number: '4', ownerId: createdUsers[2].id},
|
{ number: '4', ownerId: createdUsers[2].id },
|
||||||
],
|
],
|
||||||
function (items) {
|
function(items) {
|
||||||
createdPassports = items;
|
createdPassports = items;
|
||||||
createPosts();
|
createPosts();
|
||||||
}
|
}
|
||||||
|
@ -719,12 +719,12 @@ function setup(done) {
|
||||||
clearAndCreate(
|
clearAndCreate(
|
||||||
Profile,
|
Profile,
|
||||||
[
|
[
|
||||||
{profileName: 'Profile A', userId: createdUsers[0].id},
|
{ profileName: 'Profile A', userId: createdUsers[0].id },
|
||||||
{profileName: 'Profile B', userId: createdUsers[1].id},
|
{ profileName: 'Profile B', userId: createdUsers[1].id },
|
||||||
{profileName: 'Profile Z'}
|
{ profileName: 'Profile Z' },
|
||||||
],
|
],
|
||||||
function (items) {
|
function(items) {
|
||||||
createdProfiles = items
|
createdProfiles = items;
|
||||||
done();
|
done();
|
||||||
}
|
}
|
||||||
);
|
);
|
||||||
|
@ -734,13 +734,13 @@ function setup(done) {
|
||||||
clearAndCreate(
|
clearAndCreate(
|
||||||
Post,
|
Post,
|
||||||
[
|
[
|
||||||
{title: 'Post A', userId: createdUsers[0].id},
|
{ title: 'Post A', userId: createdUsers[0].id },
|
||||||
{title: 'Post B', userId: createdUsers[0].id},
|
{ title: 'Post B', userId: createdUsers[0].id },
|
||||||
{title: 'Post C', userId: createdUsers[0].id},
|
{ title: 'Post C', userId: createdUsers[0].id },
|
||||||
{title: 'Post D', userId: createdUsers[1].id},
|
{ title: 'Post D', userId: createdUsers[1].id },
|
||||||
{title: 'Post E'}
|
{ title: 'Post E' },
|
||||||
],
|
],
|
||||||
function (items) {
|
function(items) {
|
||||||
createdPosts = items;
|
createdPosts = items;
|
||||||
createProfiles();
|
createProfiles();
|
||||||
}
|
}
|
||||||
|
@ -752,7 +752,7 @@ function setup(done) {
|
||||||
|
|
||||||
function clearAndCreate(model, data, callback) {
|
function clearAndCreate(model, data, callback) {
|
||||||
var createdItems = [];
|
var createdItems = [];
|
||||||
model.destroyAll(function () {
|
model.destroyAll(function() {
|
||||||
nextItem(null, null);
|
nextItem(null, null);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
@ -775,38 +775,38 @@ describe('Model instance with included relation .toJSON()', function() {
|
||||||
var db, ChallengerModel, GameParticipationModel, ResultModel;
|
var db, ChallengerModel, GameParticipationModel, ResultModel;
|
||||||
|
|
||||||
before(function(done) {
|
before(function(done) {
|
||||||
db = new DataSource({connector: 'memory'});
|
db = new DataSource({ connector: 'memory' });
|
||||||
ChallengerModel = db.createModel('Challenger',
|
ChallengerModel = db.createModel('Challenger',
|
||||||
{
|
{
|
||||||
name: String
|
name: String,
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
relations: {
|
relations: {
|
||||||
gameParticipations: {
|
gameParticipations: {
|
||||||
type: 'hasMany',
|
type: 'hasMany',
|
||||||
model: 'GameParticipation',
|
model: 'GameParticipation',
|
||||||
foreignKey: ''
|
foreignKey: '',
|
||||||
}
|
},
|
||||||
}
|
},
|
||||||
}
|
}
|
||||||
);
|
);
|
||||||
GameParticipationModel = db.createModel('GameParticipation',
|
GameParticipationModel = db.createModel('GameParticipation',
|
||||||
{
|
{
|
||||||
date: Date
|
date: Date,
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
relations: {
|
relations: {
|
||||||
challenger: {
|
challenger: {
|
||||||
type: 'belongsTo',
|
type: 'belongsTo',
|
||||||
model: 'Challenger',
|
model: 'Challenger',
|
||||||
foreignKey: ''
|
foreignKey: '',
|
||||||
},
|
},
|
||||||
results: {
|
results: {
|
||||||
type: 'hasMany',
|
type: 'hasMany',
|
||||||
model: 'Result',
|
model: 'Result',
|
||||||
foreignKey: ''
|
foreignKey: '',
|
||||||
}
|
},
|
||||||
}
|
},
|
||||||
}
|
}
|
||||||
);
|
);
|
||||||
ResultModel = db.createModel('Result', {
|
ResultModel = db.createModel('Result', {
|
||||||
|
@ -816,9 +816,9 @@ describe('Model instance with included relation .toJSON()', function() {
|
||||||
gameParticipation: {
|
gameParticipation: {
|
||||||
type: 'belongsTo',
|
type: 'belongsTo',
|
||||||
model: 'GameParticipation',
|
model: 'GameParticipation',
|
||||||
foreignKey: ''
|
foreignKey: '',
|
||||||
}
|
},
|
||||||
}
|
},
|
||||||
});
|
});
|
||||||
|
|
||||||
async.waterfall([
|
async.waterfall([
|
||||||
|
@ -832,25 +832,25 @@ describe('Model instance with included relation .toJSON()', function() {
|
||||||
});
|
});
|
||||||
|
|
||||||
function createChallengers(callback) {
|
function createChallengers(callback) {
|
||||||
ChallengerModel.create([{name: 'challenger1'}, {name: 'challenger2'}], callback);
|
ChallengerModel.create([{ name: 'challenger1' }, { name: 'challenger2' }], callback);
|
||||||
}
|
}
|
||||||
|
|
||||||
function createGameParticipations(challengers, callback) {
|
function createGameParticipations(challengers, callback) {
|
||||||
GameParticipationModel.create([
|
GameParticipationModel.create([
|
||||||
{challengerId: challengers[0].id, date: Date.now()},
|
{ challengerId: challengers[0].id, date: Date.now() },
|
||||||
{challengerId: challengers[0].id, date: Date.now()}
|
{ challengerId: challengers[0].id, date: Date.now() },
|
||||||
], callback);
|
], callback);
|
||||||
}
|
}
|
||||||
|
|
||||||
function createResults(gameParticipations, callback) {
|
function createResults(gameParticipations, callback) {
|
||||||
ResultModel.create([
|
ResultModel.create([
|
||||||
{gameParticipationId: gameParticipations[0].id, points: 10},
|
{ gameParticipationId: gameParticipations[0].id, points: 10 },
|
||||||
{gameParticipationId: gameParticipations[0].id, points: 20}
|
{ gameParticipationId: gameParticipations[0].id, points: 20 },
|
||||||
], callback);
|
], callback);
|
||||||
}
|
}
|
||||||
|
|
||||||
it('should recursively serialize objects', function(done) {
|
it('should recursively serialize objects', function(done) {
|
||||||
var filter = {include: {gameParticipations: 'results'}};
|
var filter = { include: { gameParticipations: 'results' }};
|
||||||
ChallengerModel.find(filter, function(err, challengers) {
|
ChallengerModel.find(filter, function(err, challengers) {
|
||||||
|
|
||||||
var levelOneInclusion = challengers[0].toJSON().gameParticipations[0];
|
var levelOneInclusion = challengers[0].toJSON().gameParticipations[0];
|
||||||
|
|
|
@ -3,44 +3,44 @@
|
||||||
// This file is licensed under the MIT License.
|
// This file is licensed under the MIT License.
|
||||||
// License text available at https://opensource.org/licenses/MIT
|
// License text available at https://opensource.org/licenses/MIT
|
||||||
|
|
||||||
var assert = require("assert");
|
var assert = require('assert');
|
||||||
var should = require("should");
|
var should = require('should');
|
||||||
|
|
||||||
var includeUtils = require("../lib/include_utils");
|
var includeUtils = require('../lib/include_utils');
|
||||||
|
|
||||||
describe('include_util', function(){
|
describe('include_util', function() {
|
||||||
describe('#buildOneToOneIdentityMapWithOrigKeys', function(){
|
describe('#buildOneToOneIdentityMapWithOrigKeys', function() {
|
||||||
it('should return an object with keys', function(){
|
it('should return an object with keys', function() {
|
||||||
var objs = [
|
var objs = [
|
||||||
{id: 11, letter: "A"},
|
{ id: 11, letter: 'A' },
|
||||||
{id: 22, letter: "B"}
|
{ id: 22, letter: 'B' },
|
||||||
];
|
];
|
||||||
var result = includeUtils.buildOneToOneIdentityMapWithOrigKeys(objs, "id");
|
var result = includeUtils.buildOneToOneIdentityMapWithOrigKeys(objs, 'id');
|
||||||
result.get(11).should.be.ok;
|
result.get(11).should.be.ok;
|
||||||
result.get(22).should.be.ok;
|
result.get(22).should.be.ok;
|
||||||
});
|
});
|
||||||
|
|
||||||
it('should overwrite keys in case of collision', function(){
|
it('should overwrite keys in case of collision', function() {
|
||||||
var objs = [
|
var objs = [
|
||||||
{id: 11, letter: "A"},
|
{ id: 11, letter: 'A' },
|
||||||
{id: 22, letter: "B"},
|
{ id: 22, letter: 'B' },
|
||||||
{id: 33, letter: "C"},
|
{ id: 33, letter: 'C' },
|
||||||
{id: 11, letter: "HA!"}
|
{ id: 11, letter: 'HA!' },
|
||||||
];
|
];
|
||||||
|
|
||||||
var result = includeUtils.buildOneToOneIdentityMapWithOrigKeys(objs, "id");
|
var result = includeUtils.buildOneToOneIdentityMapWithOrigKeys(objs, 'id');
|
||||||
result.getKeys().should.containEql(11);
|
result.getKeys().should.containEql(11);
|
||||||
result.getKeys().should.containEql(22);
|
result.getKeys().should.containEql(22);
|
||||||
result.getKeys().should.containEql(33);
|
result.getKeys().should.containEql(33);
|
||||||
result.get(11)["letter"].should.equal("HA!");
|
result.get(11)['letter'].should.equal('HA!');
|
||||||
result.get(33)["letter"].should.equal("C");
|
result.get(33)['letter'].should.equal('C');
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
describe('#buildOneToOneIdentityMapWithOrigKeys', function(){
|
describe('#buildOneToOneIdentityMapWithOrigKeys', function() {
|
||||||
it('should return an object with keys', function(){
|
it('should return an object with keys', function() {
|
||||||
var objs = [
|
var objs = [
|
||||||
{id: 11, letter: "A"},
|
{ id: 11, letter: 'A' },
|
||||||
{id: 22, letter: "B"}
|
{ id: 22, letter: 'B' },
|
||||||
];
|
];
|
||||||
var result = includeUtils.buildOneToOneIdentityMapWithOrigKeys(objs, 'id');
|
var result = includeUtils.buildOneToOneIdentityMapWithOrigKeys(objs, 'id');
|
||||||
result.get(11).should.be.ok;
|
result.get(11).should.be.ok;
|
||||||
|
@ -48,36 +48,36 @@ describe('include_util', function(){
|
||||||
result.getKeys().should.have.lengthOf(2); // no additional properties
|
result.getKeys().should.have.lengthOf(2); // no additional properties
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
describe('#buildOneToManyIdentityMap', function(){
|
describe('#buildOneToManyIdentityMap', function() {
|
||||||
it('should return an object with keys', function(){
|
it('should return an object with keys', function() {
|
||||||
var objs = [
|
var objs = [
|
||||||
{id: 11, letter: "A"},
|
{ id: 11, letter: 'A' },
|
||||||
{id: 22, letter: "B"}
|
{ id: 22, letter: 'B' },
|
||||||
];
|
];
|
||||||
var result = includeUtils.buildOneToManyIdentityMapWithOrigKeys(objs, "id");
|
var result = includeUtils.buildOneToManyIdentityMapWithOrigKeys(objs, 'id');
|
||||||
result.exist(11).should.be.true;
|
result.exist(11).should.be.true;
|
||||||
result.exist(22).should.be.true;
|
result.exist(22).should.be.true;
|
||||||
});
|
|
||||||
|
|
||||||
it('should collect keys in case of collision', function(){
|
|
||||||
var objs = [
|
|
||||||
{fk_id: 11, letter: "A"},
|
|
||||||
{fk_id: 22, letter: "B"},
|
|
||||||
{fk_id: 33, letter: "C"},
|
|
||||||
{fk_id: 11, letter: "HA!"}
|
|
||||||
];
|
|
||||||
|
|
||||||
var result = includeUtils.buildOneToManyIdentityMapWithOrigKeys(objs, "fk_id");
|
|
||||||
result.get(11)[0]["letter"].should.equal("A");
|
|
||||||
result.get(11)[1]["letter"].should.equal("HA!");
|
|
||||||
result.get(33)[0]["letter"].should.equal("C");
|
|
||||||
});
|
|
||||||
});
|
});
|
||||||
|
|
||||||
|
it('should collect keys in case of collision', function() {
|
||||||
|
var objs = [
|
||||||
|
{ fk_id: 11, letter: 'A' },
|
||||||
|
{ fk_id: 22, letter: 'B' },
|
||||||
|
{ fk_id: 33, letter: 'C' },
|
||||||
|
{ fk_id: 11, letter: 'HA!' },
|
||||||
|
];
|
||||||
|
|
||||||
|
var result = includeUtils.buildOneToManyIdentityMapWithOrigKeys(objs, 'fk_id');
|
||||||
|
result.get(11)[0]['letter'].should.equal('A');
|
||||||
|
result.get(11)[1]['letter'].should.equal('HA!');
|
||||||
|
result.get(33)[0]['letter'].should.equal('C');
|
||||||
|
});
|
||||||
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
|
|
||||||
describe('KVMap', function(){
|
describe('KVMap', function() {
|
||||||
it('should allow to set and get value with key string', function(){
|
it('should allow to set and get value with key string', function() {
|
||||||
var map = new includeUtils.KVMap();
|
var map = new includeUtils.KVMap();
|
||||||
map.set('name', 'Alex');
|
map.set('name', 'Alex');
|
||||||
map.set('gender', true);
|
map.set('gender', true);
|
||||||
|
@ -86,23 +86,23 @@ describe('KVMap', function(){
|
||||||
map.get('gender').should.be.equal(true);
|
map.get('gender').should.be.equal(true);
|
||||||
map.get('age').should.be.equal(25);
|
map.get('age').should.be.equal(25);
|
||||||
});
|
});
|
||||||
it('should allow to set and get value with arbitrary key type', function(){
|
it('should allow to set and get value with arbitrary key type', function() {
|
||||||
var map = new includeUtils.KVMap();
|
var map = new includeUtils.KVMap();
|
||||||
map.set('name', 'Alex');
|
map.set('name', 'Alex');
|
||||||
map.set(true, 'male');
|
map.set(true, 'male');
|
||||||
map.set(false, false);
|
map.set(false, false);
|
||||||
map.set({isTrue: 'yes'}, 25);
|
map.set({ isTrue: 'yes' }, 25);
|
||||||
map.get('name').should.be.equal('Alex');
|
map.get('name').should.be.equal('Alex');
|
||||||
map.get(true).should.be.equal('male');
|
map.get(true).should.be.equal('male');
|
||||||
map.get(false).should.be.equal(false);
|
map.get(false).should.be.equal(false);
|
||||||
map.get({isTrue: 'yes'}).should.be.equal(25);
|
map.get({ isTrue: 'yes' }).should.be.equal(25);
|
||||||
});
|
});
|
||||||
it('should not allow to get values with [] operator', function(){
|
it('should not allow to get values with [] operator', function() {
|
||||||
var map = new includeUtils.KVMap();
|
var map = new includeUtils.KVMap();
|
||||||
map.set('name', 'Alex');
|
map.set('name', 'Alex');
|
||||||
(map['name'] === undefined).should.be.equal(true);
|
(map['name'] === undefined).should.be.equal(true);
|
||||||
});
|
});
|
||||||
it('should provide .exist() method for checking if key presented', function(){
|
it('should provide .exist() method for checking if key presented', function() {
|
||||||
var map = new includeUtils.KVMap();
|
var map = new includeUtils.KVMap();
|
||||||
map.set('one', 1);
|
map.set('one', 1);
|
||||||
map.set(2, 'two');
|
map.set(2, 'two');
|
||||||
|
@ -112,7 +112,7 @@ describe('KVMap', function(){
|
||||||
map.exist(true).should.be.true;
|
map.exist(true).should.be.true;
|
||||||
map.exist('two').should.be.false;
|
map.exist('two').should.be.false;
|
||||||
});
|
});
|
||||||
it('should return array of original keys with .getKeys()', function(){
|
it('should return array of original keys with .getKeys()', function() {
|
||||||
var map = new includeUtils.KVMap();
|
var map = new includeUtils.KVMap();
|
||||||
map.set('one', 1);
|
map.set('one', 1);
|
||||||
map.set(2, 'two');
|
map.set(2, 'two');
|
||||||
|
@ -122,7 +122,7 @@ describe('KVMap', function(){
|
||||||
keys.should.containEql(2);
|
keys.should.containEql(2);
|
||||||
keys.should.containEql(true);
|
keys.should.containEql(true);
|
||||||
});
|
});
|
||||||
it('should allow to store and fetch arrays', function(){
|
it('should allow to store and fetch arrays', function() {
|
||||||
var map = new includeUtils.KVMap();
|
var map = new includeUtils.KVMap();
|
||||||
map.set(1, [1, 2, 3]);
|
map.set(1, [1, 2, 3]);
|
||||||
map.set(2, [2, 3, 4]);
|
map.set(2, [2, 3, 4]);
|
||||||
|
|
|
@ -21,13 +21,13 @@ var ModelBuilder = require('../').ModelBuilder;
|
||||||
var Schema = require('../').Schema;
|
var Schema = require('../').Schema;
|
||||||
|
|
||||||
if (!('getSchema' in global)) {
|
if (!('getSchema' in global)) {
|
||||||
global.getSchema = function (connector, settings) {
|
global.getSchema = function(connector, settings) {
|
||||||
return new Schema(connector || 'memory', settings);
|
return new Schema(connector || 'memory', settings);
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
if (!('getModelBuilder' in global)) {
|
if (!('getModelBuilder' in global)) {
|
||||||
global.getModelBuilder = function () {
|
global.getModelBuilder = function() {
|
||||||
return new ModelBuilder();
|
return new ModelBuilder();
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
|
@ -19,19 +19,19 @@ var json = {
|
||||||
city: 'San Jose',
|
city: 'San Jose',
|
||||||
state: 'CA',
|
state: 'CA',
|
||||||
zipcode: '95131',
|
zipcode: '95131',
|
||||||
country: 'US'
|
country: 'US',
|
||||||
},
|
},
|
||||||
friends: ['John', 'Mary'],
|
friends: ['John', 'Mary'],
|
||||||
emails: [
|
emails: [
|
||||||
{label: 'work', id: 'x@sample.com'},
|
{ label: 'work', id: 'x@sample.com' },
|
||||||
{label: 'home', id: 'x@home.com'}
|
{ label: 'home', id: 'x@home.com' },
|
||||||
],
|
],
|
||||||
tags: []
|
tags: [],
|
||||||
};
|
};
|
||||||
|
|
||||||
describe('Introspection of model definitions from JSON', function () {
|
describe('Introspection of model definitions from JSON', function() {
|
||||||
|
|
||||||
it('should handle simple types', function () {
|
it('should handle simple types', function() {
|
||||||
assert.equal(introspectType('123'), 'string');
|
assert.equal(introspectType('123'), 'string');
|
||||||
assert.equal(introspectType(true), 'boolean');
|
assert.equal(introspectType(true), 'boolean');
|
||||||
assert.equal(introspectType(false), 'boolean');
|
assert.equal(introspectType(false), 'boolean');
|
||||||
|
@ -39,7 +39,7 @@ describe('Introspection of model definitions from JSON', function () {
|
||||||
assert.equal(introspectType(new Date()), 'date');
|
assert.equal(introspectType(new Date()), 'date');
|
||||||
});
|
});
|
||||||
|
|
||||||
it('should handle array types', function () {
|
it('should handle array types', function() {
|
||||||
var type = introspectType(['123']);
|
var type = introspectType(['123']);
|
||||||
assert.deepEqual(type, ['string'], 'type should be ["string"]');
|
assert.deepEqual(type, ['string'], 'type should be ["string"]');
|
||||||
type = introspectType([1]);
|
type = introspectType([1]);
|
||||||
|
@ -54,21 +54,21 @@ describe('Introspection of model definitions from JSON', function () {
|
||||||
assert.equal(type, 'array');
|
assert.equal(type, 'array');
|
||||||
});
|
});
|
||||||
|
|
||||||
it('should return Any for null or undefined', function () {
|
it('should return Any for null or undefined', function() {
|
||||||
assert.equal(introspectType(null), ModelBuilder.Any);
|
assert.equal(introspectType(null), ModelBuilder.Any);
|
||||||
assert.equal(introspectType(undefined), ModelBuilder.Any);
|
assert.equal(introspectType(undefined), ModelBuilder.Any);
|
||||||
});
|
});
|
||||||
|
|
||||||
it('should return a schema for object', function () {
|
it('should return a schema for object', function() {
|
||||||
var json = {a: 'str', b: 0, c: true};
|
var json = { a: 'str', b: 0, c: true };
|
||||||
var type = introspectType(json);
|
var type = introspectType(json);
|
||||||
assert.equal(type.a, 'string');
|
assert.equal(type.a, 'string');
|
||||||
assert.equal(type.b, 'number');
|
assert.equal(type.b, 'number');
|
||||||
assert.equal(type.c, 'boolean');
|
assert.equal(type.c, 'boolean');
|
||||||
});
|
});
|
||||||
|
|
||||||
it('should handle nesting objects', function () {
|
it('should handle nesting objects', function() {
|
||||||
var json = {a: 'str', b: 0, c: true, d: {x: 10, y: 5}};
|
var json = { a: 'str', b: 0, c: true, d: { x: 10, y: 5 }};
|
||||||
var type = introspectType(json);
|
var type = introspectType(json);
|
||||||
assert.equal(type.a, 'string');
|
assert.equal(type.a, 'string');
|
||||||
assert.equal(type.b, 'number');
|
assert.equal(type.b, 'number');
|
||||||
|
@ -77,8 +77,8 @@ describe('Introspection of model definitions from JSON', function () {
|
||||||
assert.equal(type.d.y, 'number');
|
assert.equal(type.d.y, 'number');
|
||||||
});
|
});
|
||||||
|
|
||||||
it('should handle nesting arrays', function () {
|
it('should handle nesting arrays', function() {
|
||||||
var json = {a: 'str', b: 0, c: true, d: [1, 2]};
|
var json = { a: 'str', b: 0, c: true, d: [1, 2] };
|
||||||
var type = introspectType(json);
|
var type = introspectType(json);
|
||||||
assert.equal(type.a, 'string');
|
assert.equal(type.a, 'string');
|
||||||
assert.equal(type.b, 'number');
|
assert.equal(type.b, 'number');
|
||||||
|
@ -86,13 +86,13 @@ describe('Introspection of model definitions from JSON', function () {
|
||||||
assert.deepEqual(type.d, ['number']);
|
assert.deepEqual(type.d, ['number']);
|
||||||
});
|
});
|
||||||
|
|
||||||
it('should build a model from the introspected schema', function (done) {
|
it('should build a model from the introspected schema', function(done) {
|
||||||
var copy = traverse(json).clone();
|
var copy = traverse(json).clone();
|
||||||
|
|
||||||
var schema = introspectType(json);
|
var schema = introspectType(json);
|
||||||
|
|
||||||
var builder = new ModelBuilder();
|
var builder = new ModelBuilder();
|
||||||
var Model = builder.define('MyModel', schema, {idInjection: false});
|
var Model = builder.define('MyModel', schema, { idInjection: false });
|
||||||
|
|
||||||
// FIXME: [rfeng] The constructor mutates the arguments
|
// FIXME: [rfeng] The constructor mutates the arguments
|
||||||
var obj = new Model(json);
|
var obj = new Model(json);
|
||||||
|
@ -103,11 +103,11 @@ describe('Introspection of model definitions from JSON', function () {
|
||||||
done();
|
done();
|
||||||
});
|
});
|
||||||
|
|
||||||
it('should build a model using buildModelFromInstance', function (done) {
|
it('should build a model using buildModelFromInstance', function(done) {
|
||||||
var copy = traverse(json).clone();
|
var copy = traverse(json).clone();
|
||||||
|
|
||||||
var builder = new ModelBuilder();
|
var builder = new ModelBuilder();
|
||||||
var Model = builder.buildModelFromInstance('MyModel', copy, {idInjection: false});
|
var Model = builder.buildModelFromInstance('MyModel', copy, { idInjection: false });
|
||||||
|
|
||||||
var obj = new Model(json);
|
var obj = new Model(json);
|
||||||
obj = obj.toObject();
|
obj = obj.toObject();
|
||||||
|
@ -115,12 +115,12 @@ describe('Introspection of model definitions from JSON', function () {
|
||||||
done();
|
done();
|
||||||
});
|
});
|
||||||
|
|
||||||
it('should build a model using DataSource.buildModelFromInstance', function (done) {
|
it('should build a model using DataSource.buildModelFromInstance', function(done) {
|
||||||
var copy = traverse(json).clone();
|
var copy = traverse(json).clone();
|
||||||
|
|
||||||
var builder = new DataSource('memory');
|
var builder = new DataSource('memory');
|
||||||
var Model = builder.buildModelFromInstance('MyModel', copy,
|
var Model = builder.buildModelFromInstance('MyModel', copy,
|
||||||
{idInjection: false});
|
{ idInjection: false });
|
||||||
|
|
||||||
assert.equal(Model.dataSource, builder);
|
assert.equal(Model.dataSource, builder);
|
||||||
|
|
||||||
|
|
|
@ -9,33 +9,33 @@ var should = require('./init.js');
|
||||||
var Schema = require('../').Schema;
|
var Schema = require('../').Schema;
|
||||||
var ModelBuilder = require('../').ModelBuilder;
|
var ModelBuilder = require('../').ModelBuilder;
|
||||||
|
|
||||||
describe('JSON property', function () {
|
describe('JSON property', function() {
|
||||||
var dataSource, Model;
|
var dataSource, Model;
|
||||||
|
|
||||||
it('should be defined', function () {
|
it('should be defined', function() {
|
||||||
dataSource = getSchema();
|
dataSource = getSchema();
|
||||||
Model = dataSource.define('Model', {propertyName: ModelBuilder.JSON});
|
Model = dataSource.define('Model', { propertyName: ModelBuilder.JSON });
|
||||||
var m = new Model;
|
var m = new Model;
|
||||||
(new Boolean('propertyName' in m)).should.eql(true);
|
(new Boolean('propertyName' in m)).should.eql(true);
|
||||||
should.not.exist(m.propertyName);
|
should.not.exist(m.propertyName);
|
||||||
});
|
});
|
||||||
|
|
||||||
it('should accept JSON in constructor and return object', function () {
|
it('should accept JSON in constructor and return object', function() {
|
||||||
var m = new Model({
|
var m = new Model({
|
||||||
propertyName: '{"foo": "bar"}'
|
propertyName: '{"foo": "bar"}',
|
||||||
});
|
});
|
||||||
m.propertyName.should.be.an.Object;
|
m.propertyName.should.be.an.Object;
|
||||||
m.propertyName.foo.should.equal('bar');
|
m.propertyName.foo.should.equal('bar');
|
||||||
});
|
});
|
||||||
|
|
||||||
it('should accept object in setter and return object', function () {
|
it('should accept object in setter and return object', function() {
|
||||||
var m = new Model;
|
var m = new Model;
|
||||||
m.propertyName = {"foo": "bar"};
|
m.propertyName = { 'foo': 'bar' };
|
||||||
m.propertyName.should.be.an.Object;
|
m.propertyName.should.be.an.Object;
|
||||||
m.propertyName.foo.should.equal('bar');
|
m.propertyName.foo.should.equal('bar');
|
||||||
});
|
});
|
||||||
|
|
||||||
it('should accept string in setter and return string', function () {
|
it('should accept string in setter and return string', function() {
|
||||||
var m = new Model;
|
var m = new Model;
|
||||||
m.propertyName = '{"foo": "bar"}';
|
m.propertyName = '{"foo": "bar"}';
|
||||||
m.propertyName.should.be.a.String;
|
m.propertyName.should.be.a.String;
|
||||||
|
|
|
@ -8,8 +8,8 @@ var should = require('./init.js');
|
||||||
|
|
||||||
var loopbackData = require('../');
|
var loopbackData = require('../');
|
||||||
|
|
||||||
describe('loopback-datasource-juggler', function () {
|
describe('loopback-datasource-juggler', function() {
|
||||||
it('should expose version', function () {
|
it('should expose version', function() {
|
||||||
loopbackData.version.should.equal(require('../package.json').version);
|
loopbackData.version.should.equal(require('../package.json').version);
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
|
@ -36,20 +36,20 @@ describe('Memory connector', function() {
|
||||||
function createUserModel() {
|
function createUserModel() {
|
||||||
var ds = new DataSource({
|
var ds = new DataSource({
|
||||||
connector: 'memory',
|
connector: 'memory',
|
||||||
file: file
|
file: file,
|
||||||
});
|
});
|
||||||
|
|
||||||
var User = ds.createModel('User', {
|
var User = ds.createModel('User', {
|
||||||
id: {
|
id: {
|
||||||
type: Number,
|
type: Number,
|
||||||
id: true,
|
id: true,
|
||||||
generated: true
|
generated: true,
|
||||||
},
|
},
|
||||||
name: String,
|
name: String,
|
||||||
bio: String,
|
bio: String,
|
||||||
approved: Boolean,
|
approved: Boolean,
|
||||||
joinedAt: Date,
|
joinedAt: Date,
|
||||||
age: Number
|
age: Number,
|
||||||
});
|
});
|
||||||
return User;
|
return User;
|
||||||
}
|
}
|
||||||
|
@ -64,7 +64,7 @@ describe('Memory connector', function() {
|
||||||
it('should persist create', function(done) {
|
it('should persist create', function(done) {
|
||||||
var count = 0;
|
var count = 0;
|
||||||
async.eachSeries(['John1', 'John2', 'John3'], function(item, cb) {
|
async.eachSeries(['John1', 'John2', 'John3'], function(item, cb) {
|
||||||
User.create({name: item}, function(err, result) {
|
User.create({ name: item }, function(err, result) {
|
||||||
ids.push(result.id);
|
ids.push(result.id);
|
||||||
count++;
|
count++;
|
||||||
readModels(function(err, json) {
|
readModels(function(err, json) {
|
||||||
|
@ -92,7 +92,7 @@ describe('Memory connector', function() {
|
||||||
});
|
});
|
||||||
|
|
||||||
it('should persist upsert', function(done) {
|
it('should persist upsert', function(done) {
|
||||||
User.upsert({id: ids[1], name: 'John'}, function(err, result) {
|
User.upsert({ id: ids[1], name: 'John' }, function(err, result) {
|
||||||
if (err) {
|
if (err) {
|
||||||
return done(err);
|
return done(err);
|
||||||
}
|
}
|
||||||
|
@ -110,7 +110,7 @@ describe('Memory connector', function() {
|
||||||
});
|
});
|
||||||
|
|
||||||
it('should persist update', function(done) {
|
it('should persist update', function(done) {
|
||||||
User.update({id: ids[1]}, {name: 'John1'},
|
User.update({ id: ids[1] }, { name: 'John1' },
|
||||||
function(err, result) {
|
function(err, result) {
|
||||||
if (err) {
|
if (err) {
|
||||||
return done(err);
|
return done(err);
|
||||||
|
@ -141,33 +141,33 @@ describe('Memory connector', function() {
|
||||||
|
|
||||||
describe('Query for memory connector', function() {
|
describe('Query for memory connector', function() {
|
||||||
var ds = new DataSource({
|
var ds = new DataSource({
|
||||||
connector: 'memory'
|
connector: 'memory',
|
||||||
});
|
});
|
||||||
|
|
||||||
var User = ds.define('User', {
|
var User = ds.define('User', {
|
||||||
seq: {type: Number, index: true},
|
seq: { type: Number, index: true },
|
||||||
name: {type: String, index: true, sort: true},
|
name: { type: String, index: true, sort: true },
|
||||||
email: {type: String, index: true},
|
email: { type: String, index: true },
|
||||||
birthday: {type: Date, index: true},
|
birthday: { type: Date, index: true },
|
||||||
role: {type: String, index: true},
|
role: { type: String, index: true },
|
||||||
order: {type: Number, index: true, sort: true},
|
order: { type: Number, index: true, sort: true },
|
||||||
vip: {type: Boolean},
|
vip: { type: Boolean },
|
||||||
address: {
|
address: {
|
||||||
street: String,
|
street: String,
|
||||||
city: String,
|
city: String,
|
||||||
state: String,
|
state: String,
|
||||||
zipCode: String
|
zipCode: String,
|
||||||
},
|
},
|
||||||
friends: [
|
friends: [
|
||||||
{
|
{
|
||||||
name: String
|
name: String,
|
||||||
}
|
},
|
||||||
]
|
],
|
||||||
});
|
});
|
||||||
|
|
||||||
before(seed);
|
before(seed);
|
||||||
it('should allow to find using like', function(done) {
|
it('should allow to find using like', function(done) {
|
||||||
User.find({where: {name: {like: '%St%'}}}, function(err, posts) {
|
User.find({ where: { name: { like: '%St%' }}}, function(err, posts) {
|
||||||
should.not.exist(err);
|
should.not.exist(err);
|
||||||
posts.should.have.property('length', 2);
|
posts.should.have.property('length', 2);
|
||||||
done();
|
done();
|
||||||
|
@ -175,7 +175,7 @@ describe('Memory connector', function() {
|
||||||
});
|
});
|
||||||
|
|
||||||
it('should allow to find using like with regexp', function(done) {
|
it('should allow to find using like with regexp', function(done) {
|
||||||
User.find({where: {name: {like: /.*St.*/}}}, function(err, posts) {
|
User.find({ where: { name: { like: /.*St.*/ }}}, function(err, posts) {
|
||||||
should.not.exist(err);
|
should.not.exist(err);
|
||||||
posts.should.have.property('length', 2);
|
posts.should.have.property('length', 2);
|
||||||
done();
|
done();
|
||||||
|
@ -183,7 +183,7 @@ describe('Memory connector', function() {
|
||||||
});
|
});
|
||||||
|
|
||||||
it('should support like for no match', function(done) {
|
it('should support like for no match', function(done) {
|
||||||
User.find({where: {name: {like: 'M%XY'}}}, function(err, posts) {
|
User.find({ where: { name: { like: 'M%XY' }}}, function(err, posts) {
|
||||||
should.not.exist(err);
|
should.not.exist(err);
|
||||||
posts.should.have.property('length', 0);
|
posts.should.have.property('length', 0);
|
||||||
done();
|
done();
|
||||||
|
@ -191,7 +191,7 @@ describe('Memory connector', function() {
|
||||||
});
|
});
|
||||||
|
|
||||||
it('should allow to find using nlike', function(done) {
|
it('should allow to find using nlike', function(done) {
|
||||||
User.find({where: {name: {nlike: '%St%'}}}, function(err, posts) {
|
User.find({ where: { name: { nlike: '%St%' }}}, function(err, posts) {
|
||||||
should.not.exist(err);
|
should.not.exist(err);
|
||||||
posts.should.have.property('length', 4);
|
posts.should.have.property('length', 4);
|
||||||
done();
|
done();
|
||||||
|
@ -199,7 +199,7 @@ describe('Memory connector', function() {
|
||||||
});
|
});
|
||||||
|
|
||||||
it('should allow to find using nlike with regexp', function(done) {
|
it('should allow to find using nlike with regexp', function(done) {
|
||||||
User.find({where: {name: {nlike: /.*St.*/}}}, function(err, posts) {
|
User.find({ where: { name: { nlike: /.*St.*/ }}}, function(err, posts) {
|
||||||
should.not.exist(err);
|
should.not.exist(err);
|
||||||
posts.should.have.property('length', 4);
|
posts.should.have.property('length', 4);
|
||||||
done();
|
done();
|
||||||
|
@ -207,7 +207,7 @@ describe('Memory connector', function() {
|
||||||
});
|
});
|
||||||
|
|
||||||
it('should support nlike for no match', function(done) {
|
it('should support nlike for no match', function(done) {
|
||||||
User.find({where: {name: {nlike: 'M%XY'}}}, function(err, posts) {
|
User.find({ where: { name: { nlike: 'M%XY' }}}, function(err, posts) {
|
||||||
should.not.exist(err);
|
should.not.exist(err);
|
||||||
posts.should.have.property('length', 6);
|
posts.should.have.property('length', 6);
|
||||||
done();
|
done();
|
||||||
|
@ -215,73 +215,73 @@ describe('Memory connector', function() {
|
||||||
});
|
});
|
||||||
|
|
||||||
it('should throw if the like value is not string or regexp', function(done) {
|
it('should throw if the like value is not string or regexp', function(done) {
|
||||||
User.find({where: {name: {like: 123}}}, function(err, posts) {
|
User.find({ where: { name: { like: 123 }}}, function(err, posts) {
|
||||||
should.exist(err);
|
should.exist(err);
|
||||||
done();
|
done();
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
it('should throw if the nlike value is not string or regexp', function(done) {
|
it('should throw if the nlike value is not string or regexp', function(done) {
|
||||||
User.find({where: {name: {nlike: 123}}}, function(err, posts) {
|
User.find({ where: { name: { nlike: 123 }}}, function(err, posts) {
|
||||||
should.exist(err);
|
should.exist(err);
|
||||||
done();
|
done();
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
it('should throw if the inq value is not an array', function(done) {
|
it('should throw if the inq value is not an array', function(done) {
|
||||||
User.find({where: {name: {inq: '12'}}}, function(err, posts) {
|
User.find({ where: { name: { inq: '12' }}}, function(err, posts) {
|
||||||
should.exist(err);
|
should.exist(err);
|
||||||
done();
|
done();
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
it('should throw if the nin value is not an array', function(done) {
|
it('should throw if the nin value is not an array', function(done) {
|
||||||
User.find({where: {name: {nin: '12'}}}, function(err, posts) {
|
User.find({ where: { name: { nin: '12' }}}, function(err, posts) {
|
||||||
should.exist(err);
|
should.exist(err);
|
||||||
done();
|
done();
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
it('should throw if the between value is not an array', function(done) {
|
it('should throw if the between value is not an array', function(done) {
|
||||||
User.find({where: {name: {between: '12'}}}, function(err, posts) {
|
User.find({ where: { name: { between: '12' }}}, function(err, posts) {
|
||||||
should.exist(err);
|
should.exist(err);
|
||||||
done();
|
done();
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
it('should throw if the between value is not an array of length 2', function(done) {
|
it('should throw if the between value is not an array of length 2', function(done) {
|
||||||
User.find({where: {name: {between: ['12']}}}, function(err, posts) {
|
User.find({ where: { name: { between: ['12'] }}}, function(err, posts) {
|
||||||
should.exist(err);
|
should.exist(err);
|
||||||
done();
|
done();
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
it('should successfully extract 5 users from the db', function(done) {
|
it('should successfully extract 5 users from the db', function(done) {
|
||||||
User.find({where: {seq: {between: [1,5]}}}, function(err, users) {
|
User.find({ where: { seq: { between: [1, 5] }}}, function(err, users) {
|
||||||
should(users.length).be.equal(5);
|
should(users.length).be.equal(5);
|
||||||
done();
|
done();
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
it('should successfully extract 1 user (Lennon) from the db', function(done) {
|
it('should successfully extract 1 user (Lennon) from the db', function(done) {
|
||||||
User.find({where: {birthday: {between: [new Date(1970,0),new Date(1990,0)]}}},
|
User.find({ where: { birthday: { between: [new Date(1970, 0), new Date(1990, 0)] }}},
|
||||||
function(err, users) {
|
function(err, users) {
|
||||||
should(users.length).be.equal(1);
|
should(users.length).be.equal(1);
|
||||||
should(users[0].name).be.equal('John Lennon');
|
should(users[0].name).be.equal('John Lennon');
|
||||||
done();
|
done();
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
it('should successfully extract 2 users from the db', function(done) {
|
it('should successfully extract 2 users from the db', function(done) {
|
||||||
User.find({where: {birthday: {between: [new Date(1940,0),new Date(1990,0)]}}},
|
User.find({ where: { birthday: { between: [new Date(1940, 0), new Date(1990, 0)] }}},
|
||||||
function(err, users) {
|
function(err, users) {
|
||||||
should(users.length).be.equal(2);
|
should(users.length).be.equal(2);
|
||||||
done();
|
done();
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
it('should successfully extract 2 users using implied and', function(done) {
|
it('should successfully extract 2 users using implied and', function(done) {
|
||||||
User.find({where: {role:'lead', vip:true}}, function(err, users) {
|
User.find({ where: { role:'lead', vip:true }}, function(err, users) {
|
||||||
should(users.length).be.equal(2);
|
should(users.length).be.equal(2);
|
||||||
should(users[0].name).be.equal('John Lennon');
|
should(users[0].name).be.equal('John Lennon');
|
||||||
should(users[1].name).be.equal('Paul McCartney');
|
should(users[1].name).be.equal('Paul McCartney');
|
||||||
|
@ -290,7 +290,7 @@ describe('Memory connector', function() {
|
||||||
});
|
});
|
||||||
|
|
||||||
it('should successfully extract 2 users using implied and & and', function(done) {
|
it('should successfully extract 2 users using implied and & and', function(done) {
|
||||||
User.find({where: { name: 'John Lennon',and: [{role:'lead'}, {vip:true}]}}, function(err, users) {
|
User.find({ where: { name: 'John Lennon', and: [{ role:'lead' }, { vip:true }] }}, function(err, users) {
|
||||||
should(users.length).be.equal(1);
|
should(users.length).be.equal(1);
|
||||||
should(users[0].name).be.equal('John Lennon');
|
should(users[0].name).be.equal('John Lennon');
|
||||||
done();
|
done();
|
||||||
|
@ -298,8 +298,8 @@ describe('Memory connector', function() {
|
||||||
});
|
});
|
||||||
|
|
||||||
it('should successfully extract 2 users using date range', function(done) {
|
it('should successfully extract 2 users using date range', function(done) {
|
||||||
User.find({where: {birthday: {between:
|
User.find({ where: { birthday: { between:
|
||||||
[new Date(1940, 0).toISOString(), new Date(1990, 0).toISOString()]}}},
|
[new Date(1940, 0).toISOString(), new Date(1990, 0).toISOString()] }}},
|
||||||
function(err, users) {
|
function(err, users) {
|
||||||
should(users.length).be.equal(2);
|
should(users.length).be.equal(2);
|
||||||
done();
|
done();
|
||||||
|
@ -307,21 +307,21 @@ describe('Memory connector', function() {
|
||||||
});
|
});
|
||||||
|
|
||||||
it('should successfully extract 0 user from the db', function(done) {
|
it('should successfully extract 0 user from the db', function(done) {
|
||||||
User.find({where: {birthday: {between: [new Date(1990,0), Date.now()]}}},
|
User.find({ where: { birthday: { between: [new Date(1990, 0), Date.now()] }}},
|
||||||
function(err, users) {
|
function(err, users) {
|
||||||
should(users.length).be.equal(0);
|
should(users.length).be.equal(0);
|
||||||
done();
|
done();
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
it('should successfully extract 2 users matching over array values', function (done) {
|
it('should successfully extract 2 users matching over array values', function(done) {
|
||||||
User.find({
|
User.find({
|
||||||
where: {
|
where: {
|
||||||
children: {
|
children: {
|
||||||
regexp: /an/
|
regexp: /an/,
|
||||||
}
|
},
|
||||||
}
|
},
|
||||||
}, function (err, users) {
|
}, function(err, users) {
|
||||||
should.not.exist(err);
|
should.not.exist(err);
|
||||||
users.length.should.be.equal(2);
|
users.length.should.be.equal(2);
|
||||||
users[0].name.should.be.equal('John Lennon');
|
users[0].name.should.be.equal('John Lennon');
|
||||||
|
@ -330,12 +330,12 @@ describe('Memory connector', function() {
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
it('should successfully extract 1 users matching over array values', function (done) {
|
it('should successfully extract 1 users matching over array values', function(done) {
|
||||||
User.find({
|
User.find({
|
||||||
where: {
|
where: {
|
||||||
children: 'Dhani'
|
children: 'Dhani',
|
||||||
}
|
},
|
||||||
}, function (err, users) {
|
}, function(err, users) {
|
||||||
should.not.exist(err);
|
should.not.exist(err);
|
||||||
users.length.should.be.equal(1);
|
users.length.should.be.equal(1);
|
||||||
users[0].name.should.be.equal('George Harrison');
|
users[0].name.should.be.equal('George Harrison');
|
||||||
|
@ -343,12 +343,12 @@ describe('Memory connector', function() {
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
it('should successfully extract 5 users matching a neq filter over array values', function (done) {
|
it('should successfully extract 5 users matching a neq filter over array values', function(done) {
|
||||||
User.find({
|
User.find({
|
||||||
where: {
|
where: {
|
||||||
'children': {neq: 'Dhani'}
|
'children': { neq: 'Dhani' },
|
||||||
}
|
},
|
||||||
}, function (err, users) {
|
}, function(err, users) {
|
||||||
should.not.exist(err);
|
should.not.exist(err);
|
||||||
users.length.should.be.equal(5);
|
users.length.should.be.equal(5);
|
||||||
done();
|
done();
|
||||||
|
@ -356,7 +356,7 @@ describe('Memory connector', function() {
|
||||||
});
|
});
|
||||||
|
|
||||||
it('should count using date string', function(done) {
|
it('should count using date string', function(done) {
|
||||||
User.count({birthday: {lt: new Date(1990,0).toISOString()}},
|
User.count({ birthday: { lt: new Date(1990, 0).toISOString() }},
|
||||||
function(err, count) {
|
function(err, count) {
|
||||||
should(count).be.equal(2);
|
should(count).be.equal(2);
|
||||||
done();
|
done();
|
||||||
|
@ -364,7 +364,7 @@ describe('Memory connector', function() {
|
||||||
});
|
});
|
||||||
|
|
||||||
it('should support order with multiple fields', function(done) {
|
it('should support order with multiple fields', function(done) {
|
||||||
User.find({order: 'vip ASC, seq DESC'}, function(err, posts) {
|
User.find({ order: 'vip ASC, seq DESC' }, function(err, posts) {
|
||||||
should.not.exist(err);
|
should.not.exist(err);
|
||||||
posts[0].seq.should.be.eql(4);
|
posts[0].seq.should.be.eql(4);
|
||||||
posts[1].seq.should.be.eql(3);
|
posts[1].seq.should.be.eql(3);
|
||||||
|
@ -373,7 +373,7 @@ describe('Memory connector', function() {
|
||||||
});
|
});
|
||||||
|
|
||||||
it('should sort undefined values to the end when ordered DESC', function(done) {
|
it('should sort undefined values to the end when ordered DESC', function(done) {
|
||||||
User.find({order: 'vip ASC, order DESC'}, function(err, posts) {
|
User.find({ order: 'vip ASC, order DESC' }, function(err, posts) {
|
||||||
should.not.exist(err);
|
should.not.exist(err);
|
||||||
|
|
||||||
posts[4].seq.should.be.eql(1);
|
posts[4].seq.should.be.eql(1);
|
||||||
|
@ -383,14 +383,14 @@ describe('Memory connector', function() {
|
||||||
});
|
});
|
||||||
|
|
||||||
it('should throw if order has wrong direction', function(done) {
|
it('should throw if order has wrong direction', function(done) {
|
||||||
User.find({order: 'seq ABC'}, function(err, posts) {
|
User.find({ order: 'seq ABC' }, function(err, posts) {
|
||||||
should.exist(err);
|
should.exist(err);
|
||||||
done();
|
done();
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
it('should support neq operator for number', function(done) {
|
it('should support neq operator for number', function(done) {
|
||||||
User.find({where: {seq: {neq: 4}}}, function(err, users) {
|
User.find({ where: { seq: { neq: 4 }}}, function(err, users) {
|
||||||
should.not.exist(err);
|
should.not.exist(err);
|
||||||
users.length.should.be.equal(5);
|
users.length.should.be.equal(5);
|
||||||
for (var i = 0; i < users.length; i++) {
|
for (var i = 0; i < users.length; i++) {
|
||||||
|
@ -401,7 +401,7 @@ describe('Memory connector', function() {
|
||||||
});
|
});
|
||||||
|
|
||||||
it('should support neq operator for string', function(done) {
|
it('should support neq operator for string', function(done) {
|
||||||
User.find({where: {role: {neq: 'lead'}}}, function(err, users) {
|
User.find({ where: { role: { neq: 'lead' }}}, function(err, users) {
|
||||||
should.not.exist(err);
|
should.not.exist(err);
|
||||||
users.length.should.be.equal(4);
|
users.length.should.be.equal(4);
|
||||||
for (var i = 0; i < users.length; i++) {
|
for (var i = 0; i < users.length; i++) {
|
||||||
|
@ -414,7 +414,7 @@ describe('Memory connector', function() {
|
||||||
});
|
});
|
||||||
|
|
||||||
it('should support neq operator for null', function(done) {
|
it('should support neq operator for null', function(done) {
|
||||||
User.find({where: {role: {neq: null}}}, function(err, users) {
|
User.find({ where: { role: { neq: null }}}, function(err, users) {
|
||||||
should.not.exist(err);
|
should.not.exist(err);
|
||||||
users.length.should.be.equal(2);
|
users.length.should.be.equal(2);
|
||||||
for (var i = 0; i < users.length; i++) {
|
for (var i = 0; i < users.length; i++) {
|
||||||
|
@ -426,16 +426,16 @@ describe('Memory connector', function() {
|
||||||
|
|
||||||
it('should work when a regex is provided without the regexp operator',
|
it('should work when a regex is provided without the regexp operator',
|
||||||
function(done) {
|
function(done) {
|
||||||
User.find({where: {name: /John.*/i}}, function(err, users) {
|
User.find({ where: { name: /John.*/i }}, function(err, users) {
|
||||||
should.not.exist(err);
|
should.not.exist(err);
|
||||||
users.length.should.equal(1);
|
users.length.should.equal(1);
|
||||||
users[0].name.should.equal('John Lennon');
|
users[0].name.should.equal('John Lennon');
|
||||||
done();
|
done();
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
it('should support the regexp operator with regex strings', function(done) {
|
it('should support the regexp operator with regex strings', function(done) {
|
||||||
User.find({where: {name: {regexp: '^J'}}}, function(err, users) {
|
User.find({ where: { name: { regexp: '^J' }}}, function(err, users) {
|
||||||
should.not.exist(err);
|
should.not.exist(err);
|
||||||
users.length.should.equal(1);
|
users.length.should.equal(1);
|
||||||
users[0].name.should.equal('John Lennon');
|
users[0].name.should.equal('John Lennon');
|
||||||
|
@ -444,7 +444,7 @@ describe('Memory connector', function() {
|
||||||
});
|
});
|
||||||
|
|
||||||
it('should support the regexp operator with regex literals', function(done) {
|
it('should support the regexp operator with regex literals', function(done) {
|
||||||
User.find({where: {name: {regexp: /^J/}}}, function(err, users) {
|
User.find({ where: { name: { regexp: /^J/ }}}, function(err, users) {
|
||||||
should.not.exist(err);
|
should.not.exist(err);
|
||||||
users.length.should.equal(1);
|
users.length.should.equal(1);
|
||||||
users[0].name.should.equal('John Lennon');
|
users[0].name.should.equal('John Lennon');
|
||||||
|
@ -453,7 +453,7 @@ describe('Memory connector', function() {
|
||||||
});
|
});
|
||||||
|
|
||||||
it('should support the regexp operator with regex objects', function(done) {
|
it('should support the regexp operator with regex objects', function(done) {
|
||||||
User.find({where: {name: {regexp: new RegExp(/^J/)}}}, function(err,
|
User.find({ where: { name: { regexp: new RegExp(/^J/) }}}, function(err,
|
||||||
users) {
|
users) {
|
||||||
should.not.exist(err);
|
should.not.exist(err);
|
||||||
users.length.should.equal(1);
|
users.length.should.equal(1);
|
||||||
|
@ -463,7 +463,7 @@ describe('Memory connector', function() {
|
||||||
});
|
});
|
||||||
|
|
||||||
it('should support nested property in query', function(done) {
|
it('should support nested property in query', function(done) {
|
||||||
User.find({where: {'address.city': 'San Jose'}}, function(err, users) {
|
User.find({ where: { 'address.city': 'San Jose' }}, function(err, users) {
|
||||||
should.not.exist(err);
|
should.not.exist(err);
|
||||||
users.length.should.be.equal(1);
|
users.length.should.be.equal(1);
|
||||||
for (var i = 0; i < users.length; i++) {
|
for (var i = 0; i < users.length; i++) {
|
||||||
|
@ -474,7 +474,7 @@ describe('Memory connector', function() {
|
||||||
});
|
});
|
||||||
|
|
||||||
it('should support nested property with regex over arrays in query', function(done) {
|
it('should support nested property with regex over arrays in query', function(done) {
|
||||||
User.find({where: {'friends.name': {regexp: /^Ringo/}}}, function(err, users) {
|
User.find({ where: { 'friends.name': { regexp: /^Ringo/ }}}, function(err, users) {
|
||||||
should.not.exist(err);
|
should.not.exist(err);
|
||||||
users.length.should.be.equal(2);
|
users.length.should.be.equal(2);
|
||||||
users[0].name.should.be.equal('John Lennon');
|
users[0].name.should.be.equal('John Lennon');
|
||||||
|
@ -484,18 +484,18 @@ describe('Memory connector', function() {
|
||||||
});
|
});
|
||||||
|
|
||||||
it('should support nested property with gt in query', function(done) {
|
it('should support nested property with gt in query', function(done) {
|
||||||
User.find({where: {'address.city': {gt: 'San'}}}, function(err, users) {
|
User.find({ where: { 'address.city': { gt: 'San' }}}, function(err, users) {
|
||||||
should.not.exist(err);
|
should.not.exist(err);
|
||||||
users.length.should.be.equal(2);
|
users.length.should.be.equal(2);
|
||||||
for (var i = 0; i < users.length; i++) {
|
for (var i = 0; i < users.length; i++) {
|
||||||
users[i].address.state.should.be.eql('CA');
|
users[i].address.state.should.be.eql('CA');
|
||||||
}
|
}
|
||||||
done();
|
done();
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
it('should support nested property for order in query', function(done) {
|
it('should support nested property for order in query', function(done) {
|
||||||
User.find({where: {'address.state': 'CA'}, order: 'address.city DESC'},
|
User.find({ where: { 'address.state': 'CA' }, order: 'address.city DESC' },
|
||||||
function(err, users) {
|
function(err, users) {
|
||||||
should.not.exist(err);
|
should.not.exist(err);
|
||||||
users.length.should.be.equal(2);
|
users.length.should.be.equal(2);
|
||||||
|
@ -506,8 +506,8 @@ describe('Memory connector', function() {
|
||||||
});
|
});
|
||||||
|
|
||||||
it('should deserialize values after saving in upsert', function(done) {
|
it('should deserialize values after saving in upsert', function(done) {
|
||||||
User.findOne({where: {seq: 1}}, function(err, paul) {
|
User.findOne({ where: { seq: 1 }}, function(err, paul) {
|
||||||
User.updateOrCreate({id: paul.id, name: 'Sir Paul McCartney'},
|
User.updateOrCreate({ id: paul.id, name: 'Sir Paul McCartney' },
|
||||||
function(err, sirpaul) {
|
function(err, sirpaul) {
|
||||||
should.not.exist(err);
|
should.not.exist(err);
|
||||||
sirpaul.birthday.should.be.instanceOf(Date);
|
sirpaul.birthday.should.be.instanceOf(Date);
|
||||||
|
@ -531,14 +531,14 @@ describe('Memory connector', function() {
|
||||||
street: '123 A St',
|
street: '123 A St',
|
||||||
city: 'San Jose',
|
city: 'San Jose',
|
||||||
state: 'CA',
|
state: 'CA',
|
||||||
zipCode: '95131'
|
zipCode: '95131',
|
||||||
},
|
},
|
||||||
friends: [
|
friends: [
|
||||||
{ name: 'Paul McCartney' },
|
{ name: 'Paul McCartney' },
|
||||||
{ name: 'George Harrison' },
|
{ name: 'George Harrison' },
|
||||||
{ name: 'Ringo Starr' },
|
{ name: 'Ringo Starr' },
|
||||||
],
|
],
|
||||||
children: ['Sean', 'Julian']
|
children: ['Sean', 'Julian'],
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
seq: 1,
|
seq: 1,
|
||||||
|
@ -552,26 +552,26 @@ describe('Memory connector', function() {
|
||||||
street: '456 B St',
|
street: '456 B St',
|
||||||
city: 'San Mateo',
|
city: 'San Mateo',
|
||||||
state: 'CA',
|
state: 'CA',
|
||||||
zipCode: '94065'
|
zipCode: '94065',
|
||||||
},
|
},
|
||||||
friends: [
|
friends: [
|
||||||
{ name: 'John Lennon' },
|
{ name: 'John Lennon' },
|
||||||
{ name: 'George Harrison' },
|
{ name: 'George Harrison' },
|
||||||
{ name: 'Ringo Starr' },
|
{ name: 'Ringo Starr' },
|
||||||
],
|
],
|
||||||
children: ['Stella', 'Mary', 'Heather', 'Beatrice', 'James']
|
children: ['Stella', 'Mary', 'Heather', 'Beatrice', 'James'],
|
||||||
},
|
},
|
||||||
{seq: 2, name: 'George Harrison', order: 5, vip: false, children: ['Dhani']},
|
{ seq: 2, name: 'George Harrison', order: 5, vip: false, children: ['Dhani'] },
|
||||||
{seq: 3, name: 'Ringo Starr', order: 6, vip: false},
|
{ seq: 3, name: 'Ringo Starr', order: 6, vip: false },
|
||||||
{seq: 4, name: 'Pete Best', order: 4, children: []},
|
{ seq: 4, name: 'Pete Best', order: 4, children: [] },
|
||||||
{seq: 5, name: 'Stuart Sutcliffe', order: 3, vip: true}
|
{ seq: 5, name: 'Stuart Sutcliffe', order: 3, vip: true },
|
||||||
];
|
];
|
||||||
|
|
||||||
async.series([
|
async.series([
|
||||||
User.destroyAll.bind(User),
|
User.destroyAll.bind(User),
|
||||||
function(cb) {
|
function(cb) {
|
||||||
async.each(beatles, User.create.bind(User), cb);
|
async.each(beatles, User.create.bind(User), cb);
|
||||||
}
|
},
|
||||||
], done);
|
], done);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -579,20 +579,20 @@ describe('Memory connector', function() {
|
||||||
|
|
||||||
it('should use collection setting', function(done) {
|
it('should use collection setting', function(done) {
|
||||||
var ds = new DataSource({
|
var ds = new DataSource({
|
||||||
connector: 'memory'
|
connector: 'memory',
|
||||||
});
|
});
|
||||||
|
|
||||||
var Product = ds.createModel('Product', {
|
var Product = ds.createModel('Product', {
|
||||||
name: String
|
name: String,
|
||||||
});
|
});
|
||||||
|
|
||||||
var Tool = ds.createModel('Tool', {
|
var Tool = ds.createModel('Tool', {
|
||||||
name: String
|
name: String,
|
||||||
}, {memory: {collection: 'Product'}});
|
}, { memory: { collection: 'Product' }});
|
||||||
|
|
||||||
var Widget = ds.createModel('Widget', {
|
var Widget = ds.createModel('Widget', {
|
||||||
name: String
|
name: String,
|
||||||
}, {memory: {collection: 'Product'}});
|
}, { memory: { collection: 'Product' }});
|
||||||
|
|
||||||
ds.connector.getCollection('Tool').should.equal('Product');
|
ds.connector.getCollection('Tool').should.equal('Product');
|
||||||
ds.connector.getCollection('Widget').should.equal('Product');
|
ds.connector.getCollection('Widget').should.equal('Product');
|
||||||
|
@ -606,7 +606,7 @@ describe('Memory connector', function() {
|
||||||
},
|
},
|
||||||
function(next) {
|
function(next) {
|
||||||
Widget.create({ name: 'Widget A' }, next);
|
Widget.create({ name: 'Widget A' }, next);
|
||||||
}
|
},
|
||||||
], function(err) {
|
], function(err) {
|
||||||
Product.find(function(err, products) {
|
Product.find(function(err, products) {
|
||||||
should.not.exist(err);
|
should.not.exist(err);
|
||||||
|
@ -623,11 +623,11 @@ describe('Memory connector', function() {
|
||||||
var ds;
|
var ds;
|
||||||
beforeEach(function() {
|
beforeEach(function() {
|
||||||
ds = new DataSource({
|
ds = new DataSource({
|
||||||
connector: 'memory'
|
connector: 'memory',
|
||||||
});
|
});
|
||||||
|
|
||||||
ds.createModel('m1', {
|
ds.createModel('m1', {
|
||||||
name: String
|
name: String,
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
|
@ -642,7 +642,7 @@ describe('Memory connector', function() {
|
||||||
.then(function(result) {
|
.then(function(result) {
|
||||||
done();
|
done();
|
||||||
})
|
})
|
||||||
.catch(function(err){
|
.catch(function(err) {
|
||||||
done(err);
|
done(err);
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
@ -658,7 +658,7 @@ describe('Memory connector', function() {
|
||||||
.then(function(result) {
|
.then(function(result) {
|
||||||
done();
|
done();
|
||||||
})
|
})
|
||||||
.catch(function(err){
|
.catch(function(err) {
|
||||||
done(err);
|
done(err);
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
@ -674,7 +674,7 @@ describe('Memory connector', function() {
|
||||||
.then(function(result) {
|
.then(function(result) {
|
||||||
done();
|
done();
|
||||||
})
|
})
|
||||||
.catch(function(err){
|
.catch(function(err) {
|
||||||
done(err);
|
done(err);
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
@ -688,10 +688,10 @@ describe('Memory connector', function() {
|
||||||
|
|
||||||
it('automigrate reports errors for models not attached - promise variant', function(done) {
|
it('automigrate reports errors for models not attached - promise variant', function(done) {
|
||||||
ds.automigrate(['m1', 'm2'])
|
ds.automigrate(['m1', 'm2'])
|
||||||
.then(function(){
|
.then(function() {
|
||||||
done(new Error('automigrate() should have failed'));
|
done(new Error('automigrate() should have failed'));
|
||||||
})
|
})
|
||||||
.catch(function(err){
|
.catch(function(err) {
|
||||||
err.should.be.an.instanceOf(Error);
|
err.should.be.an.instanceOf(Error);
|
||||||
done();
|
done();
|
||||||
});
|
});
|
||||||
|
@ -702,17 +702,17 @@ describe('Memory connector', function() {
|
||||||
describe('findOrCreate', function() {
|
describe('findOrCreate', function() {
|
||||||
var ds, Cars;
|
var ds, Cars;
|
||||||
before(function() {
|
before(function() {
|
||||||
ds = new DataSource({connector: 'memory'});
|
ds = new DataSource({ connector: 'memory' });
|
||||||
Cars = ds.define('Cars', {
|
Cars = ds.define('Cars', {
|
||||||
color: String
|
color: String,
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
it('should create a specific object once and in the subsequent calls it should find it', function(done) {
|
it('should create a specific object once and in the subsequent calls it should find it', function(done) {
|
||||||
var creationNum = 0;
|
var creationNum = 0;
|
||||||
async.times(100, function(n, next) {
|
async.times(100, function(n, next) {
|
||||||
var initialData = {color: 'white'};
|
var initialData = { color: 'white' };
|
||||||
var query = {'where': initialData};
|
var query = { 'where': initialData };
|
||||||
Cars.findOrCreate(query, initialData, function(err, car, created) {
|
Cars.findOrCreate(query, initialData, function(err, car, created) {
|
||||||
if (created) creationNum++;
|
if (created) creationNum++;
|
||||||
next(err, car);
|
next(err, car);
|
||||||
|
@ -735,20 +735,20 @@ describe('Memory connector', function() {
|
||||||
var ds;
|
var ds;
|
||||||
beforeEach(function() {
|
beforeEach(function() {
|
||||||
ds = new DataSource({
|
ds = new DataSource({
|
||||||
connector: 'memory'
|
connector: 'memory',
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
it('automigrate does NOT report error when NO models are attached', function(done) {
|
it('automigrate does NOT report error when NO models are attached', function(done) {
|
||||||
ds.automigrate(function(err) {
|
ds.automigrate(function(err) {
|
||||||
done();
|
done();
|
||||||
})
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
it('automigrate does NOT report error when NO models are attached - promise variant', function(done) {
|
it('automigrate does NOT report error when NO models are attached - promise variant', function(done) {
|
||||||
ds.automigrate()
|
ds.automigrate()
|
||||||
.then(done)
|
.then(done)
|
||||||
.catch(function(err){
|
.catch(function(err) {
|
||||||
done(err);
|
done(err);
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
@ -758,7 +758,7 @@ describe('Memory connector', function() {
|
||||||
var ds, model;
|
var ds, model;
|
||||||
beforeEach(function() {
|
beforeEach(function() {
|
||||||
ds = new DataSource({
|
ds = new DataSource({
|
||||||
connector: 'memory'
|
connector: 'memory',
|
||||||
});
|
});
|
||||||
|
|
||||||
ds.connector.autoupdate = function(models, cb) {
|
ds.connector.autoupdate = function(models, cb) {
|
||||||
|
@ -766,19 +766,19 @@ describe('Memory connector', function() {
|
||||||
};
|
};
|
||||||
|
|
||||||
model = ds.createModel('m1', {
|
model = ds.createModel('m1', {
|
||||||
name: String
|
name: String,
|
||||||
});
|
});
|
||||||
|
|
||||||
ds.automigrate();
|
ds.automigrate();
|
||||||
|
|
||||||
ds.createModel('m1', {
|
ds.createModel('m1', {
|
||||||
name: String,
|
name: String,
|
||||||
address: String
|
address: String,
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
it('autoupdates all models', function(done) {
|
it('autoupdates all models', function(done) {
|
||||||
ds.autoupdate(function(err, result){
|
ds.autoupdate(function(err, result) {
|
||||||
done(err);
|
done(err);
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
@ -786,9 +786,9 @@ describe('Memory connector', function() {
|
||||||
it('autoupdates all models - promise variant', function(done) {
|
it('autoupdates all models - promise variant', function(done) {
|
||||||
ds.autoupdate()
|
ds.autoupdate()
|
||||||
.then(function(result) {
|
.then(function(result) {
|
||||||
done();
|
done();
|
||||||
})
|
})
|
||||||
.catch(function(err){
|
.catch(function(err) {
|
||||||
done(err);
|
done(err);
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
@ -804,7 +804,7 @@ describe('Memory connector', function() {
|
||||||
.then(function(result) {
|
.then(function(result) {
|
||||||
done();
|
done();
|
||||||
})
|
})
|
||||||
.catch(function(err){
|
.catch(function(err) {
|
||||||
done(err);
|
done(err);
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
@ -820,7 +820,7 @@ describe('Memory connector', function() {
|
||||||
.then(function(result) {
|
.then(function(result) {
|
||||||
done();
|
done();
|
||||||
})
|
})
|
||||||
.catch(function(err){
|
.catch(function(err) {
|
||||||
done(err);
|
done(err);
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
@ -834,10 +834,10 @@ describe('Memory connector', function() {
|
||||||
|
|
||||||
it('autoupdate reports errors for models not attached - promise variant', function(done) {
|
it('autoupdate reports errors for models not attached - promise variant', function(done) {
|
||||||
ds.autoupdate(['m1', 'm2'])
|
ds.autoupdate(['m1', 'm2'])
|
||||||
.then(function(){
|
.then(function() {
|
||||||
done(new Error('automigrate() should have failed'));
|
done(new Error('automigrate() should have failed'));
|
||||||
})
|
})
|
||||||
.catch(function(err){
|
.catch(function(err) {
|
||||||
err.should.be.an.instanceOf(Error);
|
err.should.be.an.instanceOf(Error);
|
||||||
done();
|
done();
|
||||||
});
|
});
|
||||||
|
@ -849,16 +849,16 @@ describe('Optimized connector', function() {
|
||||||
var ds = new DataSource({ connector: Memory });
|
var ds = new DataSource({ connector: Memory });
|
||||||
|
|
||||||
// optimized methods
|
// optimized methods
|
||||||
ds.connector.findOrCreate = function (model, query, data, callback) {
|
ds.connector.findOrCreate = function(model, query, data, callback) {
|
||||||
this.all(model, query, {}, function (err, list) {
|
this.all(model, query, {}, function(err, list) {
|
||||||
if (err || (list && list[0])) return callback(err, list && list[0], false);
|
if (err || (list && list[0])) return callback(err, list && list[0], false);
|
||||||
this.create(model, data, {}, function (err) {
|
this.create(model, data, {}, function(err) {
|
||||||
callback(err, data, true);
|
callback(err, data, true);
|
||||||
});
|
});
|
||||||
}.bind(this));
|
}.bind(this));
|
||||||
};
|
};
|
||||||
|
|
||||||
require('./persistence-hooks.suite')(ds, should, {replaceOrCreateReportsNewInstance: true});
|
require('./persistence-hooks.suite')(ds, should, { replaceOrCreateReportsNewInstance: true });
|
||||||
});
|
});
|
||||||
|
|
||||||
describe('Unoptimized connector', function() {
|
describe('Unoptimized connector', function() {
|
||||||
|
@ -867,14 +867,14 @@ describe('Unoptimized connector', function() {
|
||||||
ds.connector.updateOrCreate = false;
|
ds.connector.updateOrCreate = false;
|
||||||
ds.connector.findOrCreate = false;
|
ds.connector.findOrCreate = false;
|
||||||
|
|
||||||
require('./persistence-hooks.suite')(ds, should, {replaceOrCreateReportsNewInstance: true});
|
require('./persistence-hooks.suite')(ds, should, { replaceOrCreateReportsNewInstance: true });
|
||||||
});
|
});
|
||||||
|
|
||||||
describe('Memory connector with options', function() {
|
describe('Memory connector with options', function() {
|
||||||
var ds, savedOptions = {}, Post;
|
var ds, savedOptions = {}, Post;
|
||||||
|
|
||||||
before(function() {
|
before(function() {
|
||||||
ds = new DataSource({connector: 'memory'});
|
ds = new DataSource({ connector: 'memory' });
|
||||||
ds.connector.create = function(model, data, options, cb) {
|
ds.connector.create = function(model, data, options, cb) {
|
||||||
savedOptions.create = options;
|
savedOptions.create = options;
|
||||||
process.nextTick(function() {
|
process.nextTick(function() {
|
||||||
|
@ -885,33 +885,33 @@ describe('Memory connector with options', function() {
|
||||||
ds.connector.update = function(model, where, data, options, cb) {
|
ds.connector.update = function(model, where, data, options, cb) {
|
||||||
savedOptions.update = options;
|
savedOptions.update = options;
|
||||||
process.nextTick(function() {
|
process.nextTick(function() {
|
||||||
cb(null, {count: 1});
|
cb(null, { count: 1 });
|
||||||
});
|
});
|
||||||
};
|
};
|
||||||
|
|
||||||
ds.connector.all = function(model, filter, options, cb) {
|
ds.connector.all = function(model, filter, options, cb) {
|
||||||
savedOptions.find = options;
|
savedOptions.find = options;
|
||||||
process.nextTick(function() {
|
process.nextTick(function() {
|
||||||
cb(null, [{title: 't1', content: 'c1'}]);
|
cb(null, [{ title: 't1', content: 'c1' }]);
|
||||||
});
|
});
|
||||||
};
|
};
|
||||||
|
|
||||||
Post = ds.define('Post', {
|
Post = ds.define('Post', {
|
||||||
title: String,
|
title: String,
|
||||||
content: String
|
content: String,
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
it('should receive options from the find method', function(done) {
|
it('should receive options from the find method', function(done) {
|
||||||
var opts = {transaction: 'tx1'};
|
var opts = { transaction: 'tx1' };
|
||||||
Post.find({where: {title: 't1'}}, opts, function(err, p) {
|
Post.find({ where: { title: 't1' }}, opts, function(err, p) {
|
||||||
savedOptions.find.should.be.eql(opts);
|
savedOptions.find.should.be.eql(opts);
|
||||||
done(err);
|
done(err);
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
it('should receive options from the find method', function(done) {
|
it('should receive options from the find method', function(done) {
|
||||||
var opts = {transaction: 'tx2'};
|
var opts = { transaction: 'tx2' };
|
||||||
Post.find({}, opts, function(err, p) {
|
Post.find({}, opts, function(err, p) {
|
||||||
savedOptions.find.should.be.eql(opts);
|
savedOptions.find.should.be.eql(opts);
|
||||||
done(err);
|
done(err);
|
||||||
|
@ -919,7 +919,7 @@ describe('Memory connector with options', function() {
|
||||||
});
|
});
|
||||||
|
|
||||||
it('should treat first object arg as filter for find', function(done) {
|
it('should treat first object arg as filter for find', function(done) {
|
||||||
var filter = {title: 't1'};
|
var filter = { title: 't1' };
|
||||||
Post.find(filter, function(err, p) {
|
Post.find(filter, function(err, p) {
|
||||||
savedOptions.find.should.be.eql({});
|
savedOptions.find.should.be.eql({});
|
||||||
done(err);
|
done(err);
|
||||||
|
@ -927,16 +927,16 @@ describe('Memory connector with options', function() {
|
||||||
});
|
});
|
||||||
|
|
||||||
it('should receive options from the create method', function(done) {
|
it('should receive options from the create method', function(done) {
|
||||||
var opts = {transaction: 'tx3'};
|
var opts = { transaction: 'tx3' };
|
||||||
Post.create({title: 't1', content: 'c1'}, opts, function(err, p) {
|
Post.create({ title: 't1', content: 'c1' }, opts, function(err, p) {
|
||||||
savedOptions.create.should.be.eql(opts);
|
savedOptions.create.should.be.eql(opts);
|
||||||
done(err);
|
done(err);
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
it('should receive options from the update method', function(done) {
|
it('should receive options from the update method', function(done) {
|
||||||
var opts = {transaction: 'tx4'};
|
var opts = { transaction: 'tx4' };
|
||||||
Post.update({title: 't1'}, {content: 'c1 --> c2'},
|
Post.update({ title: 't1' }, { content: 'c1 --> c2' },
|
||||||
opts, function(err, p) {
|
opts, function(err, p) {
|
||||||
savedOptions.update.should.be.eql(opts);
|
savedOptions.update.should.be.eql(opts);
|
||||||
done(err);
|
done(err);
|
||||||
|
@ -947,7 +947,7 @@ describe('Memory connector with options', function() {
|
||||||
|
|
||||||
describe('Memory connector with observers', function() {
|
describe('Memory connector with observers', function() {
|
||||||
var ds = new DataSource({
|
var ds = new DataSource({
|
||||||
connector: 'memory'
|
connector: 'memory',
|
||||||
});
|
});
|
||||||
|
|
||||||
it('should have observer mixed into the connector', function() {
|
it('should have observer mixed into the connector', function() {
|
||||||
|
@ -959,7 +959,7 @@ describe('Memory connector with observers', function() {
|
||||||
var events = [];
|
var events = [];
|
||||||
ds.connector.execute = function(command, params, options, cb) {
|
ds.connector.execute = function(command, params, options, cb) {
|
||||||
var self = this;
|
var self = this;
|
||||||
var context = {command: command, params: params, options: options};
|
var context = { command: command, params: params, options: options };
|
||||||
self.notifyObserversOf('before execute', context, function(err) {
|
self.notifyObserversOf('before execute', context, function(err) {
|
||||||
process.nextTick(function() {
|
process.nextTick(function() {
|
||||||
if (err) return cb(err);
|
if (err) return cb(err);
|
||||||
|
@ -981,7 +981,7 @@ describe('Memory connector with observers', function() {
|
||||||
next();
|
next();
|
||||||
});
|
});
|
||||||
|
|
||||||
ds.connector.execute('test', [1, 2], {x: 2}, function(err) {
|
ds.connector.execute('test', [1, 2], { x: 2 }, function(err) {
|
||||||
if (err) return done(err);
|
if (err) return done(err);
|
||||||
events.should.eql(['before execute', 'execute', 'after execute']);
|
events.should.eql(['before execute', 'execute', 'after execute']);
|
||||||
done();
|
done();
|
||||||
|
|
|
@ -45,7 +45,7 @@ function timestamps(Model, options) {
|
||||||
|
|
||||||
mixins.define('TimeStamp', timestamps);
|
mixins.define('TimeStamp', timestamps);
|
||||||
|
|
||||||
describe('Model class', function () {
|
describe('Model class', function() {
|
||||||
|
|
||||||
it('should define mixins', function() {
|
it('should define mixins', function() {
|
||||||
mixins.define('Example', function(Model, options) {
|
mixins.define('Example', function(Model, options) {
|
||||||
|
@ -65,12 +65,12 @@ describe('Model class', function () {
|
||||||
it('should apply a mixin class', function() {
|
it('should apply a mixin class', function() {
|
||||||
var Address = modelBuilder.define('Address', {
|
var Address = modelBuilder.define('Address', {
|
||||||
street: { type: 'string', required: true },
|
street: { type: 'string', required: true },
|
||||||
city: { type: 'string', required: true }
|
city: { type: 'string', required: true },
|
||||||
});
|
});
|
||||||
|
|
||||||
var memory = new DataSource('mem', {connector: Memory}, modelBuilder);
|
var memory = new DataSource('mem', { connector: Memory }, modelBuilder);
|
||||||
var Item = memory.createModel('Item', { name: 'string' }, {
|
var Item = memory.createModel('Item', { name: 'string' }, {
|
||||||
mixins: { Address: true }
|
mixins: { Address: true },
|
||||||
});
|
});
|
||||||
|
|
||||||
var properties = Item.definition.properties;
|
var properties = Item.definition.properties;
|
||||||
|
@ -80,15 +80,15 @@ describe('Model class', function () {
|
||||||
});
|
});
|
||||||
|
|
||||||
it('should apply mixins', function(done) {
|
it('should apply mixins', function(done) {
|
||||||
var memory = new DataSource('mem', {connector: Memory}, modelBuilder);
|
var memory = new DataSource('mem', { connector: Memory }, modelBuilder);
|
||||||
var Item = memory.createModel('Item', { name: 'string' }, {
|
var Item = memory.createModel('Item', { name: 'string' }, {
|
||||||
mixins: {
|
mixins: {
|
||||||
TimeStamp: true, Demo: { value: true },
|
TimeStamp: true, Demo: { value: true },
|
||||||
Multi: [
|
Multi: [
|
||||||
{ key: 'foo', value: 'bar' },
|
{ key: 'foo', value: 'bar' },
|
||||||
{ key: 'fox', value: 'baz' }
|
{ key: 'fox', value: 'baz' },
|
||||||
]
|
],
|
||||||
}
|
},
|
||||||
});
|
});
|
||||||
|
|
||||||
Item.mixin('Example', { foo: 'bar' });
|
Item.mixin('Example', { foo: 'bar' });
|
||||||
|
@ -110,31 +110,31 @@ describe('Model class', function () {
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
describe('#mixin()', function () {
|
describe('#mixin()', function() {
|
||||||
|
|
||||||
var Person, Author, Address;
|
var Person, Author, Address;
|
||||||
|
|
||||||
beforeEach(function () {
|
beforeEach(function() {
|
||||||
Address = modelBuilder.define('Address', {
|
Address = modelBuilder.define('Address', {
|
||||||
street: { type: 'string', required: true },
|
street: { type: 'string', required: true },
|
||||||
city: { type: 'string', required: true }
|
city: { type: 'string', required: true },
|
||||||
});
|
});
|
||||||
var memory = new DataSource('mem', {connector: Memory}, modelBuilder);
|
var memory = new DataSource('mem', { connector: Memory }, modelBuilder);
|
||||||
Person = memory.createModel('Person', { name: 'string' });
|
Person = memory.createModel('Person', { name: 'string' });
|
||||||
Author = memory.createModel('Author', { name: 'string' });
|
Author = memory.createModel('Author', { name: 'string' });
|
||||||
});
|
});
|
||||||
|
|
||||||
it('should register mixin class into _mixins', function () {
|
it('should register mixin class into _mixins', function() {
|
||||||
Person.mixin(Address);
|
Person.mixin(Address);
|
||||||
Person._mixins.should.containEql(Address);
|
Person._mixins.should.containEql(Address);
|
||||||
});
|
});
|
||||||
|
|
||||||
it('should NOT share mixins registry', function () {
|
it('should NOT share mixins registry', function() {
|
||||||
Person.mixin(Address);
|
Person.mixin(Address);
|
||||||
Author._mixins.should.not.containEql(Address);
|
Author._mixins.should.not.containEql(Address);
|
||||||
});
|
});
|
||||||
|
|
||||||
it('should able to mixin same class', function () {
|
it('should able to mixin same class', function() {
|
||||||
Person.mixin(Address);
|
Person.mixin(Address);
|
||||||
Author.mixin(Address);
|
Author.mixin(Address);
|
||||||
Author._mixins.should.containEql(Address);
|
Author._mixins.should.containEql(Address);
|
||||||
|
|
|
@ -14,21 +14,21 @@ var Memory = require('../lib/connectors/memory');
|
||||||
|
|
||||||
var ModelDefinition = require('../lib/model-definition');
|
var ModelDefinition = require('../lib/model-definition');
|
||||||
|
|
||||||
describe('ModelDefinition class', function () {
|
describe('ModelDefinition class', function() {
|
||||||
var memory;
|
var memory;
|
||||||
beforeEach(function() {
|
beforeEach(function() {
|
||||||
memory = new DataSource({connector: Memory});
|
memory = new DataSource({ connector: Memory });
|
||||||
});
|
});
|
||||||
|
|
||||||
it('should be able to define plain models', function (done) {
|
it('should be able to define plain models', function(done) {
|
||||||
var modelBuilder = new ModelBuilder();
|
var modelBuilder = new ModelBuilder();
|
||||||
|
|
||||||
var User = new ModelDefinition(modelBuilder, 'User', {
|
var User = new ModelDefinition(modelBuilder, 'User', {
|
||||||
name: "string",
|
name: 'string',
|
||||||
bio: ModelBuilder.Text,
|
bio: ModelBuilder.Text,
|
||||||
approved: Boolean,
|
approved: Boolean,
|
||||||
joinedAt: Date,
|
joinedAt: Date,
|
||||||
age: "number"
|
age: 'number',
|
||||||
});
|
});
|
||||||
|
|
||||||
User.build();
|
User.build();
|
||||||
|
@ -39,12 +39,12 @@ describe('ModelDefinition class', function () {
|
||||||
assert.equal(User.properties.age.type, Number);
|
assert.equal(User.properties.age.type, Number);
|
||||||
|
|
||||||
var json = User.toJSON();
|
var json = User.toJSON();
|
||||||
assert.equal(json.name, "User");
|
assert.equal(json.name, 'User');
|
||||||
assert.equal(json.properties.name.type, "String");
|
assert.equal(json.properties.name.type, 'String');
|
||||||
assert.equal(json.properties.bio.type, "Text");
|
assert.equal(json.properties.bio.type, 'Text');
|
||||||
assert.equal(json.properties.approved.type, "Boolean");
|
assert.equal(json.properties.approved.type, 'Boolean');
|
||||||
assert.equal(json.properties.joinedAt.type, "Date");
|
assert.equal(json.properties.joinedAt.type, 'Date');
|
||||||
assert.equal(json.properties.age.type, "Number");
|
assert.equal(json.properties.age.type, 'Number');
|
||||||
|
|
||||||
assert.deepEqual(User.toJSON(), json);
|
assert.deepEqual(User.toJSON(), json);
|
||||||
|
|
||||||
|
@ -52,22 +52,22 @@ describe('ModelDefinition class', function () {
|
||||||
|
|
||||||
});
|
});
|
||||||
|
|
||||||
it('should be able to define additional properties', function (done) {
|
it('should be able to define additional properties', function(done) {
|
||||||
var modelBuilder = new ModelBuilder();
|
var modelBuilder = new ModelBuilder();
|
||||||
|
|
||||||
var User = new ModelDefinition(modelBuilder, 'User', {
|
var User = new ModelDefinition(modelBuilder, 'User', {
|
||||||
name: "string",
|
name: 'string',
|
||||||
bio: ModelBuilder.Text,
|
bio: ModelBuilder.Text,
|
||||||
approved: Boolean,
|
approved: Boolean,
|
||||||
joinedAt: Date,
|
joinedAt: Date,
|
||||||
age: "number"
|
age: 'number',
|
||||||
});
|
});
|
||||||
|
|
||||||
User.build();
|
User.build();
|
||||||
|
|
||||||
var json = User.toJSON();
|
var json = User.toJSON();
|
||||||
|
|
||||||
User.defineProperty("id", {type: "number", id: true});
|
User.defineProperty('id', { type: 'number', id: true });
|
||||||
assert.equal(User.properties.name.type, String);
|
assert.equal(User.properties.name.type, String);
|
||||||
assert.equal(User.properties.bio.type, ModelBuilder.Text);
|
assert.equal(User.properties.bio.type, ModelBuilder.Text);
|
||||||
assert.equal(User.properties.approved.type, Boolean);
|
assert.equal(User.properties.approved.type, Boolean);
|
||||||
|
@ -77,13 +77,13 @@ describe('ModelDefinition class', function () {
|
||||||
assert.equal(User.properties.id.type, Number);
|
assert.equal(User.properties.id.type, Number);
|
||||||
|
|
||||||
json = User.toJSON();
|
json = User.toJSON();
|
||||||
assert.deepEqual(json.properties.id, {type: 'Number', id: true});
|
assert.deepEqual(json.properties.id, { type: 'Number', id: true });
|
||||||
|
|
||||||
done();
|
done();
|
||||||
|
|
||||||
});
|
});
|
||||||
|
|
||||||
it('should be able to define nesting models', function (done) {
|
it('should be able to define nesting models', function(done) {
|
||||||
var modelBuilder = new ModelBuilder();
|
var modelBuilder = new ModelBuilder();
|
||||||
|
|
||||||
var User = new ModelDefinition(modelBuilder, 'User', {
|
var User = new ModelDefinition(modelBuilder, 'User', {
|
||||||
|
@ -96,8 +96,8 @@ describe('ModelDefinition class', function () {
|
||||||
street: String,
|
street: String,
|
||||||
city: String,
|
city: String,
|
||||||
zipCode: String,
|
zipCode: String,
|
||||||
state: String
|
state: String,
|
||||||
}
|
},
|
||||||
});
|
});
|
||||||
|
|
||||||
User.build();
|
User.build();
|
||||||
|
@ -109,30 +109,30 @@ describe('ModelDefinition class', function () {
|
||||||
assert.equal(typeof User.properties.address.type, 'function');
|
assert.equal(typeof User.properties.address.type, 'function');
|
||||||
|
|
||||||
var json = User.toJSON();
|
var json = User.toJSON();
|
||||||
assert.equal(json.name, "User");
|
assert.equal(json.name, 'User');
|
||||||
assert.equal(json.properties.name.type, "String");
|
assert.equal(json.properties.name.type, 'String');
|
||||||
assert.equal(json.properties.bio.type, "Text");
|
assert.equal(json.properties.bio.type, 'Text');
|
||||||
assert.equal(json.properties.approved.type, "Boolean");
|
assert.equal(json.properties.approved.type, 'Boolean');
|
||||||
assert.equal(json.properties.joinedAt.type, "Date");
|
assert.equal(json.properties.joinedAt.type, 'Date');
|
||||||
assert.equal(json.properties.age.type, "Number");
|
assert.equal(json.properties.age.type, 'Number');
|
||||||
|
|
||||||
assert.deepEqual(json.properties.address.type, { street: { type: 'String' },
|
assert.deepEqual(json.properties.address.type, { street: { type: 'String' },
|
||||||
city: { type: 'String' },
|
city: { type: 'String' },
|
||||||
zipCode: { type: 'String' },
|
zipCode: { type: 'String' },
|
||||||
state: { type: 'String' } });
|
state: { type: 'String' }});
|
||||||
|
|
||||||
done();
|
done();
|
||||||
|
|
||||||
});
|
});
|
||||||
|
|
||||||
it('should be able to define referencing models', function (done) {
|
it('should be able to define referencing models', function(done) {
|
||||||
var modelBuilder = new ModelBuilder();
|
var modelBuilder = new ModelBuilder();
|
||||||
|
|
||||||
var Address = modelBuilder.define('Address', {
|
var Address = modelBuilder.define('Address', {
|
||||||
street: String,
|
street: String,
|
||||||
city: String,
|
city: String,
|
||||||
zipCode: String,
|
zipCode: String,
|
||||||
state: String
|
state: String,
|
||||||
});
|
});
|
||||||
var User = new ModelDefinition(modelBuilder, 'User', {
|
var User = new ModelDefinition(modelBuilder, 'User', {
|
||||||
name: String,
|
name: String,
|
||||||
|
@ -140,7 +140,7 @@ describe('ModelDefinition class', function () {
|
||||||
approved: Boolean,
|
approved: Boolean,
|
||||||
joinedAt: Date,
|
joinedAt: Date,
|
||||||
age: Number,
|
age: Number,
|
||||||
address: Address
|
address: Address,
|
||||||
|
|
||||||
});
|
});
|
||||||
|
|
||||||
|
@ -153,12 +153,12 @@ describe('ModelDefinition class', function () {
|
||||||
assert.equal(User.properties.address.type, Address);
|
assert.equal(User.properties.address.type, Address);
|
||||||
|
|
||||||
var json = User.toJSON();
|
var json = User.toJSON();
|
||||||
assert.equal(json.name, "User");
|
assert.equal(json.name, 'User');
|
||||||
assert.equal(json.properties.name.type, "String");
|
assert.equal(json.properties.name.type, 'String');
|
||||||
assert.equal(json.properties.bio.type, "Text");
|
assert.equal(json.properties.bio.type, 'Text');
|
||||||
assert.equal(json.properties.approved.type, "Boolean");
|
assert.equal(json.properties.approved.type, 'Boolean');
|
||||||
assert.equal(json.properties.joinedAt.type, "Date");
|
assert.equal(json.properties.joinedAt.type, 'Date');
|
||||||
assert.equal(json.properties.age.type, "Number");
|
assert.equal(json.properties.age.type, 'Number');
|
||||||
|
|
||||||
assert.equal(json.properties.address.type, 'Address');
|
assert.equal(json.properties.address.type, 'Address');
|
||||||
|
|
||||||
|
@ -166,14 +166,14 @@ describe('ModelDefinition class', function () {
|
||||||
|
|
||||||
});
|
});
|
||||||
|
|
||||||
it('should be able to define referencing models by name', function (done) {
|
it('should be able to define referencing models by name', function(done) {
|
||||||
var modelBuilder = new ModelBuilder();
|
var modelBuilder = new ModelBuilder();
|
||||||
|
|
||||||
var Address = modelBuilder.define('Address', {
|
var Address = modelBuilder.define('Address', {
|
||||||
street: String,
|
street: String,
|
||||||
city: String,
|
city: String,
|
||||||
zipCode: String,
|
zipCode: String,
|
||||||
state: String
|
state: String,
|
||||||
});
|
});
|
||||||
var User = new ModelDefinition(modelBuilder, 'User', {
|
var User = new ModelDefinition(modelBuilder, 'User', {
|
||||||
name: String,
|
name: String,
|
||||||
|
@ -181,7 +181,7 @@ describe('ModelDefinition class', function () {
|
||||||
approved: Boolean,
|
approved: Boolean,
|
||||||
joinedAt: Date,
|
joinedAt: Date,
|
||||||
age: Number,
|
age: Number,
|
||||||
address: 'Address'
|
address: 'Address',
|
||||||
|
|
||||||
});
|
});
|
||||||
|
|
||||||
|
@ -194,12 +194,12 @@ describe('ModelDefinition class', function () {
|
||||||
assert.equal(User.properties.address.type, Address);
|
assert.equal(User.properties.address.type, Address);
|
||||||
|
|
||||||
var json = User.toJSON();
|
var json = User.toJSON();
|
||||||
assert.equal(json.name, "User");
|
assert.equal(json.name, 'User');
|
||||||
assert.equal(json.properties.name.type, "String");
|
assert.equal(json.properties.name.type, 'String');
|
||||||
assert.equal(json.properties.bio.type, "Text");
|
assert.equal(json.properties.bio.type, 'Text');
|
||||||
assert.equal(json.properties.approved.type, "Boolean");
|
assert.equal(json.properties.approved.type, 'Boolean');
|
||||||
assert.equal(json.properties.joinedAt.type, "Date");
|
assert.equal(json.properties.joinedAt.type, 'Date');
|
||||||
assert.equal(json.properties.age.type, "Number");
|
assert.equal(json.properties.age.type, 'Number');
|
||||||
|
|
||||||
assert.equal(json.properties.address.type, 'Address');
|
assert.equal(json.properties.address.type, 'Address');
|
||||||
|
|
||||||
|
@ -207,16 +207,16 @@ describe('ModelDefinition class', function () {
|
||||||
|
|
||||||
});
|
});
|
||||||
|
|
||||||
it('should report correct id names', function (done) {
|
it('should report correct id names', function(done) {
|
||||||
var modelBuilder = new ModelBuilder();
|
var modelBuilder = new ModelBuilder();
|
||||||
|
|
||||||
var User = new ModelDefinition(modelBuilder, 'User', {
|
var User = new ModelDefinition(modelBuilder, 'User', {
|
||||||
userId: {type: String, id: true},
|
userId: { type: String, id: true },
|
||||||
name: "string",
|
name: 'string',
|
||||||
bio: ModelBuilder.Text,
|
bio: ModelBuilder.Text,
|
||||||
approved: Boolean,
|
approved: Boolean,
|
||||||
joinedAt: Date,
|
joinedAt: Date,
|
||||||
age: "number"
|
age: 'number',
|
||||||
});
|
});
|
||||||
|
|
||||||
assert.equal(User.idName(), 'userId');
|
assert.equal(User.idName(), 'userId');
|
||||||
|
@ -224,17 +224,17 @@ describe('ModelDefinition class', function () {
|
||||||
done();
|
done();
|
||||||
});
|
});
|
||||||
|
|
||||||
it('should sort id properties by its index', function () {
|
it('should sort id properties by its index', function() {
|
||||||
var modelBuilder = new ModelBuilder();
|
var modelBuilder = new ModelBuilder();
|
||||||
|
|
||||||
var User = new ModelDefinition(modelBuilder, 'User', {
|
var User = new ModelDefinition(modelBuilder, 'User', {
|
||||||
userId: {type: String, id: 2},
|
userId: { type: String, id: 2 },
|
||||||
userType: {type: String, id: 1},
|
userType: { type: String, id: 1 },
|
||||||
name: "string",
|
name: 'string',
|
||||||
bio: ModelBuilder.Text,
|
bio: ModelBuilder.Text,
|
||||||
approved: Boolean,
|
approved: Boolean,
|
||||||
joinedAt: Date,
|
joinedAt: Date,
|
||||||
age: "number"
|
age: 'number',
|
||||||
});
|
});
|
||||||
|
|
||||||
var ids = User.ids();
|
var ids = User.ids();
|
||||||
|
@ -246,13 +246,13 @@ describe('ModelDefinition class', function () {
|
||||||
assert.equal(ids[1].name, 'userId');
|
assert.equal(ids[1].name, 'userId');
|
||||||
});
|
});
|
||||||
|
|
||||||
it('should report correct table/column names', function (done) {
|
it('should report correct table/column names', function(done) {
|
||||||
var modelBuilder = new ModelBuilder();
|
var modelBuilder = new ModelBuilder();
|
||||||
|
|
||||||
var User = new ModelDefinition(modelBuilder, 'User', {
|
var User = new ModelDefinition(modelBuilder, 'User', {
|
||||||
userId: {type: String, id: true, oracle: {column: 'ID'}},
|
userId: { type: String, id: true, oracle: { column: 'ID' }},
|
||||||
name: "string"
|
name: 'string',
|
||||||
}, {oracle: {table: 'USER'}});
|
}, { oracle: { table: 'USER' }});
|
||||||
|
|
||||||
assert.equal(User.tableName('oracle'), 'USER');
|
assert.equal(User.tableName('oracle'), 'USER');
|
||||||
assert.equal(User.tableName('mysql'), 'User');
|
assert.equal(User.tableName('mysql'), 'User');
|
||||||
|
@ -261,15 +261,15 @@ describe('ModelDefinition class', function () {
|
||||||
done();
|
done();
|
||||||
});
|
});
|
||||||
|
|
||||||
it('should inherit prototype using option.base', function () {
|
it('should inherit prototype using option.base', function() {
|
||||||
var modelBuilder = memory.modelBuilder;
|
var modelBuilder = memory.modelBuilder;
|
||||||
var parent = memory.createModel('parent', {}, {
|
var parent = memory.createModel('parent', {}, {
|
||||||
relations: {
|
relations: {
|
||||||
children: {
|
children: {
|
||||||
type: 'hasMany',
|
type: 'hasMany',
|
||||||
model: 'anotherChild'
|
model: 'anotherChild',
|
||||||
}
|
},
|
||||||
}
|
},
|
||||||
});
|
});
|
||||||
var baseChild = modelBuilder.define('baseChild');
|
var baseChild = modelBuilder.define('baseChild');
|
||||||
baseChild.attachTo(memory);
|
baseChild.attachTo(memory);
|
||||||
|
@ -301,30 +301,30 @@ describe('ModelDefinition class', function () {
|
||||||
it('should serialize protected properties into JSON', function() {
|
it('should serialize protected properties into JSON', function() {
|
||||||
var modelBuilder = memory.modelBuilder;
|
var modelBuilder = memory.modelBuilder;
|
||||||
var ProtectedModel = memory.createModel('protected', {}, {
|
var ProtectedModel = memory.createModel('protected', {}, {
|
||||||
protected: ['protectedProperty']
|
protected: ['protectedProperty'],
|
||||||
});
|
});
|
||||||
var pm = new ProtectedModel({
|
var pm = new ProtectedModel({
|
||||||
id: 1, foo: 'bar', protectedProperty: 'protected'
|
id: 1, foo: 'bar', protectedProperty: 'protected',
|
||||||
});
|
});
|
||||||
var serialized = pm.toJSON();
|
var serialized = pm.toJSON();
|
||||||
assert.deepEqual(serialized, {
|
assert.deepEqual(serialized, {
|
||||||
id: 1, foo: 'bar', protectedProperty: 'protected'
|
id: 1, foo: 'bar', protectedProperty: 'protected',
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
it('should not serialize protected properties of nested models into JSON', function(done){
|
it('should not serialize protected properties of nested models into JSON', function(done) {
|
||||||
var modelBuilder = memory.modelBuilder;
|
var modelBuilder = memory.modelBuilder;
|
||||||
var Parent = memory.createModel('parent');
|
var Parent = memory.createModel('parent');
|
||||||
var Child = memory.createModel('child', {}, {protected: ['protectedProperty']});
|
var Child = memory.createModel('child', {}, { protected: ['protectedProperty'] });
|
||||||
Parent.hasMany(Child);
|
Parent.hasMany(Child);
|
||||||
Parent.create({
|
Parent.create({
|
||||||
name: 'parent'
|
name: 'parent',
|
||||||
}, function(err, parent) {
|
}, function(err, parent) {
|
||||||
parent.children.create({
|
parent.children.create({
|
||||||
name: 'child',
|
name: 'child',
|
||||||
protectedProperty: 'protectedValue'
|
protectedProperty: 'protectedValue',
|
||||||
}, function(err, child) {
|
}, function(err, child) {
|
||||||
Parent.find({include: 'children'}, function(err, parents) {
|
Parent.find({ include: 'children' }, function(err, parents) {
|
||||||
var serialized = parents[0].toJSON();
|
var serialized = parents[0].toJSON();
|
||||||
var child = serialized.children[0];
|
var child = serialized.children[0];
|
||||||
assert.equal(child.name, 'child');
|
assert.equal(child.name, 'child');
|
||||||
|
@ -335,36 +335,36 @@ describe('ModelDefinition class', function () {
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
it('should not serialize hidden properties into JSON', function () {
|
it('should not serialize hidden properties into JSON', function() {
|
||||||
var modelBuilder = memory.modelBuilder;
|
var modelBuilder = memory.modelBuilder;
|
||||||
var HiddenModel = memory.createModel('hidden', {}, {
|
var HiddenModel = memory.createModel('hidden', {}, {
|
||||||
hidden: ['secret']
|
hidden: ['secret'],
|
||||||
});
|
});
|
||||||
var hm = new HiddenModel({
|
var hm = new HiddenModel({
|
||||||
id: 1,
|
id: 1,
|
||||||
foo: 'bar',
|
foo: 'bar',
|
||||||
secret: 'secret'
|
secret: 'secret',
|
||||||
});
|
});
|
||||||
var serialized = hm.toJSON();
|
var serialized = hm.toJSON();
|
||||||
assert.deepEqual(serialized, {
|
assert.deepEqual(serialized, {
|
||||||
id: 1,
|
id: 1,
|
||||||
foo: 'bar'
|
foo: 'bar',
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
it('should not serialize hidden properties of nested models into JSON', function (done) {
|
it('should not serialize hidden properties of nested models into JSON', function(done) {
|
||||||
var modelBuilder = memory.modelBuilder;
|
var modelBuilder = memory.modelBuilder;
|
||||||
var Parent = memory.createModel('parent');
|
var Parent = memory.createModel('parent');
|
||||||
var Child = memory.createModel('child', {}, {hidden: ['secret']});
|
var Child = memory.createModel('child', {}, { hidden: ['secret'] });
|
||||||
Parent.hasMany(Child);
|
Parent.hasMany(Child);
|
||||||
Parent.create({
|
Parent.create({
|
||||||
name: 'parent'
|
name: 'parent',
|
||||||
}, function(err, parent) {
|
}, function(err, parent) {
|
||||||
parent.children.create({
|
parent.children.create({
|
||||||
name: 'child',
|
name: 'child',
|
||||||
secret: 'secret'
|
secret: 'secret',
|
||||||
}, function(err, child) {
|
}, function(err, child) {
|
||||||
Parent.find({include: 'children'}, function(err, parents) {
|
Parent.find({ include: 'children' }, function(err, parents) {
|
||||||
var serialized = parents[0].toJSON();
|
var serialized = parents[0].toJSON();
|
||||||
var child = serialized.children[0];
|
var child = serialized.children[0];
|
||||||
assert.equal(child.name, 'child');
|
assert.equal(child.name, 'child');
|
||||||
|
@ -399,7 +399,7 @@ describe('ModelDefinition class', function () {
|
||||||
it('should support "array" type shortcut', function() {
|
it('should support "array" type shortcut', function() {
|
||||||
var Model = memory.createModel('TwoArrays', {
|
var Model = memory.createModel('TwoArrays', {
|
||||||
regular: Array,
|
regular: Array,
|
||||||
sugar: 'array'
|
sugar: 'array',
|
||||||
});
|
});
|
||||||
|
|
||||||
var props = Model.definition.properties;
|
var props = Model.definition.properties;
|
||||||
|
@ -411,11 +411,11 @@ describe('ModelDefinition class', function () {
|
||||||
var Todo;
|
var Todo;
|
||||||
before(function prepModel() {
|
before(function prepModel() {
|
||||||
Todo = new ModelDefinition(new ModelBuilder(), 'Todo', {
|
Todo = new ModelDefinition(new ModelBuilder(), 'Todo', {
|
||||||
content: 'string'
|
content: 'string',
|
||||||
});
|
});
|
||||||
Todo.defineProperty('id', {
|
Todo.defineProperty('id', {
|
||||||
type: 'number',
|
type: 'number',
|
||||||
id: true
|
id: true,
|
||||||
});
|
});
|
||||||
Todo.build();
|
Todo.build();
|
||||||
});
|
});
|
||||||
|
@ -429,7 +429,7 @@ describe('ModelDefinition class', function () {
|
||||||
var Todo;
|
var Todo;
|
||||||
before(function prepModel() {
|
before(function prepModel() {
|
||||||
Todo = new ModelDefinition(new ModelBuilder(), 'Todo', {
|
Todo = new ModelDefinition(new ModelBuilder(), 'Todo', {
|
||||||
content: 'string'
|
content: 'string',
|
||||||
});
|
});
|
||||||
Todo.build();
|
Todo.build();
|
||||||
});
|
});
|
||||||
|
|
|
@ -12,31 +12,31 @@ var ValidationError = j.ValidationError;
|
||||||
|
|
||||||
var INITIAL_NAME = 'Bert';
|
var INITIAL_NAME = 'Bert';
|
||||||
var NEW_NAME = 'Ernie';
|
var NEW_NAME = 'Ernie';
|
||||||
var INVALID_DATA = {name: null};
|
var INVALID_DATA = { name: null };
|
||||||
var VALID_DATA = {name: INITIAL_NAME};
|
var VALID_DATA = { name: INITIAL_NAME };
|
||||||
|
|
||||||
describe('optional-validation', function () {
|
describe('optional-validation', function() {
|
||||||
|
|
||||||
before(function (done) {
|
before(function(done) {
|
||||||
db = getSchema();
|
db = getSchema();
|
||||||
ModelWithForceId = db.createModel(
|
ModelWithForceId = db.createModel(
|
||||||
'ModelWithForceId',
|
'ModelWithForceId',
|
||||||
{ name: String },
|
{ name: String },
|
||||||
{ forceId: true });
|
{ forceId: true });
|
||||||
User = db.define('User', {
|
User = db.define('User', {
|
||||||
seq: {type: Number, index: true},
|
seq: { type: Number, index: true },
|
||||||
name: {type: String, index: true, sort: true},
|
name: { type: String, index: true, sort: true },
|
||||||
email: {type: String, index: true},
|
email: { type: String, index: true },
|
||||||
birthday: {type: Date, index: true},
|
birthday: { type: Date, index: true },
|
||||||
role: {type: String, index: true},
|
role: { type: String, index: true },
|
||||||
order: {type: Number, index: true, sort: true},
|
order: { type: Number, index: true, sort: true },
|
||||||
vip: {type: Boolean}
|
vip: { type: Boolean },
|
||||||
}, { forceId: true, strict: true });
|
}, { forceId: true, strict: true });
|
||||||
db.automigrate(['ModelWithForceId', 'User'], done);
|
db.automigrate(['ModelWithForceId', 'User'], done);
|
||||||
});
|
});
|
||||||
|
|
||||||
beforeEach(function (done) {
|
beforeEach(function(done) {
|
||||||
User.destroyAll(function () {
|
User.destroyAll(function() {
|
||||||
delete User.validations;
|
delete User.validations;
|
||||||
User.validatesPresenceOf('name');
|
User.validatesPresenceOf('name');
|
||||||
done();
|
done();
|
||||||
|
@ -44,7 +44,7 @@ describe('optional-validation', function () {
|
||||||
});
|
});
|
||||||
|
|
||||||
function expectValidationError(done) {
|
function expectValidationError(done) {
|
||||||
return function (err, result) {
|
return function(err, result) {
|
||||||
should.exist(err);
|
should.exist(err);
|
||||||
err.should.be.instanceOf(Error);
|
err.should.be.instanceOf(Error);
|
||||||
err.should.be.instanceOf(ValidationError);
|
err.should.be.instanceOf(ValidationError);
|
||||||
|
@ -87,27 +87,27 @@ describe('optional-validation', function () {
|
||||||
}
|
}
|
||||||
|
|
||||||
function createUserAndChangeName(name, cb) {
|
function createUserAndChangeName(name, cb) {
|
||||||
User.create(VALID_DATA, {validate: true}, function (err, d) {
|
User.create(VALID_DATA, { validate: true }, function(err, d) {
|
||||||
d.name = name;
|
d.name = name;
|
||||||
cb(err, d);
|
cb(err, d);
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
function createUser(cb) {
|
function createUser(cb) {
|
||||||
User.create(VALID_DATA, {validate: true}, cb);
|
User.create(VALID_DATA, { validate: true }, cb);
|
||||||
}
|
}
|
||||||
|
|
||||||
function callUpdateOrCreateWithExistingUserId(name, options, cb){
|
function callUpdateOrCreateWithExistingUserId(name, options, cb) {
|
||||||
User.create({'name': 'Groover'}, function(err, user){
|
User.create({ 'name': 'Groover' }, function(err, user) {
|
||||||
if (err) return cb(err);
|
if (err) return cb(err);
|
||||||
var data = {name: name};
|
var data = { name: name };
|
||||||
data.id = user.id;
|
data.id = user.id;
|
||||||
User.updateOrCreate(data, options, cb);
|
User.updateOrCreate(data, options, cb);
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
function getNewWhere() {
|
function getNewWhere() {
|
||||||
return {name: 'DoesNotExist' + (whereCount++)};
|
return { name: 'DoesNotExist' + (whereCount++) };
|
||||||
}
|
}
|
||||||
|
|
||||||
describe('forceId', function() {
|
describe('forceId', function() {
|
||||||
|
@ -136,284 +136,283 @@ describe('optional-validation', function () {
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
|
|
||||||
describe('no model setting', function() {
|
describe('no model setting', function() {
|
||||||
|
|
||||||
describe('method create', function() {
|
describe('method create', function() {
|
||||||
it('should throw on create with validate:true with invalid data', function (done) {
|
it('should throw on create with validate:true with invalid data', function(done) {
|
||||||
User.create(INVALID_DATA, {validate: true}, expectValidationError(done));
|
User.create(INVALID_DATA, { validate: true }, expectValidationError(done));
|
||||||
});
|
});
|
||||||
|
|
||||||
it('should NOT throw on create with validate:false with invalid data', function (done) {
|
it('should NOT throw on create with validate:false with invalid data', function(done) {
|
||||||
User.create(INVALID_DATA, {validate: false}, expectCreateSuccess(INVALID_DATA, done));
|
User.create(INVALID_DATA, { validate: false }, expectCreateSuccess(INVALID_DATA, done));
|
||||||
});
|
});
|
||||||
|
|
||||||
it('should NOT throw on create with validate:true with valid data', function (done) {
|
it('should NOT throw on create with validate:true with valid data', function(done) {
|
||||||
User.create(VALID_DATA, {validate: true}, expectCreateSuccess(done));
|
User.create(VALID_DATA, { validate: true }, expectCreateSuccess(done));
|
||||||
});
|
});
|
||||||
|
|
||||||
it('should NOT throw on create with validate:false with valid data', function (done) {
|
it('should NOT throw on create with validate:false with valid data', function(done) {
|
||||||
User.create(VALID_DATA, {validate: false}, expectCreateSuccess(done));
|
User.create(VALID_DATA, { validate: false }, expectCreateSuccess(done));
|
||||||
});
|
});
|
||||||
|
|
||||||
it('should throw on create with invalid data', function (done) {
|
it('should throw on create with invalid data', function(done) {
|
||||||
User.create(INVALID_DATA, expectValidationError(done));
|
User.create(INVALID_DATA, expectValidationError(done));
|
||||||
});
|
});
|
||||||
|
|
||||||
it('should NOT throw on create with valid data', function (done) {
|
it('should NOT throw on create with valid data', function(done) {
|
||||||
User.create(VALID_DATA, expectCreateSuccess(done));
|
User.create(VALID_DATA, expectCreateSuccess(done));
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
describe('method findOrCreate', function() {
|
describe('method findOrCreate', function() {
|
||||||
it('should throw on findOrCreate with validate:true with invalid data', function (done) {
|
it('should throw on findOrCreate with validate:true with invalid data', function(done) {
|
||||||
User.findOrCreate(getNewWhere(), INVALID_DATA, {validate: true}, expectValidationError(done));
|
User.findOrCreate(getNewWhere(), INVALID_DATA, { validate: true }, expectValidationError(done));
|
||||||
});
|
});
|
||||||
|
|
||||||
it('should NOT throw on findOrCreate with validate:false with invalid data', function (done) {
|
it('should NOT throw on findOrCreate with validate:false with invalid data', function(done) {
|
||||||
User.findOrCreate(getNewWhere(), INVALID_DATA, {validate: false}, expectCreateSuccess(INVALID_DATA, done));
|
User.findOrCreate(getNewWhere(), INVALID_DATA, { validate: false }, expectCreateSuccess(INVALID_DATA, done));
|
||||||
});
|
});
|
||||||
|
|
||||||
it('should NOT throw on findOrCreate with validate:true with valid data', function (done) {
|
it('should NOT throw on findOrCreate with validate:true with valid data', function(done) {
|
||||||
User.findOrCreate(getNewWhere(), VALID_DATA, {validate: true}, expectCreateSuccess(done));
|
User.findOrCreate(getNewWhere(), VALID_DATA, { validate: true }, expectCreateSuccess(done));
|
||||||
});
|
});
|
||||||
|
|
||||||
it('should NOT throw on findOrCreate with validate:false with valid data', function (done) {
|
it('should NOT throw on findOrCreate with validate:false with valid data', function(done) {
|
||||||
User.findOrCreate(getNewWhere(), VALID_DATA, {validate: false}, expectCreateSuccess(done));
|
User.findOrCreate(getNewWhere(), VALID_DATA, { validate: false }, expectCreateSuccess(done));
|
||||||
});
|
});
|
||||||
|
|
||||||
it('should throw on findOrCreate with invalid data', function (done) {
|
it('should throw on findOrCreate with invalid data', function(done) {
|
||||||
User.findOrCreate(getNewWhere(), INVALID_DATA, expectValidationError(done));
|
User.findOrCreate(getNewWhere(), INVALID_DATA, expectValidationError(done));
|
||||||
});
|
});
|
||||||
|
|
||||||
it('should NOT throw on findOrCreate with valid data', function (done) {
|
it('should NOT throw on findOrCreate with valid data', function(done) {
|
||||||
User.findOrCreate(getNewWhere(), VALID_DATA, expectCreateSuccess(done));
|
User.findOrCreate(getNewWhere(), VALID_DATA, expectCreateSuccess(done));
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
describe('method updateOrCreate on existing data', function() {
|
describe('method updateOrCreate on existing data', function() {
|
||||||
it('should throw on updateOrCreate(id) with validate:true with invalid data', function (done) {
|
it('should throw on updateOrCreate(id) with validate:true with invalid data', function(done) {
|
||||||
callUpdateOrCreateWithExistingUserId(null, {validate: true}, expectValidationError(done));
|
callUpdateOrCreateWithExistingUserId(null, { validate: true }, expectValidationError(done));
|
||||||
});
|
});
|
||||||
|
|
||||||
it('should NOT throw on updateOrCreate(id) with validate:false with invalid data', function (done) {
|
it('should NOT throw on updateOrCreate(id) with validate:false with invalid data', function(done) {
|
||||||
callUpdateOrCreateWithExistingUserId(null, {validate: false}, expectChangeSuccess(INVALID_DATA, done));
|
callUpdateOrCreateWithExistingUserId(null, { validate: false }, expectChangeSuccess(INVALID_DATA, done));
|
||||||
});
|
});
|
||||||
|
|
||||||
it('should NOT throw on updateOrCreate(id) with validate:true with valid data', function (done) {
|
it('should NOT throw on updateOrCreate(id) with validate:true with valid data', function(done) {
|
||||||
callUpdateOrCreateWithExistingUserId(NEW_NAME, {validate: true}, expectChangeSuccess(done));
|
callUpdateOrCreateWithExistingUserId(NEW_NAME, { validate: true }, expectChangeSuccess(done));
|
||||||
});
|
});
|
||||||
|
|
||||||
it('should NOT throw on updateOrCreate(id) with validate:false with valid data', function (done) {
|
it('should NOT throw on updateOrCreate(id) with validate:false with valid data', function(done) {
|
||||||
callUpdateOrCreateWithExistingUserId(NEW_NAME, {validate: false}, expectChangeSuccess(done));
|
callUpdateOrCreateWithExistingUserId(NEW_NAME, { validate: false }, expectChangeSuccess(done));
|
||||||
});
|
});
|
||||||
|
|
||||||
// backwards compatible with validateUpsert
|
// backwards compatible with validateUpsert
|
||||||
it('should NOT throw on updateOrCreate(id) with invalid data', function (done) {
|
it('should NOT throw on updateOrCreate(id) with invalid data', function(done) {
|
||||||
callUpdateOrCreateWithExistingUserId(null, expectChangeSuccess(INVALID_DATA, done));
|
callUpdateOrCreateWithExistingUserId(null, expectChangeSuccess(INVALID_DATA, done));
|
||||||
});
|
});
|
||||||
|
|
||||||
it('should NOT throw on updateOrCreate(id) with valid data', function (done) {
|
it('should NOT throw on updateOrCreate(id) with valid data', function(done) {
|
||||||
callUpdateOrCreateWithExistingUserId(NEW_NAME, expectChangeSuccess(done));
|
callUpdateOrCreateWithExistingUserId(NEW_NAME, expectChangeSuccess(done));
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
describe('method save', function() {
|
describe('method save', function() {
|
||||||
it('should throw on save with {validate:true} with invalid data', function (done) {
|
it('should throw on save with {validate:true} with invalid data', function(done) {
|
||||||
createUserAndChangeName(null, function (err, d) {
|
createUserAndChangeName(null, function(err, d) {
|
||||||
d.save({validate: true}, expectValidationError(done));
|
d.save({ validate: true }, expectValidationError(done));
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
it('should NOT throw on save with {validate:false} with invalid data', function (done) {
|
it('should NOT throw on save with {validate:false} with invalid data', function(done) {
|
||||||
createUserAndChangeName(null, function (err, d) {
|
createUserAndChangeName(null, function(err, d) {
|
||||||
d.save({validate: false}, expectChangeSuccess(INVALID_DATA, done));
|
d.save({ validate: false }, expectChangeSuccess(INVALID_DATA, done));
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
it('should NOT throw on save with {validate:true} with valid data', function (done) {
|
it('should NOT throw on save with {validate:true} with valid data', function(done) {
|
||||||
createUserAndChangeName(NEW_NAME, function (err, d) {
|
createUserAndChangeName(NEW_NAME, function(err, d) {
|
||||||
d.save({validate: true}, expectChangeSuccess(done));
|
d.save({ validate: true }, expectChangeSuccess(done));
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
it('should NOT throw on save with {validate:false} with valid data', function (done) {
|
it('should NOT throw on save with {validate:false} with valid data', function(done) {
|
||||||
createUserAndChangeName(NEW_NAME, function (err, d) {
|
createUserAndChangeName(NEW_NAME, function(err, d) {
|
||||||
d.save({validate: false}, expectChangeSuccess(done));
|
d.save({ validate: false }, expectChangeSuccess(done));
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
it('should throw on save(cb) with invalid data', function (done) {
|
it('should throw on save(cb) with invalid data', function(done) {
|
||||||
createUserAndChangeName(null, function (err, d) {
|
createUserAndChangeName(null, function(err, d) {
|
||||||
d.save(expectValidationError(done));
|
d.save(expectValidationError(done));
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
it('should NOT throw on save(cb) with valid data', function (done) {
|
it('should NOT throw on save(cb) with valid data', function(done) {
|
||||||
createUserAndChangeName(NEW_NAME, function (err, d) {
|
createUserAndChangeName(NEW_NAME, function(err, d) {
|
||||||
d.save(expectChangeSuccess(done));
|
d.save(expectChangeSuccess(done));
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
describe('method updateAttributes', function() {
|
describe('method updateAttributes', function() {
|
||||||
it('should throw on updateAttributes with {validate:true} with invalid data', function (done) {
|
it('should throw on updateAttributes with {validate:true} with invalid data', function(done) {
|
||||||
createUser(function (err, d) {
|
createUser(function(err, d) {
|
||||||
d.updateAttributes(INVALID_DATA, {validate: true}, expectValidationError(done));
|
d.updateAttributes(INVALID_DATA, { validate: true }, expectValidationError(done));
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
it('should NOT throw on updateAttributes with {validate:false} with invalid data', function (done) {
|
it('should NOT throw on updateAttributes with {validate:false} with invalid data', function(done) {
|
||||||
createUser(function (err, d) {
|
createUser(function(err, d) {
|
||||||
d.updateAttributes(INVALID_DATA, {validate: false}, expectChangeSuccess(INVALID_DATA, done));
|
d.updateAttributes(INVALID_DATA, { validate: false }, expectChangeSuccess(INVALID_DATA, done));
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
it('should NOT throw on updateAttributes with {validate:true} with valid data', function (done) {
|
it('should NOT throw on updateAttributes with {validate:true} with valid data', function(done) {
|
||||||
createUser(function (err, d) {
|
createUser(function(err, d) {
|
||||||
d.updateAttributes({'name': NEW_NAME}, {validate: true}, expectChangeSuccess(done));
|
d.updateAttributes({ 'name': NEW_NAME }, { validate: true }, expectChangeSuccess(done));
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
it('should NOT throw on updateAttributes with {validate:false} with valid data', function (done) {
|
it('should NOT throw on updateAttributes with {validate:false} with valid data', function(done) {
|
||||||
createUser(function (err, d) {
|
createUser(function(err, d) {
|
||||||
d.updateAttributes({'name': NEW_NAME}, {validate: false}, expectChangeSuccess(done));
|
d.updateAttributes({ 'name': NEW_NAME }, { validate: false }, expectChangeSuccess(done));
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
it('should throw on updateAttributes(cb) with invalid data', function (done) {
|
it('should throw on updateAttributes(cb) with invalid data', function(done) {
|
||||||
createUser(function (err, d) {
|
createUser(function(err, d) {
|
||||||
d.updateAttributes(INVALID_DATA, expectValidationError(done));
|
d.updateAttributes(INVALID_DATA, expectValidationError(done));
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
it('should NOT throw on updateAttributes(cb) with valid data', function (done) {
|
it('should NOT throw on updateAttributes(cb) with valid data', function(done) {
|
||||||
createUser(function (err, d) {
|
createUser(function(err, d) {
|
||||||
d.updateAttributes({'name': NEW_NAME}, expectChangeSuccess(done));
|
d.updateAttributes({ 'name': NEW_NAME }, expectChangeSuccess(done));
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
});
|
});
|
||||||
|
|
||||||
describe('model setting: automaticValidation: false', function () {
|
describe('model setting: automaticValidation: false', function() {
|
||||||
|
|
||||||
before(function (done) {
|
before(function(done) {
|
||||||
User.settings.automaticValidation = false;
|
User.settings.automaticValidation = false;
|
||||||
done();
|
done();
|
||||||
});
|
});
|
||||||
|
|
||||||
describe('method create', function() {
|
describe('method create', function() {
|
||||||
it('should throw on create with validate:true with invalid data', function (done) {
|
it('should throw on create with validate:true with invalid data', function(done) {
|
||||||
User.create(INVALID_DATA, {validate: true}, expectValidationError(done));
|
User.create(INVALID_DATA, { validate: true }, expectValidationError(done));
|
||||||
});
|
});
|
||||||
|
|
||||||
it('should NOT throw on create with validate:false with invalid data', function (done) {
|
it('should NOT throw on create with validate:false with invalid data', function(done) {
|
||||||
User.create(INVALID_DATA, {validate: false}, expectCreateSuccess(INVALID_DATA, done));
|
User.create(INVALID_DATA, { validate: false }, expectCreateSuccess(INVALID_DATA, done));
|
||||||
});
|
});
|
||||||
|
|
||||||
it('should NOT throw on create with validate:true with valid data', function (done) {
|
it('should NOT throw on create with validate:true with valid data', function(done) {
|
||||||
User.create(VALID_DATA, {validate: true}, expectCreateSuccess(done));
|
User.create(VALID_DATA, { validate: true }, expectCreateSuccess(done));
|
||||||
});
|
});
|
||||||
|
|
||||||
it('should NOT throw on create with validate:false with valid data', function (done) {
|
it('should NOT throw on create with validate:false with valid data', function(done) {
|
||||||
User.create(VALID_DATA, {validate: false}, expectCreateSuccess(done));
|
User.create(VALID_DATA, { validate: false }, expectCreateSuccess(done));
|
||||||
});
|
});
|
||||||
|
|
||||||
it('should NOT throw on create with invalid data', function (done) {
|
it('should NOT throw on create with invalid data', function(done) {
|
||||||
User.create(INVALID_DATA, expectCreateSuccess(INVALID_DATA, done));
|
User.create(INVALID_DATA, expectCreateSuccess(INVALID_DATA, done));
|
||||||
});
|
});
|
||||||
|
|
||||||
it('should NOT throw on create with valid data', function (done) {
|
it('should NOT throw on create with valid data', function(done) {
|
||||||
User.create(VALID_DATA, expectCreateSuccess(done));
|
User.create(VALID_DATA, expectCreateSuccess(done));
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
describe('method findOrCreate', function() {
|
describe('method findOrCreate', function() {
|
||||||
it('should throw on findOrCreate with validate:true with invalid data', function (done) {
|
it('should throw on findOrCreate with validate:true with invalid data', function(done) {
|
||||||
User.findOrCreate(getNewWhere(), INVALID_DATA, {validate: true}, expectValidationError(done));
|
User.findOrCreate(getNewWhere(), INVALID_DATA, { validate: true }, expectValidationError(done));
|
||||||
});
|
});
|
||||||
|
|
||||||
it('should NOT throw on findOrCreate with validate:false with invalid data', function (done) {
|
it('should NOT throw on findOrCreate with validate:false with invalid data', function(done) {
|
||||||
User.findOrCreate(getNewWhere(), INVALID_DATA, {validate: false}, expectCreateSuccess(INVALID_DATA, done));
|
User.findOrCreate(getNewWhere(), INVALID_DATA, { validate: false }, expectCreateSuccess(INVALID_DATA, done));
|
||||||
});
|
});
|
||||||
|
|
||||||
it('should NOT throw on findOrCreate with validate:true with valid data', function (done) {
|
it('should NOT throw on findOrCreate with validate:true with valid data', function(done) {
|
||||||
User.findOrCreate(getNewWhere(), VALID_DATA, {validate: true}, expectCreateSuccess(done));
|
User.findOrCreate(getNewWhere(), VALID_DATA, { validate: true }, expectCreateSuccess(done));
|
||||||
});
|
});
|
||||||
|
|
||||||
it('should NOT throw on findOrCreate with validate:false with valid data', function (done) {
|
it('should NOT throw on findOrCreate with validate:false with valid data', function(done) {
|
||||||
User.findOrCreate(getNewWhere(), VALID_DATA, {validate: false}, expectCreateSuccess(done));
|
User.findOrCreate(getNewWhere(), VALID_DATA, { validate: false }, expectCreateSuccess(done));
|
||||||
});
|
});
|
||||||
|
|
||||||
it('should NOT throw on findOrCreate with invalid data', function (done) {
|
it('should NOT throw on findOrCreate with invalid data', function(done) {
|
||||||
User.findOrCreate(getNewWhere(), INVALID_DATA, expectCreateSuccess(INVALID_DATA, done));
|
User.findOrCreate(getNewWhere(), INVALID_DATA, expectCreateSuccess(INVALID_DATA, done));
|
||||||
});
|
});
|
||||||
|
|
||||||
it('should NOT throw on findOrCreate with valid data', function (done) {
|
it('should NOT throw on findOrCreate with valid data', function(done) {
|
||||||
User.findOrCreate(getNewWhere(), VALID_DATA, expectCreateSuccess(done));
|
User.findOrCreate(getNewWhere(), VALID_DATA, expectCreateSuccess(done));
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
describe('method updateOrCreate on existing data', function() {
|
describe('method updateOrCreate on existing data', function() {
|
||||||
it('should throw on updateOrCreate(id) with validate:true with invalid data', function (done) {
|
it('should throw on updateOrCreate(id) with validate:true with invalid data', function(done) {
|
||||||
callUpdateOrCreateWithExistingUserId(null, {validate: true}, expectValidationError(done));
|
callUpdateOrCreateWithExistingUserId(null, { validate: true }, expectValidationError(done));
|
||||||
});
|
});
|
||||||
|
|
||||||
it('should NOT throw on updateOrCreate(id) with validate:false with invalid data', function (done) {
|
it('should NOT throw on updateOrCreate(id) with validate:false with invalid data', function(done) {
|
||||||
callUpdateOrCreateWithExistingUserId(null, {validate: false}, expectChangeSuccess(INVALID_DATA, done));
|
callUpdateOrCreateWithExistingUserId(null, { validate: false }, expectChangeSuccess(INVALID_DATA, done));
|
||||||
});
|
});
|
||||||
|
|
||||||
it('should NOT throw on updateOrCreate(id) with validate:true with valid data', function (done) {
|
it('should NOT throw on updateOrCreate(id) with validate:true with valid data', function(done) {
|
||||||
callUpdateOrCreateWithExistingUserId(NEW_NAME, {validate: true}, expectChangeSuccess(done));
|
callUpdateOrCreateWithExistingUserId(NEW_NAME, { validate: true }, expectChangeSuccess(done));
|
||||||
});
|
});
|
||||||
|
|
||||||
it('should NOT throw on updateOrCreate(id) with validate:false with valid data', function (done) {
|
it('should NOT throw on updateOrCreate(id) with validate:false with valid data', function(done) {
|
||||||
callUpdateOrCreateWithExistingUserId(NEW_NAME, {validate: false}, expectChangeSuccess(done));
|
callUpdateOrCreateWithExistingUserId(NEW_NAME, { validate: false }, expectChangeSuccess(done));
|
||||||
});
|
});
|
||||||
|
|
||||||
it('should NOT throw on updateOrCreate(id) with invalid data', function (done) {
|
it('should NOT throw on updateOrCreate(id) with invalid data', function(done) {
|
||||||
callUpdateOrCreateWithExistingUserId(null, expectChangeSuccess(INVALID_DATA, done));
|
callUpdateOrCreateWithExistingUserId(null, expectChangeSuccess(INVALID_DATA, done));
|
||||||
});
|
});
|
||||||
|
|
||||||
it('should NOT throw on updateOrCreate(id) with valid data', function (done) {
|
it('should NOT throw on updateOrCreate(id) with valid data', function(done) {
|
||||||
callUpdateOrCreateWithExistingUserId(NEW_NAME, expectChangeSuccess(done));
|
callUpdateOrCreateWithExistingUserId(NEW_NAME, expectChangeSuccess(done));
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
describe('method save', function() {
|
describe('method save', function() {
|
||||||
it('should throw on save with {validate:true} with invalid data', function (done) {
|
it('should throw on save with {validate:true} with invalid data', function(done) {
|
||||||
createUserAndChangeName(null, function (err, d) {
|
createUserAndChangeName(null, function(err, d) {
|
||||||
d.save({validate: true}, expectValidationError(done));
|
d.save({ validate: true }, expectValidationError(done));
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
it('should NOT throw on save with {validate:false} with invalid data', function (done) {
|
it('should NOT throw on save with {validate:false} with invalid data', function(done) {
|
||||||
createUserAndChangeName(null, function (err, d) {
|
createUserAndChangeName(null, function(err, d) {
|
||||||
d.save({validate: false}, expectChangeSuccess(INVALID_DATA, done));
|
d.save({ validate: false }, expectChangeSuccess(INVALID_DATA, done));
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
it('should NOT throw on save with {validate:true} with valid data', function (done) {
|
it('should NOT throw on save with {validate:true} with valid data', function(done) {
|
||||||
createUserAndChangeName(NEW_NAME, function (err, d) {
|
createUserAndChangeName(NEW_NAME, function(err, d) {
|
||||||
d.save({validate: true}, expectChangeSuccess(done));
|
d.save({ validate: true }, expectChangeSuccess(done));
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
it('should NOT throw on save with {validate:false} with valid data', function (done) {
|
it('should NOT throw on save with {validate:false} with valid data', function(done) {
|
||||||
createUserAndChangeName(NEW_NAME, function (err, d) {
|
createUserAndChangeName(NEW_NAME, function(err, d) {
|
||||||
d.save({validate: false}, expectChangeSuccess(done));
|
d.save({ validate: false }, expectChangeSuccess(done));
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
it('should NOT throw on save(cb) with invalid data', function (done) {
|
it('should NOT throw on save(cb) with invalid data', function(done) {
|
||||||
createUserAndChangeName(null, function (err, d) {
|
createUserAndChangeName(null, function(err, d) {
|
||||||
d.save(expectChangeSuccess(INVALID_DATA, done));
|
d.save(expectChangeSuccess(INVALID_DATA, done));
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
it('should NOT throw on save(cb) with valid data', function (done) {
|
it('should NOT throw on save(cb) with valid data', function(done) {
|
||||||
createUserAndChangeName(NEW_NAME, function (err, d) {
|
createUserAndChangeName(NEW_NAME, function(err, d) {
|
||||||
d.save(expectChangeSuccess(done));
|
d.save(expectChangeSuccess(done));
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
@ -421,124 +420,124 @@ describe('optional-validation', function () {
|
||||||
|
|
||||||
});
|
});
|
||||||
|
|
||||||
describe('model setting: automaticValidation: true', function () {
|
describe('model setting: automaticValidation: true', function() {
|
||||||
|
|
||||||
before(function (done) {
|
before(function(done) {
|
||||||
User.settings.automaticValidation = true;
|
User.settings.automaticValidation = true;
|
||||||
done();
|
done();
|
||||||
});
|
});
|
||||||
|
|
||||||
describe('method create', function() {
|
describe('method create', function() {
|
||||||
it('should throw on create with validate:true with invalid data', function (done) {
|
it('should throw on create with validate:true with invalid data', function(done) {
|
||||||
User.create(INVALID_DATA, {validate: true}, expectValidationError(done));
|
User.create(INVALID_DATA, { validate: true }, expectValidationError(done));
|
||||||
});
|
});
|
||||||
|
|
||||||
it('should NOT throw on create with validate:false with invalid data', function (done) {
|
it('should NOT throw on create with validate:false with invalid data', function(done) {
|
||||||
User.create(INVALID_DATA, {validate: false}, expectCreateSuccess(INVALID_DATA, done));
|
User.create(INVALID_DATA, { validate: false }, expectCreateSuccess(INVALID_DATA, done));
|
||||||
});
|
});
|
||||||
|
|
||||||
it('should NOT throw on create with validate:true with valid data', function (done) {
|
it('should NOT throw on create with validate:true with valid data', function(done) {
|
||||||
User.create(VALID_DATA, {validate: true}, expectCreateSuccess(done));
|
User.create(VALID_DATA, { validate: true }, expectCreateSuccess(done));
|
||||||
});
|
});
|
||||||
|
|
||||||
it('should NOT throw on create with validate:false with valid data', function (done) {
|
it('should NOT throw on create with validate:false with valid data', function(done) {
|
||||||
User.create(VALID_DATA, {validate: false}, expectCreateSuccess(done));
|
User.create(VALID_DATA, { validate: false }, expectCreateSuccess(done));
|
||||||
});
|
});
|
||||||
|
|
||||||
it('should throw on create with invalid data', function (done) {
|
it('should throw on create with invalid data', function(done) {
|
||||||
User.create(INVALID_DATA, expectValidationError(done));
|
User.create(INVALID_DATA, expectValidationError(done));
|
||||||
});
|
});
|
||||||
|
|
||||||
it('should NOT throw on create with valid data', function (done) {
|
it('should NOT throw on create with valid data', function(done) {
|
||||||
User.create(VALID_DATA, expectCreateSuccess(done));
|
User.create(VALID_DATA, expectCreateSuccess(done));
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
describe('method findOrCreate', function() {
|
describe('method findOrCreate', function() {
|
||||||
it('should throw on findOrCreate with validate:true with invalid data', function (done) {
|
it('should throw on findOrCreate with validate:true with invalid data', function(done) {
|
||||||
User.findOrCreate(getNewWhere(), INVALID_DATA, {validate: true}, expectValidationError(done));
|
User.findOrCreate(getNewWhere(), INVALID_DATA, { validate: true }, expectValidationError(done));
|
||||||
});
|
});
|
||||||
|
|
||||||
it('should NOT throw on findOrCreate with validate:false with invalid data', function (done) {
|
it('should NOT throw on findOrCreate with validate:false with invalid data', function(done) {
|
||||||
User.findOrCreate(getNewWhere(), INVALID_DATA, {validate: false}, expectCreateSuccess(INVALID_DATA, done));
|
User.findOrCreate(getNewWhere(), INVALID_DATA, { validate: false }, expectCreateSuccess(INVALID_DATA, done));
|
||||||
});
|
});
|
||||||
|
|
||||||
it('should NOT throw on findOrCreate with validate:true with valid data', function (done) {
|
it('should NOT throw on findOrCreate with validate:true with valid data', function(done) {
|
||||||
User.findOrCreate(getNewWhere(), VALID_DATA, {validate: true}, expectCreateSuccess(done));
|
User.findOrCreate(getNewWhere(), VALID_DATA, { validate: true }, expectCreateSuccess(done));
|
||||||
});
|
});
|
||||||
|
|
||||||
it('should NOT throw on findOrCreate with validate:false with valid data', function (done) {
|
it('should NOT throw on findOrCreate with validate:false with valid data', function(done) {
|
||||||
User.findOrCreate(getNewWhere(), VALID_DATA, {validate: false}, expectCreateSuccess(done));
|
User.findOrCreate(getNewWhere(), VALID_DATA, { validate: false }, expectCreateSuccess(done));
|
||||||
});
|
});
|
||||||
|
|
||||||
it('should throw on findOrCreate with invalid data', function (done) {
|
it('should throw on findOrCreate with invalid data', function(done) {
|
||||||
User.findOrCreate(getNewWhere(), INVALID_DATA, expectValidationError(done));
|
User.findOrCreate(getNewWhere(), INVALID_DATA, expectValidationError(done));
|
||||||
});
|
});
|
||||||
|
|
||||||
it('should NOT throw on findOrCreate with valid data', function (done) {
|
it('should NOT throw on findOrCreate with valid data', function(done) {
|
||||||
User.findOrCreate(getNewWhere(), VALID_DATA, expectCreateSuccess(done));
|
User.findOrCreate(getNewWhere(), VALID_DATA, expectCreateSuccess(done));
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
describe('method updateOrCreate on existing data', function() {
|
describe('method updateOrCreate on existing data', function() {
|
||||||
it('should throw on updateOrCreate(id) with validate:true with invalid data', function (done) {
|
it('should throw on updateOrCreate(id) with validate:true with invalid data', function(done) {
|
||||||
callUpdateOrCreateWithExistingUserId(null, {validate: true}, expectValidationError(done));
|
callUpdateOrCreateWithExistingUserId(null, { validate: true }, expectValidationError(done));
|
||||||
});
|
});
|
||||||
|
|
||||||
it('should NOT throw on updateOrCreate(id) with validate:false with invalid data', function (done) {
|
it('should NOT throw on updateOrCreate(id) with validate:false with invalid data', function(done) {
|
||||||
callUpdateOrCreateWithExistingUserId(null, {validate: false}, expectChangeSuccess(INVALID_DATA, done));
|
callUpdateOrCreateWithExistingUserId(null, { validate: false }, expectChangeSuccess(INVALID_DATA, done));
|
||||||
});
|
});
|
||||||
|
|
||||||
it('should NOT throw on updateOrCreate(id) with validate:true with valid data', function (done) {
|
it('should NOT throw on updateOrCreate(id) with validate:true with valid data', function(done) {
|
||||||
callUpdateOrCreateWithExistingUserId(NEW_NAME, {validate: true}, expectChangeSuccess(done));
|
callUpdateOrCreateWithExistingUserId(NEW_NAME, { validate: true }, expectChangeSuccess(done));
|
||||||
});
|
});
|
||||||
|
|
||||||
it('should NOT throw on updateOrCreate(id) with validate:false with valid data', function (done) {
|
it('should NOT throw on updateOrCreate(id) with validate:false with valid data', function(done) {
|
||||||
callUpdateOrCreateWithExistingUserId(NEW_NAME, {validate: false}, expectChangeSuccess(done));
|
callUpdateOrCreateWithExistingUserId(NEW_NAME, { validate: false }, expectChangeSuccess(done));
|
||||||
});
|
});
|
||||||
|
|
||||||
it('should throw on updateOrCreate(id) with invalid data', function (done) {
|
it('should throw on updateOrCreate(id) with invalid data', function(done) {
|
||||||
callUpdateOrCreateWithExistingUserId(null, expectValidationError(done));
|
callUpdateOrCreateWithExistingUserId(null, expectValidationError(done));
|
||||||
});
|
});
|
||||||
|
|
||||||
it('should NOT throw on updateOrCreate(id) with valid data', function (done) {
|
it('should NOT throw on updateOrCreate(id) with valid data', function(done) {
|
||||||
callUpdateOrCreateWithExistingUserId(NEW_NAME, expectChangeSuccess(done));
|
callUpdateOrCreateWithExistingUserId(NEW_NAME, expectChangeSuccess(done));
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
describe('method save', function() {
|
describe('method save', function() {
|
||||||
it('should throw on save with {validate:true} with invalid data', function (done) {
|
it('should throw on save with {validate:true} with invalid data', function(done) {
|
||||||
createUserAndChangeName(null, function (err, d) {
|
createUserAndChangeName(null, function(err, d) {
|
||||||
d.save(options, expectValidationError(done));
|
d.save(options, expectValidationError(done));
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
it('should NOT throw on save with {validate:false} with invalid data', function (done) {
|
it('should NOT throw on save with {validate:false} with invalid data', function(done) {
|
||||||
createUserAndChangeName(null, function (err, d) {
|
createUserAndChangeName(null, function(err, d) {
|
||||||
d.save({validate: false}, expectChangeSuccess(INVALID_DATA, done));
|
d.save({ validate: false }, expectChangeSuccess(INVALID_DATA, done));
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
it('should NOT throw on save with {validate:true} with valid data', function (done) {
|
it('should NOT throw on save with {validate:true} with valid data', function(done) {
|
||||||
createUserAndChangeName(NEW_NAME, function (err, d) {
|
createUserAndChangeName(NEW_NAME, function(err, d) {
|
||||||
d.save({validate: true}, expectChangeSuccess(done));
|
d.save({ validate: true }, expectChangeSuccess(done));
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
it('should NOT throw on save with {validate:false} with valid data', function (done) {
|
it('should NOT throw on save with {validate:false} with valid data', function(done) {
|
||||||
createUserAndChangeName(NEW_NAME, function (err, d) {
|
createUserAndChangeName(NEW_NAME, function(err, d) {
|
||||||
d.save({validate: false}, expectChangeSuccess(done));
|
d.save({ validate: false }, expectChangeSuccess(done));
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
it('should throw on save(cb) with invalid data', function (done) {
|
it('should throw on save(cb) with invalid data', function(done) {
|
||||||
createUserAndChangeName(null, function (err, d) {
|
createUserAndChangeName(null, function(err, d) {
|
||||||
d.save(expectValidationError(done));
|
d.save(expectValidationError(done));
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
it('should NOT throw on save(cb) with valid data', function (done) {
|
it('should NOT throw on save(cb) with valid data', function(done) {
|
||||||
createUserAndChangeName(NEW_NAME, function (err, d) {
|
createUserAndChangeName(NEW_NAME, function(err, d) {
|
||||||
d.save(expectChangeSuccess(done));
|
d.save(expectChangeSuccess(done));
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
|
@ -8,16 +8,16 @@ var should = require('./init.js');
|
||||||
|
|
||||||
var db = getSchema(), slave = getSchema(), Model, SlaveModel;
|
var db = getSchema(), slave = getSchema(), Model, SlaveModel;
|
||||||
|
|
||||||
describe('dataSource', function () {
|
describe('dataSource', function() {
|
||||||
|
|
||||||
it('should define Model', function () {
|
it('should define Model', function() {
|
||||||
Model = db.define('Model');
|
Model = db.define('Model');
|
||||||
Model.dataSource.should.eql(db);
|
Model.dataSource.should.eql(db);
|
||||||
var m = new Model;
|
var m = new Model;
|
||||||
m.getDataSource().should.eql(db);
|
m.getDataSource().should.eql(db);
|
||||||
});
|
});
|
||||||
|
|
||||||
it('should clone existing model', function () {
|
it('should clone existing model', function() {
|
||||||
SlaveModel = slave.copyModel(Model);
|
SlaveModel = slave.copyModel(Model);
|
||||||
SlaveModel.dataSource.should.equal(slave);
|
SlaveModel.dataSource.should.equal(slave);
|
||||||
slave.should.not.equal(db);
|
slave.should.not.equal(db);
|
||||||
|
@ -27,30 +27,30 @@ describe('dataSource', function () {
|
||||||
sm.getDataSource().should.equal(slave);
|
sm.getDataSource().should.equal(slave);
|
||||||
});
|
});
|
||||||
|
|
||||||
it('should automigrate', function (done) {
|
it('should automigrate', function(done) {
|
||||||
db.automigrate(done);
|
db.automigrate(done);
|
||||||
});
|
});
|
||||||
|
|
||||||
it('should create transaction', function (done) {
|
it('should create transaction', function(done) {
|
||||||
var tr = db.transaction();
|
var tr = db.transaction();
|
||||||
tr.connected.should.be.false;
|
tr.connected.should.be.false;
|
||||||
tr.connecting.should.be.false;
|
tr.connecting.should.be.false;
|
||||||
var called = false;
|
var called = false;
|
||||||
tr.models.Model.create(Array(3), function () {
|
tr.models.Model.create(Array(3), function() {
|
||||||
called = true;
|
called = true;
|
||||||
});
|
});
|
||||||
tr.connected.should.be.false;
|
tr.connected.should.be.false;
|
||||||
tr.connecting.should.be.true;
|
tr.connecting.should.be.true;
|
||||||
|
|
||||||
db.models.Model.count(function (err, c) {
|
db.models.Model.count(function(err, c) {
|
||||||
should.not.exist(err);
|
should.not.exist(err);
|
||||||
should.exist(c);
|
should.exist(c);
|
||||||
c.should.equal(0);
|
c.should.equal(0);
|
||||||
called.should.be.false;
|
called.should.be.false;
|
||||||
tr.exec(function () {
|
tr.exec(function() {
|
||||||
setTimeout(function () {
|
setTimeout(function() {
|
||||||
called.should.be.true;
|
called.should.be.true;
|
||||||
db.models.Model.count(function (err, c) {
|
db.models.Model.count(function(err, c) {
|
||||||
c.should.equal(3);
|
c.should.equal(3);
|
||||||
done();
|
done();
|
||||||
});
|
});
|
||||||
|
|
|
@ -8,45 +8,45 @@ var should = require('./init.js');
|
||||||
|
|
||||||
var db, Railway, Station;
|
var db, Railway, Station;
|
||||||
|
|
||||||
describe('scope', function () {
|
describe('scope', function() {
|
||||||
|
|
||||||
before(function () {
|
before(function() {
|
||||||
db = getSchema();
|
db = getSchema();
|
||||||
Railway = db.define('Railway', {
|
Railway = db.define('Railway', {
|
||||||
URID: {type: String, index: true}
|
URID: { type: String, index: true },
|
||||||
}, {
|
}, {
|
||||||
scopes: {
|
scopes: {
|
||||||
highSpeed: {
|
highSpeed: {
|
||||||
where: {
|
where: {
|
||||||
highSpeed: true
|
highSpeed: true,
|
||||||
}
|
},
|
||||||
}
|
},
|
||||||
}
|
},
|
||||||
});
|
});
|
||||||
Station = db.define('Station', {
|
Station = db.define('Station', {
|
||||||
USID: {type: String, index: true},
|
USID: { type: String, index: true },
|
||||||
capacity: {type: Number, index: true},
|
capacity: { type: Number, index: true },
|
||||||
thoughput: {type: Number, index: true},
|
thoughput: { type: Number, index: true },
|
||||||
isActive: {type: Boolean, index: true},
|
isActive: { type: Boolean, index: true },
|
||||||
isUndeground: {type: Boolean, index: true}
|
isUndeground: { type: Boolean, index: true },
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
beforeEach(function (done) {
|
beforeEach(function(done) {
|
||||||
Railway.destroyAll(function () {
|
Railway.destroyAll(function() {
|
||||||
Station.destroyAll(done);
|
Station.destroyAll(done);
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
it('should define scope using options.scopes', function () {
|
it('should define scope using options.scopes', function() {
|
||||||
Railway.scopes.should.have.property('highSpeed');
|
Railway.scopes.should.have.property('highSpeed');
|
||||||
Railway.highSpeed.should.be.function;
|
Railway.highSpeed.should.be.function;
|
||||||
});
|
});
|
||||||
|
|
||||||
it('should define scope with query', function (done) {
|
it('should define scope with query', function(done) {
|
||||||
Station.scope('active', {where: {isActive: true}});
|
Station.scope('active', { where: { isActive: true }});
|
||||||
Station.scopes.should.have.property('active');
|
Station.scopes.should.have.property('active');
|
||||||
Station.active.create(function (err, station) {
|
Station.active.create(function(err, station) {
|
||||||
should.not.exist(err);
|
should.not.exist(err);
|
||||||
should.exist(station);
|
should.exist(station);
|
||||||
should.exist(station.isActive);
|
should.exist(station.isActive);
|
||||||
|
@ -55,35 +55,35 @@ describe('scope', function () {
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
it('should allow scope chaining', function (done) {
|
it('should allow scope chaining', function(done) {
|
||||||
Station.scope('active', {where: {isActive: true}});
|
Station.scope('active', { where: { isActive: true }});
|
||||||
Station.scope('subway', {where: {isUndeground: true}});
|
Station.scope('subway', { where: { isUndeground: true }});
|
||||||
Station.active.subway.create(function (err, station) {
|
Station.active.subway.create(function(err, station) {
|
||||||
should.not.exist(err);
|
should.not.exist(err);
|
||||||
should.exist(station);
|
should.exist(station);
|
||||||
station.isActive.should.be.true;
|
station.isActive.should.be.true;
|
||||||
station.isUndeground.should.be.true;
|
station.isUndeground.should.be.true;
|
||||||
done();
|
done();
|
||||||
})
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
it('should query all', function (done) {
|
it('should query all', function(done) {
|
||||||
Station.scope('active', {where: {isActive: true}});
|
Station.scope('active', { where: { isActive: true }});
|
||||||
Station.scope('inactive', {where: {isActive: false}});
|
Station.scope('inactive', { where: { isActive: false }});
|
||||||
Station.scope('ground', {where: {isUndeground: true}});
|
Station.scope('ground', { where: { isUndeground: true }});
|
||||||
Station.active.ground.create(function () {
|
Station.active.ground.create(function() {
|
||||||
Station.inactive.ground.create(function () {
|
Station.inactive.ground.create(function() {
|
||||||
Station.ground.inactive(function (err, ss) {
|
Station.ground.inactive(function(err, ss) {
|
||||||
ss.should.have.lengthOf(1);
|
ss.should.have.lengthOf(1);
|
||||||
done();
|
done();
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
it('should not cache any results', function (done) {
|
it('should not cache any results', function(done) {
|
||||||
Station.scope('active', {where: {isActive: true}});
|
Station.scope('active', { where: { isActive: true }});
|
||||||
Station.active.create(function (err, s) {
|
Station.active.create(function(err, s) {
|
||||||
if (err) return done(err);
|
if (err) return done(err);
|
||||||
s.isActive.should.be.true;
|
s.isActive.should.be.true;
|
||||||
Station.active(function(err, ss) {
|
Station.active(function(err, ss) {
|
||||||
|
@ -105,34 +105,34 @@ describe('scope', function () {
|
||||||
|
|
||||||
});
|
});
|
||||||
|
|
||||||
describe('scope - order', function () {
|
describe('scope - order', function() {
|
||||||
|
|
||||||
before(function () {
|
before(function() {
|
||||||
db = getSchema();
|
db = getSchema();
|
||||||
Station = db.define('Station', {
|
Station = db.define('Station', {
|
||||||
name: {type: String, index: true},
|
name: { type: String, index: true },
|
||||||
order: {type: Number, index: true}
|
order: { type: Number, index: true },
|
||||||
});
|
});
|
||||||
Station.scope('reverse', {order: 'order DESC'});
|
Station.scope('reverse', { order: 'order DESC' });
|
||||||
});
|
});
|
||||||
|
|
||||||
beforeEach(function (done) {
|
beforeEach(function(done) {
|
||||||
Station.destroyAll(done);
|
Station.destroyAll(done);
|
||||||
});
|
});
|
||||||
|
|
||||||
beforeEach(function (done) {
|
beforeEach(function(done) {
|
||||||
Station.create({ name: 'a', order: 1 }, done);
|
Station.create({ name: 'a', order: 1 }, done);
|
||||||
});
|
});
|
||||||
|
|
||||||
beforeEach(function (done) {
|
beforeEach(function(done) {
|
||||||
Station.create({ name: 'b', order: 2 }, done);
|
Station.create({ name: 'b', order: 2 }, done);
|
||||||
});
|
});
|
||||||
|
|
||||||
beforeEach(function (done) {
|
beforeEach(function(done) {
|
||||||
Station.create({ name: 'c', order: 3 }, done);
|
Station.create({ name: 'c', order: 3 }, done);
|
||||||
});
|
});
|
||||||
|
|
||||||
it('should define scope with default order', function (done) {
|
it('should define scope with default order', function(done) {
|
||||||
Station.reverse(function(err, stations) {
|
Station.reverse(function(err, stations) {
|
||||||
stations[0].name.should.equal('c');
|
stations[0].name.should.equal('c');
|
||||||
stations[0].order.should.equal(3);
|
stations[0].order.should.equal(3);
|
||||||
|
@ -144,8 +144,8 @@ describe('scope - order', function () {
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
it('should override default scope order', function (done) {
|
it('should override default scope order', function(done) {
|
||||||
Station.reverse({order: 'order ASC'}, function(err, stations) {
|
Station.reverse({ order: 'order ASC' }, function(err, stations) {
|
||||||
stations[0].name.should.equal('a');
|
stations[0].name.should.equal('a');
|
||||||
stations[0].order.should.equal(1);
|
stations[0].order.should.equal(1);
|
||||||
stations[1].name.should.equal('b');
|
stations[1].name.should.equal('b');
|
||||||
|
@ -158,128 +158,128 @@ describe('scope - order', function () {
|
||||||
|
|
||||||
});
|
});
|
||||||
|
|
||||||
describe('scope - filtered count, updateAll and destroyAll', function () {
|
describe('scope - filtered count, updateAll and destroyAll', function() {
|
||||||
|
|
||||||
var stationA;
|
var stationA;
|
||||||
|
|
||||||
before(function () {
|
before(function() {
|
||||||
db = getSchema();
|
db = getSchema();
|
||||||
Station = db.define('Station', {
|
Station = db.define('Station', {
|
||||||
name: {type: String, index: true},
|
name: { type: String, index: true },
|
||||||
order: {type: Number, index: true},
|
order: { type: Number, index: true },
|
||||||
active: {type: Boolean, index: true, default: true},
|
active: { type: Boolean, index: true, default: true },
|
||||||
flagged: {type: Boolean, index: true, default: false}
|
flagged: { type: Boolean, index: true, default: false },
|
||||||
});
|
});
|
||||||
Station.scope('ordered', {order: 'order'});
|
Station.scope('ordered', { order: 'order' });
|
||||||
Station.scope('active', {where: { active: true}});
|
Station.scope('active', { where: { active: true }});
|
||||||
Station.scope('inactive', {where: { active: false}});
|
Station.scope('inactive', { where: { active: false }});
|
||||||
Station.scope('flagged', {where: { flagged: true}});
|
Station.scope('flagged', { where: { flagged: true }});
|
||||||
});
|
});
|
||||||
|
|
||||||
beforeEach(function (done) {
|
beforeEach(function(done) {
|
||||||
Station.destroyAll(done);
|
Station.destroyAll(done);
|
||||||
});
|
});
|
||||||
|
|
||||||
beforeEach(function (done) {
|
beforeEach(function(done) {
|
||||||
Station.create({ name: 'b', order: 2, active: false }, done);
|
Station.create({ name: 'b', order: 2, active: false }, done);
|
||||||
});
|
});
|
||||||
|
|
||||||
beforeEach(function (done) {
|
beforeEach(function(done) {
|
||||||
Station.create({ name: 'a', order: 1 }, function(err, inst) {
|
Station.create({ name: 'a', order: 1 }, function(err, inst) {
|
||||||
stationA = inst;
|
stationA = inst;
|
||||||
done();
|
done();
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
beforeEach(function (done) {
|
beforeEach(function(done) {
|
||||||
Station.create({ name: 'd', order: 4, active: false }, done);
|
Station.create({ name: 'd', order: 4, active: false }, done);
|
||||||
});
|
});
|
||||||
|
|
||||||
beforeEach(function (done) {
|
beforeEach(function(done) {
|
||||||
Station.create({ name: 'c', order: 3 }, done);
|
Station.create({ name: 'c', order: 3 }, done);
|
||||||
});
|
});
|
||||||
|
|
||||||
it('should find all - verify', function(done) {
|
it('should find all - verify', function(done) {
|
||||||
Station.ordered(function(err, stations) {
|
Station.ordered(function(err, stations) {
|
||||||
should.not.exist(err);
|
should.not.exist(err);
|
||||||
stations.should.have.length(4);
|
stations.should.have.length(4);
|
||||||
stations[0].name.should.equal('a');
|
stations[0].name.should.equal('a');
|
||||||
stations[1].name.should.equal('b');
|
stations[1].name.should.equal('b');
|
||||||
stations[2].name.should.equal('c');
|
stations[2].name.should.equal('c');
|
||||||
stations[3].name.should.equal('d');
|
stations[3].name.should.equal('d');
|
||||||
done();
|
done();
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
it('should find one', function(done) {
|
it('should find one', function(done) {
|
||||||
Station.active.findOne(function(err, station) {
|
Station.active.findOne(function(err, station) {
|
||||||
should.not.exist(err);
|
should.not.exist(err);
|
||||||
station.name.should.equal('a');
|
station.name.should.equal('a');
|
||||||
done();
|
done();
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
it('should find one - with filter', function(done) {
|
it('should find one - with filter', function(done) {
|
||||||
Station.active.findOne({ where: { name: 'c' } }, function(err, station) {
|
Station.active.findOne({ where: { name: 'c' }}, function(err, station) {
|
||||||
should.not.exist(err);
|
should.not.exist(err);
|
||||||
station.name.should.equal('c');
|
station.name.should.equal('c');
|
||||||
done();
|
done();
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
it('should find by id - match', function(done) {
|
it('should find by id - match', function(done) {
|
||||||
Station.active.findById(stationA.id, function(err, station) {
|
Station.active.findById(stationA.id, function(err, station) {
|
||||||
should.not.exist(err);
|
should.not.exist(err);
|
||||||
station.name.should.equal('a');
|
station.name.should.equal('a');
|
||||||
done();
|
done();
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
it('should find by id - no match', function(done) {
|
it('should find by id - no match', function(done) {
|
||||||
Station.inactive.findById(stationA.id, function(err, station) {
|
Station.inactive.findById(stationA.id, function(err, station) {
|
||||||
should.not.exist(err);
|
should.not.exist(err);
|
||||||
should.not.exist(station);
|
should.not.exist(station);
|
||||||
done();
|
done();
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
it('should count all in scope - active', function(done) {
|
it('should count all in scope - active', function(done) {
|
||||||
Station.active.count(function(err, count) {
|
Station.active.count(function(err, count) {
|
||||||
should.not.exist(err);
|
should.not.exist(err);
|
||||||
count.should.equal(2);
|
count.should.equal(2);
|
||||||
done();
|
done();
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
it('should count all in scope - inactive', function(done) {
|
it('should count all in scope - inactive', function(done) {
|
||||||
Station.inactive.count(function(err, count) {
|
Station.inactive.count(function(err, count) {
|
||||||
should.not.exist(err);
|
should.not.exist(err);
|
||||||
count.should.equal(2);
|
count.should.equal(2);
|
||||||
done();
|
done();
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
it('should count filtered - active', function(done) {
|
it('should count filtered - active', function(done) {
|
||||||
Station.active.count({ order: { gt: 1 } }, function(err, count) {
|
Station.active.count({ order: { gt: 1 }}, function(err, count) {
|
||||||
should.not.exist(err);
|
should.not.exist(err);
|
||||||
count.should.equal(1);
|
count.should.equal(1);
|
||||||
done();
|
done();
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
it('should count filtered - inactive', function(done) {
|
it('should count filtered - inactive', function(done) {
|
||||||
Station.inactive.count({ order: 2 }, function(err, count) {
|
Station.inactive.count({ order: 2 }, function(err, count) {
|
||||||
should.not.exist(err);
|
should.not.exist(err);
|
||||||
count.should.equal(1);
|
count.should.equal(1);
|
||||||
done();
|
done();
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
it('should allow updateAll', function(done) {
|
it('should allow updateAll', function(done) {
|
||||||
Station.inactive.updateAll({ flagged: true }, function(err, result) {
|
Station.inactive.updateAll({ flagged: true }, function(err, result) {
|
||||||
should.not.exist(err);
|
should.not.exist(err);
|
||||||
result.count.should.equal(2);
|
result.count.should.equal(2);
|
||||||
verify();
|
verify();
|
||||||
});
|
});
|
||||||
|
|
||||||
var verify = function() {
|
var verify = function() {
|
||||||
|
@ -293,9 +293,9 @@ describe('scope - filtered count, updateAll and destroyAll', function () {
|
||||||
|
|
||||||
it('should allow filtered updateAll', function(done) {
|
it('should allow filtered updateAll', function(done) {
|
||||||
Station.ordered.updateAll({ active: true }, { flagged: true }, function(err, result) {
|
Station.ordered.updateAll({ active: true }, { flagged: true }, function(err, result) {
|
||||||
should.not.exist(err);
|
should.not.exist(err);
|
||||||
result.count.should.equal(2);
|
result.count.should.equal(2);
|
||||||
verify();
|
verify();
|
||||||
});
|
});
|
||||||
|
|
||||||
var verify = function() {
|
var verify = function() {
|
||||||
|
@ -309,8 +309,8 @@ describe('scope - filtered count, updateAll and destroyAll', function () {
|
||||||
|
|
||||||
it('should allow filtered destroyAll', function(done) {
|
it('should allow filtered destroyAll', function(done) {
|
||||||
Station.ordered.destroyAll({ active: false }, function(err) {
|
Station.ordered.destroyAll({ active: false }, function(err) {
|
||||||
should.not.exist(err);
|
should.not.exist(err);
|
||||||
verify();
|
verify();
|
||||||
});
|
});
|
||||||
|
|
||||||
var verify = function() {
|
var verify = function() {
|
||||||
|
@ -318,9 +318,9 @@ describe('scope - filtered count, updateAll and destroyAll', function () {
|
||||||
should.not.exist(err);
|
should.not.exist(err);
|
||||||
count.should.equal(2);
|
count.should.equal(2);
|
||||||
Station.inactive.count(function(err, count) {
|
Station.inactive.count(function(err, count) {
|
||||||
should.not.exist(err);
|
should.not.exist(err);
|
||||||
count.should.equal(0);
|
count.should.equal(0);
|
||||||
done();
|
done();
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
};
|
};
|
||||||
|
@ -328,17 +328,17 @@ describe('scope - filtered count, updateAll and destroyAll', function () {
|
||||||
|
|
||||||
});
|
});
|
||||||
|
|
||||||
describe('scope - dynamic target class', function () {
|
describe('scope - dynamic target class', function() {
|
||||||
|
|
||||||
var Collection, Media, Image, Video;
|
var Collection, Media, Image, Video;
|
||||||
|
|
||||||
|
|
||||||
before(function () {
|
before(function() {
|
||||||
db = getSchema();
|
db = getSchema();
|
||||||
Image = db.define('Image', {name: String});
|
Image = db.define('Image', { name: String });
|
||||||
Video = db.define('Video', {name: String});
|
Video = db.define('Video', { name: String });
|
||||||
|
|
||||||
Collection = db.define('Collection', {name: String, modelName: String});
|
Collection = db.define('Collection', { name: String, modelName: String });
|
||||||
Collection.scope('items', function() {
|
Collection.scope('items', function() {
|
||||||
return {}; // could return a scope based on `this` (receiver)
|
return {}; // could return a scope based on `this` (receiver)
|
||||||
}, null, {}, { isStatic: false, modelTo: function(receiver) {
|
}, null, {}, { isStatic: false, modelTo: function(receiver) {
|
||||||
|
@ -346,36 +346,36 @@ describe('scope - dynamic target class', function () {
|
||||||
} });
|
} });
|
||||||
});
|
});
|
||||||
|
|
||||||
beforeEach(function (done) {
|
beforeEach(function(done) {
|
||||||
Collection.destroyAll(function() {
|
Collection.destroyAll(function() {
|
||||||
Image.destroyAll(function() {
|
Image.destroyAll(function() {
|
||||||
Video.destroyAll(done);
|
Video.destroyAll(done);
|
||||||
})
|
});
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
beforeEach(function (done) {
|
beforeEach(function(done) {
|
||||||
Collection.create({ name: 'Images', modelName: 'Image' }, done);
|
Collection.create({ name: 'Images', modelName: 'Image' }, done);
|
||||||
});
|
});
|
||||||
|
|
||||||
beforeEach(function (done) {
|
beforeEach(function(done) {
|
||||||
Collection.create({ name: 'Videos', modelName: 'Video' }, done);
|
Collection.create({ name: 'Videos', modelName: 'Video' }, done);
|
||||||
});
|
});
|
||||||
|
|
||||||
beforeEach(function (done) {
|
beforeEach(function(done) {
|
||||||
Collection.create({ name: 'Things', modelName: 'Unknown' }, done);
|
Collection.create({ name: 'Things', modelName: 'Unknown' }, done);
|
||||||
});
|
});
|
||||||
|
|
||||||
beforeEach(function (done) {
|
beforeEach(function(done) {
|
||||||
Image.create({ name: 'Image A' }, done);
|
Image.create({ name: 'Image A' }, done);
|
||||||
});
|
});
|
||||||
|
|
||||||
beforeEach(function (done) {
|
beforeEach(function(done) {
|
||||||
Video.create({ name: 'Video A' }, done);
|
Video.create({ name: 'Video A' }, done);
|
||||||
});
|
});
|
||||||
|
|
||||||
it('should deduce modelTo at runtime - Image', function(done) {
|
it('should deduce modelTo at runtime - Image', function(done) {
|
||||||
Collection.findOne({ where: { modelName: 'Image' } }, function(err, coll) {
|
Collection.findOne({ where: { modelName: 'Image' }}, function(err, coll) {
|
||||||
should.not.exist(err);
|
should.not.exist(err);
|
||||||
coll.name.should.equal('Images');
|
coll.name.should.equal('Images');
|
||||||
coll.items(function(err, items) {
|
coll.items(function(err, items) {
|
||||||
|
@ -389,7 +389,7 @@ describe('scope - dynamic target class', function () {
|
||||||
});
|
});
|
||||||
|
|
||||||
it('should deduce modelTo at runtime - Video', function(done) {
|
it('should deduce modelTo at runtime - Video', function(done) {
|
||||||
Collection.findOne({ where: { modelName: 'Video' } }, function(err, coll) {
|
Collection.findOne({ where: { modelName: 'Video' }}, function(err, coll) {
|
||||||
should.not.exist(err);
|
should.not.exist(err);
|
||||||
coll.name.should.equal('Videos');
|
coll.name.should.equal('Videos');
|
||||||
coll.items(function(err, items) {
|
coll.items(function(err, items) {
|
||||||
|
@ -403,10 +403,10 @@ describe('scope - dynamic target class', function () {
|
||||||
});
|
});
|
||||||
|
|
||||||
it('should throw if modelTo is invalid', function(done) {
|
it('should throw if modelTo is invalid', function(done) {
|
||||||
Collection.findOne({ where: { name: 'Things' } }, function(err, coll) {
|
Collection.findOne({ where: { name: 'Things' }}, function(err, coll) {
|
||||||
should.not.exist(err);
|
should.not.exist(err);
|
||||||
coll.modelName.should.equal('Unknown');
|
coll.modelName.should.equal('Unknown');
|
||||||
(function () {
|
(function() {
|
||||||
coll.items(function(err, items) {});
|
coll.items(function(err, items) {});
|
||||||
}).should.throw();
|
}).should.throw();
|
||||||
done();
|
done();
|
||||||
|
@ -415,34 +415,34 @@ describe('scope - dynamic target class', function () {
|
||||||
|
|
||||||
});
|
});
|
||||||
|
|
||||||
describe('scope - dynamic function', function () {
|
describe('scope - dynamic function', function() {
|
||||||
|
|
||||||
var Item,seed=0;
|
var Item, seed = 0;
|
||||||
|
|
||||||
before(function () {
|
before(function() {
|
||||||
db = getSchema();
|
db = getSchema();
|
||||||
Item = db.define('Item', {title: Number,creator:Number});
|
Item = db.define('Item', { title: Number, creator:Number });
|
||||||
Item.scope('dynamicQuery', function () {
|
Item.scope('dynamicQuery', function() {
|
||||||
seed++;
|
seed++;
|
||||||
return {where:{creator:seed}};
|
return { where:{ creator:seed }};
|
||||||
})
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
beforeEach(function (done) {
|
beforeEach(function(done) {
|
||||||
Item.create({ title:1,creator:1 }, function () {
|
Item.create({ title:1, creator:1 }, function() {
|
||||||
Item.create({ title:2,creator:2 },done)
|
Item.create({ title:2, creator:2 }, done);
|
||||||
})
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
it('should deduce item by runtime creator', function (done) {
|
it('should deduce item by runtime creator', function(done) {
|
||||||
Item.dynamicQuery.findOne(function (err,firstQuery) {
|
Item.dynamicQuery.findOne(function(err, firstQuery) {
|
||||||
should.not.exist(err);
|
should.not.exist(err);
|
||||||
firstQuery.title.should.equal(1);
|
firstQuery.title.should.equal(1);
|
||||||
Item.dynamicQuery.findOne(function (err,secondQuery) {
|
Item.dynamicQuery.findOne(function(err, secondQuery) {
|
||||||
should.not.exist(err);
|
should.not.exist(err);
|
||||||
secondQuery.title.should.equal(2);
|
secondQuery.title.should.equal(2);
|
||||||
done();
|
done();
|
||||||
})
|
});
|
||||||
})
|
});
|
||||||
})
|
});
|
||||||
});
|
});
|
||||||
|
|
|
@ -28,12 +28,12 @@ function context(name, tests) {
|
||||||
EXT_EXP[name] = {};
|
EXT_EXP[name] = {};
|
||||||
group_name = name;
|
group_name = name;
|
||||||
tests({
|
tests({
|
||||||
before: function (f) {
|
before: function(f) {
|
||||||
it('setUp', f);
|
it('setUp', f);
|
||||||
},
|
},
|
||||||
after: function (f) {
|
after: function(f) {
|
||||||
it('tearDown', f);
|
it('tearDown', f);
|
||||||
}
|
},
|
||||||
});
|
});
|
||||||
group_name = false;
|
group_name = false;
|
||||||
}
|
}
|
||||||
|
|
|
@ -12,32 +12,32 @@ var should = require('./init.js');
|
||||||
var db, TransientModel, Person, Widget, Item;
|
var db, TransientModel, Person, Widget, Item;
|
||||||
|
|
||||||
var getTransientDataSource = function(settings) {
|
var getTransientDataSource = function(settings) {
|
||||||
return new DataSource('transient', settings);
|
return new DataSource('transient', settings);
|
||||||
};
|
};
|
||||||
|
|
||||||
describe('Transient connector', function () {
|
describe('Transient connector', function() {
|
||||||
|
|
||||||
before(function () {
|
before(function() {
|
||||||
db = getTransientDataSource();
|
db = getTransientDataSource();
|
||||||
TransientModel = db.define('TransientModel', {}, { idInjection: false });
|
TransientModel = db.define('TransientModel', {}, { idInjection: false });
|
||||||
|
|
||||||
Person = TransientModel.extend('Person', {name: String});
|
Person = TransientModel.extend('Person', { name: String });
|
||||||
Person.attachTo(db);
|
Person.attachTo(db);
|
||||||
|
|
||||||
Widget = db.define('Widget', {name: String});
|
Widget = db.define('Widget', { name: String });
|
||||||
Item = db.define('Item', {
|
Item = db.define('Item', {
|
||||||
id: {type: Number, id: true}, name: String
|
id: { type: Number, id: true }, name: String,
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
it('should respect idInjection being false', function(done) {
|
it('should respect idInjection being false', function(done) {
|
||||||
should.not.exist(Person.definition.properties.id);
|
should.not.exist(Person.definition.properties.id);
|
||||||
should.exist(Person.definition.properties.name);
|
should.exist(Person.definition.properties.name);
|
||||||
|
|
||||||
Person.create({ name: 'Wilma' }, function(err, inst) {
|
Person.create({ name: 'Wilma' }, function(err, inst) {
|
||||||
should.not.exist(err);
|
should.not.exist(err);
|
||||||
inst.toObject().should.eql({ name: 'Wilma' });
|
inst.toObject().should.eql({ name: 'Wilma' });
|
||||||
|
|
||||||
Person.count(function(err, count) {
|
Person.count(function(err, count) {
|
||||||
should.not.exist(err);
|
should.not.exist(err);
|
||||||
count.should.equal(0);
|
count.should.equal(0);
|
||||||
|
@ -45,18 +45,18 @@ describe('Transient connector', function () {
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
it('should generate a random string id', function(done) {
|
it('should generate a random string id', function(done) {
|
||||||
should.exist(Widget.definition.properties.id);
|
should.exist(Widget.definition.properties.id);
|
||||||
should.exist(Widget.definition.properties.name);
|
should.exist(Widget.definition.properties.name);
|
||||||
|
|
||||||
Widget.definition.properties.id.type.should.equal(String);
|
Widget.definition.properties.id.type.should.equal(String);
|
||||||
|
|
||||||
Widget.create({ name: 'Thing' }, function(err, inst) {
|
Widget.create({ name: 'Thing' }, function(err, inst) {
|
||||||
should.not.exist(err);
|
should.not.exist(err);
|
||||||
inst.id.should.match(/^[0-9a-fA-F]{24}$/);
|
inst.id.should.match(/^[0-9a-fA-F]{24}$/);
|
||||||
inst.name.should.equal('Thing');
|
inst.name.should.equal('Thing');
|
||||||
|
|
||||||
Widget.findById(inst.id, function(err, widget) {
|
Widget.findById(inst.id, function(err, widget) {
|
||||||
should.not.exist(err);
|
should.not.exist(err);
|
||||||
should.not.exist(widget);
|
should.not.exist(widget);
|
||||||
|
@ -64,17 +64,17 @@ describe('Transient connector', function () {
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
it('should generate a random number id', function(done) {
|
it('should generate a random number id', function(done) {
|
||||||
should.exist(Item.definition.properties.id);
|
should.exist(Item.definition.properties.id);
|
||||||
should.exist(Item.definition.properties.name);
|
should.exist(Item.definition.properties.name);
|
||||||
|
|
||||||
Item.definition.properties.id.type.should.equal(Number);
|
Item.definition.properties.id.type.should.equal(Number);
|
||||||
|
|
||||||
Item.create({ name: 'Example' }, function(err, inst) {
|
Item.create({ name: 'Example' }, function(err, inst) {
|
||||||
should.not.exist(err);
|
should.not.exist(err);
|
||||||
inst.name.should.equal('Example');
|
inst.name.should.equal('Example');
|
||||||
|
|
||||||
Item.count(function(err, count) {
|
Item.count(function(err, count) {
|
||||||
should.not.exist(err);
|
should.not.exist(err);
|
||||||
count.should.equal(0);
|
count.should.equal(0);
|
||||||
|
@ -82,5 +82,5 @@ describe('Transient connector', function () {
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
});
|
});
|
||||||
|
|
|
@ -12,54 +12,54 @@ var mergeIncludes = utils.mergeIncludes;
|
||||||
var sortObjectsByIds = utils.sortObjectsByIds;
|
var sortObjectsByIds = utils.sortObjectsByIds;
|
||||||
var uniq = utils.uniq;
|
var uniq = utils.uniq;
|
||||||
|
|
||||||
describe('util.fieldsToArray', function () {
|
describe('util.fieldsToArray', function() {
|
||||||
function sample(fields, excludeUnknown) {
|
function sample(fields, excludeUnknown) {
|
||||||
var properties = ['foo', 'bar', 'bat', 'baz'];
|
var properties = ['foo', 'bar', 'bat', 'baz'];
|
||||||
return {
|
return {
|
||||||
expect: function (arr) {
|
expect: function(arr) {
|
||||||
should.deepEqual(fieldsToArray(fields, properties, excludeUnknown), arr);
|
should.deepEqual(fieldsToArray(fields, properties, excludeUnknown), arr);
|
||||||
}
|
},
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
it('Turn objects and strings into an array of fields' +
|
it('Turn objects and strings into an array of fields' +
|
||||||
' to include when finding models', function () {
|
' to include when finding models', function() {
|
||||||
|
|
||||||
sample(false).expect(undefined);
|
sample(false).expect(undefined);
|
||||||
sample(null).expect(undefined);
|
sample(null).expect(undefined);
|
||||||
sample({}).expect(undefined);
|
sample({}).expect(undefined);
|
||||||
sample('foo').expect(['foo']);
|
sample('foo').expect(['foo']);
|
||||||
sample(['foo']).expect(['foo']);
|
sample(['foo']).expect(['foo']);
|
||||||
sample({'foo': 1}).expect(['foo']);
|
sample({ 'foo': 1 }).expect(['foo']);
|
||||||
sample({'bat': true}).expect(['bat']);
|
sample({ 'bat': true }).expect(['bat']);
|
||||||
sample({'bat': 0}).expect(['foo', 'bar', 'baz']);
|
sample({ 'bat': 0 }).expect(['foo', 'bar', 'baz']);
|
||||||
sample({'bat': false}).expect(['foo', 'bar', 'baz']);
|
sample({ 'bat': false }).expect(['foo', 'bar', 'baz']);
|
||||||
});
|
});
|
||||||
|
|
||||||
it('should exclude unknown properties', function () {
|
it('should exclude unknown properties', function() {
|
||||||
|
|
||||||
sample(false, true).expect(undefined);
|
sample(false, true).expect(undefined);
|
||||||
sample(null, true).expect(undefined);
|
sample(null, true).expect(undefined);
|
||||||
sample({}, true).expect(undefined);
|
sample({}, true).expect(undefined);
|
||||||
sample('foo', true).expect(['foo']);
|
sample('foo', true).expect(['foo']);
|
||||||
sample(['foo', 'unknown'], true).expect(['foo']);
|
sample(['foo', 'unknown'], true).expect(['foo']);
|
||||||
sample({'foo': 1, unknown: 1}, true).expect(['foo']);
|
sample({ 'foo': 1, unknown: 1 }, true).expect(['foo']);
|
||||||
sample({'bat': true, unknown: true}, true).expect(['bat']);
|
sample({ 'bat': true, unknown: true }, true).expect(['bat']);
|
||||||
sample({'bat': 0}, true).expect(['foo', 'bar', 'baz']);
|
sample({ 'bat': 0 }, true).expect(['foo', 'bar', 'baz']);
|
||||||
sample({'bat': false}, true).expect(['foo', 'bar', 'baz']);
|
sample({ 'bat': false }, true).expect(['foo', 'bar', 'baz']);
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
describe('util.removeUndefined', function () {
|
describe('util.removeUndefined', function() {
|
||||||
it('Remove undefined values from the query object', function () {
|
it('Remove undefined values from the query object', function() {
|
||||||
var q1 = {where: {x: 1, y: undefined}};
|
var q1 = { where: { x: 1, y: undefined }};
|
||||||
should.deepEqual(removeUndefined(q1), {where: {x: 1}});
|
should.deepEqual(removeUndefined(q1), { where: { x: 1 }});
|
||||||
|
|
||||||
var q2 = {where: {x: 1, y: 2}};
|
var q2 = { where: { x: 1, y: 2 }};
|
||||||
should.deepEqual(removeUndefined(q2), {where: {x: 1, y: 2}});
|
should.deepEqual(removeUndefined(q2), { where: { x: 1, y: 2 }});
|
||||||
|
|
||||||
var q3 = {where: {x: 1, y: {in: [2, undefined]}}};
|
var q3 = { where: { x: 1, y: { in: [2, undefined] }}};
|
||||||
should.deepEqual(removeUndefined(q3), {where: {x: 1, y: {in: [2]}}});
|
should.deepEqual(removeUndefined(q3), { where: { x: 1, y: { in: [2] }}});
|
||||||
|
|
||||||
should.equal(removeUndefined(null), null);
|
should.equal(removeUndefined(null), null);
|
||||||
|
|
||||||
|
@ -68,21 +68,21 @@ describe('util.removeUndefined', function () {
|
||||||
should.equal(removeUndefined('x'), 'x');
|
should.equal(removeUndefined('x'), 'x');
|
||||||
|
|
||||||
var date = new Date();
|
var date = new Date();
|
||||||
var q4 = {where: {x: 1, y: date}};
|
var q4 = { where: { x: 1, y: date }};
|
||||||
should.deepEqual(removeUndefined(q4), {where: {x: 1, y: date}});
|
should.deepEqual(removeUndefined(q4), { where: { x: 1, y: date }});
|
||||||
|
|
||||||
// test handling of undefined
|
// test handling of undefined
|
||||||
var q5 = {where: {x: 1, y: undefined}};
|
var q5 = { where: { x: 1, y: undefined }};
|
||||||
should.deepEqual(removeUndefined(q5, 'nullify'), {where: {x: 1, y: null}});
|
should.deepEqual(removeUndefined(q5, 'nullify'), { where: { x: 1, y: null }});
|
||||||
|
|
||||||
var q6 = {where: {x: 1, y: undefined}};
|
var q6 = { where: { x: 1, y: undefined }};
|
||||||
(function(){ removeUndefined(q6, 'throw') }).should.throw(/`undefined` in query/);
|
(function() { removeUndefined(q6, 'throw'); }).should.throw(/`undefined` in query/);
|
||||||
|
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
describe('util.parseSettings', function () {
|
describe('util.parseSettings', function() {
|
||||||
it('Parse a full url into a settings object', function () {
|
it('Parse a full url into a settings object', function() {
|
||||||
var url = 'mongodb://x:y@localhost:27017/mydb?w=2';
|
var url = 'mongodb://x:y@localhost:27017/mydb?w=2';
|
||||||
var settings = utils.parseSettings(url);
|
var settings = utils.parseSettings(url);
|
||||||
should.equal(settings.hostname, 'localhost');
|
should.equal(settings.hostname, 'localhost');
|
||||||
|
@ -97,7 +97,7 @@ describe('util.parseSettings', function () {
|
||||||
|
|
||||||
});
|
});
|
||||||
|
|
||||||
it('Parse a url without auth into a settings object', function () {
|
it('Parse a url without auth into a settings object', function() {
|
||||||
var url = 'mongodb://localhost:27017/mydb/abc?w=2';
|
var url = 'mongodb://localhost:27017/mydb/abc?w=2';
|
||||||
var settings = utils.parseSettings(url);
|
var settings = utils.parseSettings(url);
|
||||||
should.equal(settings.hostname, 'localhost');
|
should.equal(settings.hostname, 'localhost');
|
||||||
|
@ -112,7 +112,7 @@ describe('util.parseSettings', function () {
|
||||||
|
|
||||||
});
|
});
|
||||||
|
|
||||||
it('Parse a url with complex query into a settings object', function () {
|
it('Parse a url with complex query into a settings object', function() {
|
||||||
var url = 'mysql://127.0.0.1:3306/mydb?x[a]=1&x[b]=2&engine=InnoDB';
|
var url = 'mysql://127.0.0.1:3306/mydb?x[a]=1&x[b]=2&engine=InnoDB';
|
||||||
var settings = utils.parseSettings(url);
|
var settings = utils.parseSettings(url);
|
||||||
should.equal(settings.hostname, '127.0.0.1');
|
should.equal(settings.hostname, '127.0.0.1');
|
||||||
|
@ -129,7 +129,7 @@ describe('util.parseSettings', function () {
|
||||||
|
|
||||||
});
|
});
|
||||||
|
|
||||||
it('Parse a url without auth into a settings object', function () {
|
it('Parse a url without auth into a settings object', function() {
|
||||||
var url = 'memory://?x=1';
|
var url = 'memory://?x=1';
|
||||||
var settings = utils.parseSettings(url);
|
var settings = utils.parseSettings(url);
|
||||||
should.equal(settings.hostname, '');
|
should.equal(settings.hostname, '');
|
||||||
|
@ -144,12 +144,12 @@ describe('util.parseSettings', function () {
|
||||||
|
|
||||||
});
|
});
|
||||||
|
|
||||||
describe('mergeSettings', function () {
|
describe('mergeSettings', function() {
|
||||||
it('should merge settings correctly', function () {
|
it('should merge settings correctly', function() {
|
||||||
var src = { base: 'User',
|
var src = { base: 'User',
|
||||||
relations: { accessTokens: { model: 'accessToken', type: 'hasMany',
|
relations: { accessTokens: { model: 'accessToken', type: 'hasMany',
|
||||||
foreignKey: 'userId' },
|
foreignKey: 'userId' },
|
||||||
account: { model: 'account', type: 'belongsTo' } },
|
account: { model: 'account', type: 'belongsTo' }},
|
||||||
acls: [
|
acls: [
|
||||||
{ accessType: '*',
|
{ accessType: '*',
|
||||||
permission: 'DENY',
|
permission: 'DENY',
|
||||||
|
@ -163,7 +163,7 @@ describe('mergeSettings', function () {
|
||||||
{ permission: 'ALLOW',
|
{ permission: 'ALLOW',
|
||||||
property: 'findById',
|
property: 'findById',
|
||||||
principalType: 'ROLE',
|
principalType: 'ROLE',
|
||||||
principalId: '$owner' }
|
principalId: '$owner' },
|
||||||
] };
|
] };
|
||||||
var tgt = { strict: false,
|
var tgt = { strict: false,
|
||||||
acls: [
|
acls: [
|
||||||
|
@ -174,7 +174,7 @@ describe('mergeSettings', function () {
|
||||||
{ principalType: 'ROLE',
|
{ principalType: 'ROLE',
|
||||||
principalId: '$owner',
|
principalId: '$owner',
|
||||||
permission: 'ALLOW',
|
permission: 'ALLOW',
|
||||||
property: 'removeById' }
|
property: 'removeById' },
|
||||||
],
|
],
|
||||||
maxTTL: 31556926,
|
maxTTL: 31556926,
|
||||||
ttl: 1209600 };
|
ttl: 1209600 };
|
||||||
|
@ -203,20 +203,20 @@ describe('mergeSettings', function () {
|
||||||
{ permission: 'ALLOW',
|
{ permission: 'ALLOW',
|
||||||
property: 'findById',
|
property: 'findById',
|
||||||
principalType: 'ROLE',
|
principalType: 'ROLE',
|
||||||
principalId: '$owner' }
|
principalId: '$owner' },
|
||||||
],
|
],
|
||||||
maxTTL: 31556926,
|
maxTTL: 31556926,
|
||||||
ttl: 1209600,
|
ttl: 1209600,
|
||||||
base: 'User',
|
base: 'User',
|
||||||
relations: { accessTokens: { model: 'accessToken', type: 'hasMany',
|
relations: { accessTokens: { model: 'accessToken', type: 'hasMany',
|
||||||
foreignKey: 'userId' },
|
foreignKey: 'userId' },
|
||||||
account: { model: 'account', type: 'belongsTo' } } };
|
account: { model: 'account', type: 'belongsTo' }}};
|
||||||
|
|
||||||
should.deepEqual(dst.acls, expected.acls, 'Merged settings should match the expectation');
|
should.deepEqual(dst.acls, expected.acls, 'Merged settings should match the expectation');
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
describe('sortObjectsByIds', function () {
|
describe('sortObjectsByIds', function() {
|
||||||
|
|
||||||
var items = [
|
var items = [
|
||||||
{ id: 1, name: 'a' },
|
{ id: 1, name: 'a' },
|
||||||
|
@ -224,7 +224,7 @@ describe('sortObjectsByIds', function () {
|
||||||
{ id: 3, name: 'c' },
|
{ id: 3, name: 'c' },
|
||||||
{ id: 4, name: 'd' },
|
{ id: 4, name: 'd' },
|
||||||
{ id: 5, name: 'e' },
|
{ id: 5, name: 'e' },
|
||||||
{ id: 6, name: 'f' }
|
{ id: 6, name: 'f' },
|
||||||
];
|
];
|
||||||
|
|
||||||
it('should sort', function() {
|
it('should sort', function() {
|
||||||
|
@ -247,7 +247,7 @@ describe('sortObjectsByIds', function () {
|
||||||
|
|
||||||
});
|
});
|
||||||
|
|
||||||
describe('util.mergeIncludes', function () {
|
describe('util.mergeIncludes', function() {
|
||||||
|
|
||||||
function checkInputOutput(baseInclude, updateInclude, expectedInclude) {
|
function checkInputOutput(baseInclude, updateInclude, expectedInclude) {
|
||||||
var mergedInclude = mergeIncludes(baseInclude, updateInclude);
|
var mergedInclude = mergeIncludes(baseInclude, updateInclude);
|
||||||
|
@ -259,8 +259,8 @@ describe('util.mergeIncludes', function () {
|
||||||
var baseInclude = 'relation1';
|
var baseInclude = 'relation1';
|
||||||
var updateInclude = 'relation2';
|
var updateInclude = 'relation2';
|
||||||
var expectedInclude = [
|
var expectedInclude = [
|
||||||
{relation2: true},
|
{ relation2: true },
|
||||||
{relation1: true}
|
{ relation1: true },
|
||||||
];
|
];
|
||||||
checkInputOutput(baseInclude, updateInclude, expectedInclude);
|
checkInputOutput(baseInclude, updateInclude, expectedInclude);
|
||||||
});
|
});
|
||||||
|
@ -269,18 +269,18 @@ describe('util.mergeIncludes', function () {
|
||||||
var baseInclude = 'relation1';
|
var baseInclude = 'relation1';
|
||||||
var updateInclude = ['relation2'];
|
var updateInclude = ['relation2'];
|
||||||
var expectedInclude = [
|
var expectedInclude = [
|
||||||
{relation2: true},
|
{ relation2: true },
|
||||||
{relation1: true}
|
{ relation1: true },
|
||||||
];
|
];
|
||||||
checkInputOutput(baseInclude, updateInclude, expectedInclude);
|
checkInputOutput(baseInclude, updateInclude, expectedInclude);
|
||||||
});
|
});
|
||||||
|
|
||||||
it('Merge string & object values to object', function() {
|
it('Merge string & object values to object', function() {
|
||||||
var baseInclude = ['relation1'];
|
var baseInclude = ['relation1'];
|
||||||
var updateInclude = {relation2: 'relation2Include'};
|
var updateInclude = { relation2: 'relation2Include' };
|
||||||
var expectedInclude = [
|
var expectedInclude = [
|
||||||
{relation2: 'relation2Include'},
|
{ relation2: 'relation2Include' },
|
||||||
{relation1: true}
|
{ relation1: true },
|
||||||
];
|
];
|
||||||
checkInputOutput(baseInclude, updateInclude, expectedInclude);
|
checkInputOutput(baseInclude, updateInclude, expectedInclude);
|
||||||
});
|
});
|
||||||
|
@ -289,37 +289,37 @@ describe('util.mergeIncludes', function () {
|
||||||
var baseInclude = ['relation1'];
|
var baseInclude = ['relation1'];
|
||||||
var updateInclude = ['relation2'];
|
var updateInclude = ['relation2'];
|
||||||
var expectedInclude = [
|
var expectedInclude = [
|
||||||
{relation2: true},
|
{ relation2: true },
|
||||||
{relation1: true}
|
{ relation1: true },
|
||||||
];
|
];
|
||||||
checkInputOutput(baseInclude, updateInclude, expectedInclude);
|
checkInputOutput(baseInclude, updateInclude, expectedInclude);
|
||||||
});
|
});
|
||||||
|
|
||||||
it('Merge array & object values to object', function() {
|
it('Merge array & object values to object', function() {
|
||||||
var baseInclude = ['relation1'];
|
var baseInclude = ['relation1'];
|
||||||
var updateInclude = {relation2: 'relation2Include'};
|
var updateInclude = { relation2: 'relation2Include' };
|
||||||
var expectedInclude = [
|
var expectedInclude = [
|
||||||
{relation2: 'relation2Include'},
|
{ relation2: 'relation2Include' },
|
||||||
{relation1: true}
|
{ relation1: true },
|
||||||
];
|
];
|
||||||
checkInputOutput(baseInclude, updateInclude, expectedInclude);
|
checkInputOutput(baseInclude, updateInclude, expectedInclude);
|
||||||
});
|
});
|
||||||
|
|
||||||
it('Merge object & object values to object', function() {
|
it('Merge object & object values to object', function() {
|
||||||
var baseInclude = {relation1: 'relation1Include'};
|
var baseInclude = { relation1: 'relation1Include' };
|
||||||
var updateInclude = {relation2: 'relation2Include'};
|
var updateInclude = { relation2: 'relation2Include' };
|
||||||
var expectedInclude = [
|
var expectedInclude = [
|
||||||
{relation2: 'relation2Include'},
|
{ relation2: 'relation2Include' },
|
||||||
{relation1: 'relation1Include'}
|
{ relation1: 'relation1Include' },
|
||||||
];
|
];
|
||||||
checkInputOutput(baseInclude, updateInclude, expectedInclude);
|
checkInputOutput(baseInclude, updateInclude, expectedInclude);
|
||||||
});
|
});
|
||||||
|
|
||||||
it('Override property collision with update value', function() {
|
it('Override property collision with update value', function() {
|
||||||
var baseInclude = {relation1: 'baseValue'};
|
var baseInclude = { relation1: 'baseValue' };
|
||||||
var updateInclude = {relation1: 'updateValue'};
|
var updateInclude = { relation1: 'updateValue' };
|
||||||
var expectedInclude = [
|
var expectedInclude = [
|
||||||
{relation1: 'updateValue'}
|
{ relation1: 'updateValue' },
|
||||||
];
|
];
|
||||||
checkInputOutput(baseInclude, updateInclude, expectedInclude);
|
checkInputOutput(baseInclude, updateInclude, expectedInclude);
|
||||||
});
|
});
|
||||||
|
@ -327,9 +327,9 @@ describe('util.mergeIncludes', function () {
|
||||||
it('Merge string includes & include with relation syntax properly',
|
it('Merge string includes & include with relation syntax properly',
|
||||||
function() {
|
function() {
|
||||||
var baseInclude = 'relation1';
|
var baseInclude = 'relation1';
|
||||||
var updateInclude = {relation: 'relation1'};
|
var updateInclude = { relation: 'relation1' };
|
||||||
var expectedInclude = [
|
var expectedInclude = [
|
||||||
{relation: 'relation1'}
|
{ relation: 'relation1' },
|
||||||
];
|
];
|
||||||
checkInputOutput(baseInclude, updateInclude, expectedInclude);
|
checkInputOutput(baseInclude, updateInclude, expectedInclude);
|
||||||
});
|
});
|
||||||
|
@ -338,10 +338,10 @@ describe('util.mergeIncludes', function () {
|
||||||
var baseInclude = 'relation1';
|
var baseInclude = 'relation1';
|
||||||
var updateInclude = {
|
var updateInclude = {
|
||||||
relation: 'relation1',
|
relation: 'relation1',
|
||||||
scope: {include: 'relation2'}
|
scope: { include: 'relation2' },
|
||||||
};
|
};
|
||||||
var expectedInclude = [
|
var expectedInclude = [
|
||||||
{relation: 'relation1', scope: {include: 'relation2'}}
|
{ relation: 'relation1', scope: { include: 'relation2' }},
|
||||||
];
|
];
|
||||||
checkInputOutput(baseInclude, updateInclude, expectedInclude);
|
checkInputOutput(baseInclude, updateInclude, expectedInclude);
|
||||||
});
|
});
|
||||||
|
@ -352,39 +352,39 @@ describe('util.mergeIncludes', function () {
|
||||||
var baseInclude = ['relation2'];
|
var baseInclude = ['relation2'];
|
||||||
var updateInclude = {
|
var updateInclude = {
|
||||||
relation: 'relation1',
|
relation: 'relation1',
|
||||||
scope: {include: 'relation2'}
|
scope: { include: 'relation2' },
|
||||||
};
|
};
|
||||||
var expectedInclude = [{
|
var expectedInclude = [{
|
||||||
relation: 'relation1',
|
relation: 'relation1',
|
||||||
scope: {include: 'relation2'}
|
scope: { include: 'relation2' },
|
||||||
}, {relation2: true}];
|
}, { relation2: true }];
|
||||||
checkInputOutput(baseInclude, updateInclude, expectedInclude);
|
checkInputOutput(baseInclude, updateInclude, expectedInclude);
|
||||||
|
|
||||||
//w & w/o relation syntax - collision
|
//w & w/o relation syntax - collision
|
||||||
baseInclude = ['relation1'];
|
baseInclude = ['relation1'];
|
||||||
updateInclude = {relation: 'relation1', scope: {include: 'relation2'}};
|
updateInclude = { relation: 'relation1', scope: { include: 'relation2' }};
|
||||||
expectedInclude =
|
expectedInclude =
|
||||||
[{relation: 'relation1', scope: {include: 'relation2'}}];
|
[{ relation: 'relation1', scope: { include: 'relation2' }}];
|
||||||
checkInputOutput(baseInclude, updateInclude, expectedInclude);
|
checkInputOutput(baseInclude, updateInclude, expectedInclude);
|
||||||
|
|
||||||
//w & w/o relation syntax - collision
|
//w & w/o relation syntax - collision
|
||||||
baseInclude = {relation: 'relation1', scope: {include: 'relation2'}};
|
baseInclude = { relation: 'relation1', scope: { include: 'relation2' }};
|
||||||
updateInclude = ['relation1'];
|
updateInclude = ['relation1'];
|
||||||
expectedInclude = [{relation1: true}];
|
expectedInclude = [{ relation1: true }];
|
||||||
checkInputOutput(baseInclude, updateInclude, expectedInclude);
|
checkInputOutput(baseInclude, updateInclude, expectedInclude);
|
||||||
});
|
});
|
||||||
|
|
||||||
it('Merge includes with mixture of strings, arrays & objects properly', function() {
|
it('Merge includes with mixture of strings, arrays & objects properly', function() {
|
||||||
var baseInclude = ['relation1', {relation2: true},
|
var baseInclude = ['relation1', { relation2: true },
|
||||||
{relation: 'relation3', scope: {where: {id: 'some id'}}},
|
{ relation: 'relation3', scope: { where: { id: 'some id' }}},
|
||||||
{relation: 'relation5', scope: {where: {id: 'some id'}}}
|
{ relation: 'relation5', scope: { where: { id: 'some id' }}},
|
||||||
];
|
];
|
||||||
var updateInclude = ['relation4', {relation3: true},
|
var updateInclude = ['relation4', { relation3: true },
|
||||||
{relation: 'relation2', scope: {where: {id: 'some id'}}}];
|
{ relation: 'relation2', scope: { where: { id: 'some id' }}}];
|
||||||
var expectedInclude = [{relation4: true}, {relation3: true},
|
var expectedInclude = [{ relation4: true }, { relation3: true },
|
||||||
{relation: 'relation2', scope: {where: {id: 'some id'}}},
|
{ relation: 'relation2', scope: { where: { id: 'some id' }}},
|
||||||
{relation1: true},
|
{ relation1: true },
|
||||||
{relation: 'relation5', scope: {where: {id: 'some id'}}}];
|
{ relation: 'relation5', scope: { where: { id: 'some id' }}}];
|
||||||
checkInputOutput(baseInclude, updateInclude, expectedInclude);
|
checkInputOutput(baseInclude, updateInclude, expectedInclude);
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
@ -457,18 +457,18 @@ describe('util.toRegExp', function() {
|
||||||
context('with a regex string', function() {
|
context('with a regex string', function() {
|
||||||
it('should return a RegExp object when no regex flags are provided',
|
it('should return a RegExp object when no regex flags are provided',
|
||||||
function() {
|
function() {
|
||||||
utils.toRegExp('^regex$').should.be.an.instanceOf(RegExp);
|
utils.toRegExp('^regex$').should.be.an.instanceOf(RegExp);
|
||||||
});
|
});
|
||||||
|
|
||||||
it('should throw an error when invalid regex flags are provided',
|
it('should throw an error when invalid regex flags are provided',
|
||||||
function() {
|
function() {
|
||||||
utils.toRegExp('^regex$/abc').should.be.an.Error;
|
utils.toRegExp('^regex$/abc').should.be.an.Error;
|
||||||
});
|
});
|
||||||
|
|
||||||
it('should return a RegExp object when valid flags are provided',
|
it('should return a RegExp object when valid flags are provided',
|
||||||
function() {
|
function() {
|
||||||
utils.toRegExp('regex/igm').should.be.an.instanceOf(RegExp);
|
utils.toRegExp('regex/igm').should.be.an.instanceOf(RegExp);
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
context('with a regex literal', function() {
|
context('with a regex literal', function() {
|
||||||
|
|
|
@ -18,15 +18,15 @@ function getValidAttributes() {
|
||||||
age: 26,
|
age: 26,
|
||||||
gender: 'male',
|
gender: 'male',
|
||||||
createdByAdmin: false,
|
createdByAdmin: false,
|
||||||
createdByScript: true
|
createdByScript: true,
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
describe('validations', function () {
|
describe('validations', function() {
|
||||||
|
|
||||||
var User, Entry;
|
var User, Entry;
|
||||||
|
|
||||||
before(function (done) {
|
before(function(done) {
|
||||||
db = getSchema();
|
db = getSchema();
|
||||||
User = db.define('User', {
|
User = db.define('User', {
|
||||||
email: String,
|
email: String,
|
||||||
|
@ -39,33 +39,33 @@ describe('validations', function () {
|
||||||
pendingPeriod: Number,
|
pendingPeriod: Number,
|
||||||
createdByAdmin: Boolean,
|
createdByAdmin: Boolean,
|
||||||
createdByScript: Boolean,
|
createdByScript: Boolean,
|
||||||
updatedAt: Date
|
updatedAt: Date,
|
||||||
});
|
});
|
||||||
Entry = db.define('Entry', {
|
Entry = db.define('Entry', {
|
||||||
id: { type: 'string', id: true, generated: false },
|
id: { type: 'string', id: true, generated: false },
|
||||||
name: { type: 'string' }
|
name: { type: 'string' },
|
||||||
});
|
});
|
||||||
Entry.validatesUniquenessOf('id');
|
Entry.validatesUniquenessOf('id');
|
||||||
db.automigrate(done);
|
db.automigrate(done);
|
||||||
});
|
});
|
||||||
|
|
||||||
beforeEach(function (done) {
|
beforeEach(function(done) {
|
||||||
User.destroyAll(function () {
|
User.destroyAll(function() {
|
||||||
delete User.validations;
|
delete User.validations;
|
||||||
done();
|
done();
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
after(function () {
|
after(function() {
|
||||||
// db.disconnect();
|
// db.disconnect();
|
||||||
});
|
});
|
||||||
|
|
||||||
describe('commons', function () {
|
describe('commons', function() {
|
||||||
|
|
||||||
describe('skipping', function () {
|
describe('skipping', function() {
|
||||||
|
|
||||||
it('should NOT skip when `if` is fulfilled', function () {
|
it('should NOT skip when `if` is fulfilled', function() {
|
||||||
User.validatesPresenceOf('pendingPeriod', {if: 'createdByAdmin'});
|
User.validatesPresenceOf('pendingPeriod', { if: 'createdByAdmin' });
|
||||||
var user = new User;
|
var user = new User;
|
||||||
user.createdByAdmin = true;
|
user.createdByAdmin = true;
|
||||||
user.isValid().should.be.false;
|
user.isValid().should.be.false;
|
||||||
|
@ -74,8 +74,8 @@ describe('validations', function () {
|
||||||
user.isValid().should.be.true;
|
user.isValid().should.be.true;
|
||||||
});
|
});
|
||||||
|
|
||||||
it('should skip when `if` is NOT fulfilled', function () {
|
it('should skip when `if` is NOT fulfilled', function() {
|
||||||
User.validatesPresenceOf('pendingPeriod', {if: 'createdByAdmin'});
|
User.validatesPresenceOf('pendingPeriod', { if: 'createdByAdmin' });
|
||||||
var user = new User;
|
var user = new User;
|
||||||
user.createdByAdmin = false;
|
user.createdByAdmin = false;
|
||||||
user.isValid().should.be.true;
|
user.isValid().should.be.true;
|
||||||
|
@ -84,8 +84,8 @@ describe('validations', function () {
|
||||||
user.isValid().should.be.true;
|
user.isValid().should.be.true;
|
||||||
});
|
});
|
||||||
|
|
||||||
it('should NOT skip when `unless` is fulfilled', function () {
|
it('should NOT skip when `unless` is fulfilled', function() {
|
||||||
User.validatesPresenceOf('pendingPeriod', {unless: 'createdByAdmin'});
|
User.validatesPresenceOf('pendingPeriod', { unless: 'createdByAdmin' });
|
||||||
var user = new User;
|
var user = new User;
|
||||||
user.createdByAdmin = false;
|
user.createdByAdmin = false;
|
||||||
user.isValid().should.be.false;
|
user.isValid().should.be.false;
|
||||||
|
@ -94,8 +94,8 @@ describe('validations', function () {
|
||||||
user.isValid().should.be.true;
|
user.isValid().should.be.true;
|
||||||
});
|
});
|
||||||
|
|
||||||
it('should skip when `unless` is NOT fulfilled', function () {
|
it('should skip when `unless` is NOT fulfilled', function() {
|
||||||
User.validatesPresenceOf('pendingPeriod', {unless: 'createdByAdmin'});
|
User.validatesPresenceOf('pendingPeriod', { unless: 'createdByAdmin' });
|
||||||
var user = new User;
|
var user = new User;
|
||||||
user.createdByAdmin = true;
|
user.createdByAdmin = true;
|
||||||
user.isValid().should.be.true;
|
user.isValid().should.be.true;
|
||||||
|
@ -106,58 +106,58 @@ describe('validations', function () {
|
||||||
|
|
||||||
});
|
});
|
||||||
|
|
||||||
describe('skipping in async validation', function () {
|
describe('skipping in async validation', function() {
|
||||||
|
|
||||||
it('should skip when `if` is NOT fulfilled', function (done) {
|
it('should skip when `if` is NOT fulfilled', function(done) {
|
||||||
User.validateAsync('pendingPeriod', function (err, done) {
|
User.validateAsync('pendingPeriod', function(err, done) {
|
||||||
if (!this.pendingPeriod) err();
|
if (!this.pendingPeriod) err();
|
||||||
done();
|
done();
|
||||||
}, {if: 'createdByAdmin', code: 'presence', message: 'can\'t be blank'});
|
}, { if: 'createdByAdmin', code: 'presence', message: 'can\'t be blank' });
|
||||||
var user = new User;
|
var user = new User;
|
||||||
user.createdByAdmin = false;
|
user.createdByAdmin = false;
|
||||||
user.isValid(function (valid) {
|
user.isValid(function(valid) {
|
||||||
valid.should.be.true;
|
valid.should.be.true;
|
||||||
user.errors.should.be.false;
|
user.errors.should.be.false;
|
||||||
done();
|
done();
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
it('should NOT skip when `if` is fulfilled', function (done) {
|
it('should NOT skip when `if` is fulfilled', function(done) {
|
||||||
User.validateAsync('pendingPeriod', function (err, done) {
|
User.validateAsync('pendingPeriod', function(err, done) {
|
||||||
if (!this.pendingPeriod) err();
|
if (!this.pendingPeriod) err();
|
||||||
done();
|
done();
|
||||||
}, {if: 'createdByAdmin', code: 'presence', message: 'can\'t be blank'});
|
}, { if: 'createdByAdmin', code: 'presence', message: 'can\'t be blank' });
|
||||||
var user = new User;
|
var user = new User;
|
||||||
user.createdByAdmin = true;
|
user.createdByAdmin = true;
|
||||||
user.isValid(function (valid) {
|
user.isValid(function(valid) {
|
||||||
valid.should.be.false;
|
valid.should.be.false;
|
||||||
user.errors.pendingPeriod.should.eql(['can\'t be blank']);
|
user.errors.pendingPeriod.should.eql(['can\'t be blank']);
|
||||||
done();
|
done();
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
it('should skip when `unless` is NOT fulfilled', function (done) {
|
it('should skip when `unless` is NOT fulfilled', function(done) {
|
||||||
User.validateAsync('pendingPeriod', function (err, done) {
|
User.validateAsync('pendingPeriod', function(err, done) {
|
||||||
if (!this.pendingPeriod) err();
|
if (!this.pendingPeriod) err();
|
||||||
done();
|
done();
|
||||||
}, {unless: 'createdByAdmin', code: 'presence', message: 'can\'t be blank'});
|
}, { unless: 'createdByAdmin', code: 'presence', message: 'can\'t be blank' });
|
||||||
var user = new User;
|
var user = new User;
|
||||||
user.createdByAdmin = true;
|
user.createdByAdmin = true;
|
||||||
user.isValid(function (valid) {
|
user.isValid(function(valid) {
|
||||||
valid.should.be.true;
|
valid.should.be.true;
|
||||||
user.errors.should.be.false;
|
user.errors.should.be.false;
|
||||||
done();
|
done();
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
it('should NOT skip when `unless` is fulfilled', function (done) {
|
it('should NOT skip when `unless` is fulfilled', function(done) {
|
||||||
User.validateAsync('pendingPeriod', function (err, done) {
|
User.validateAsync('pendingPeriod', function(err, done) {
|
||||||
if (!this.pendingPeriod) err();
|
if (!this.pendingPeriod) err();
|
||||||
done();
|
done();
|
||||||
}, {unless: 'createdByAdmin', code: 'presence', message: 'can\'t be blank'});
|
}, { unless: 'createdByAdmin', code: 'presence', message: 'can\'t be blank' });
|
||||||
var user = new User;
|
var user = new User;
|
||||||
user.createdByAdmin = false;
|
user.createdByAdmin = false;
|
||||||
user.isValid(function (valid) {
|
user.isValid(function(valid) {
|
||||||
valid.should.be.false;
|
valid.should.be.false;
|
||||||
user.errors.pendingPeriod.should.eql(['can\'t be blank']);
|
user.errors.pendingPeriod.should.eql(['can\'t be blank']);
|
||||||
done();
|
done();
|
||||||
|
@ -166,33 +166,33 @@ describe('validations', function () {
|
||||||
|
|
||||||
});
|
});
|
||||||
|
|
||||||
describe('lifecycle', function () {
|
describe('lifecycle', function() {
|
||||||
|
|
||||||
it('should work on create', function (done) {
|
it('should work on create', function(done) {
|
||||||
delete User.validations;
|
delete User.validations;
|
||||||
User.validatesPresenceOf('name');
|
User.validatesPresenceOf('name');
|
||||||
User.create(function (e, u) {
|
User.create(function(e, u) {
|
||||||
should.exist(e);
|
should.exist(e);
|
||||||
User.create({name: 'Valid'}, function (e, d) {
|
User.create({ name: 'Valid' }, function(e, d) {
|
||||||
should.not.exist(e);
|
should.not.exist(e);
|
||||||
done();
|
done();
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
it('should work on update', function (done) {
|
it('should work on update', function(done) {
|
||||||
delete User.validations;
|
delete User.validations;
|
||||||
User.validatesPresenceOf('name');
|
User.validatesPresenceOf('name');
|
||||||
User.create({name: 'Valid'}, function (e, d) {
|
User.create({ name: 'Valid' }, function(e, d) {
|
||||||
d.updateAttribute('name', null, function (e) {
|
d.updateAttribute('name', null, function(e) {
|
||||||
should.exist(e);
|
should.exist(e);
|
||||||
e.should.be.instanceOf(Error);
|
e.should.be.instanceOf(Error);
|
||||||
e.should.be.instanceOf(ValidationError);
|
e.should.be.instanceOf(ValidationError);
|
||||||
d.updateAttribute('name', 'Vasiliy', function (e) {
|
d.updateAttribute('name', 'Vasiliy', function(e) {
|
||||||
should.not.exist(e);
|
should.not.exist(e);
|
||||||
done();
|
done();
|
||||||
});
|
});
|
||||||
})
|
});
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
|
@ -232,18 +232,18 @@ describe('validations', function () {
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
it('should return error code', function (done) {
|
it('should return error code', function(done) {
|
||||||
delete User.validations;
|
delete User.validations;
|
||||||
User.validatesPresenceOf('name');
|
User.validatesPresenceOf('name');
|
||||||
User.create(function (e, u) {
|
User.create(function(e, u) {
|
||||||
should.exist(e);
|
should.exist(e);
|
||||||
e.details.codes.name.should.eql(['presence']);
|
e.details.codes.name.should.eql(['presence']);
|
||||||
done();
|
done();
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
it('should allow to modify error after validation', function (done) {
|
it('should allow to modify error after validation', function(done) {
|
||||||
User.afterValidate = function (next) {
|
User.afterValidate = function(next) {
|
||||||
next();
|
next();
|
||||||
};
|
};
|
||||||
done();
|
done();
|
||||||
|
@ -252,7 +252,7 @@ describe('validations', function () {
|
||||||
it('should include validation messages in err.message', function(done) {
|
it('should include validation messages in err.message', function(done) {
|
||||||
delete User.validations;
|
delete User.validations;
|
||||||
User.validatesPresenceOf('name');
|
User.validatesPresenceOf('name');
|
||||||
User.create(function (e, u) {
|
User.create(function(e, u) {
|
||||||
should.exist(e);
|
should.exist(e);
|
||||||
e.message.should.match(/`name` can't be blank/);
|
e.message.should.match(/`name` can't be blank/);
|
||||||
done();
|
done();
|
||||||
|
@ -262,7 +262,7 @@ describe('validations', function () {
|
||||||
it('should include property value in err.message', function(done) {
|
it('should include property value in err.message', function(done) {
|
||||||
delete User.validations;
|
delete User.validations;
|
||||||
User.validatesPresenceOf('name');
|
User.validatesPresenceOf('name');
|
||||||
User.create(function (e, u) {
|
User.create(function(e, u) {
|
||||||
should.exist(e);
|
should.exist(e);
|
||||||
e.message.should.match(/`name` can't be blank \(value: undefined\)/);
|
e.message.should.match(/`name` can't be blank \(value: undefined\)/);
|
||||||
done();
|
done();
|
||||||
|
@ -272,7 +272,7 @@ describe('validations', function () {
|
||||||
it('should include model name in err.message', function(done) {
|
it('should include model name in err.message', function(done) {
|
||||||
delete User.validations;
|
delete User.validations;
|
||||||
User.validatesPresenceOf('name');
|
User.validatesPresenceOf('name');
|
||||||
User.create(function (e, u) {
|
User.create(function(e, u) {
|
||||||
should.exist(e);
|
should.exist(e);
|
||||||
e.message.should.match(/`User` instance/i);
|
e.message.should.match(/`User` instance/i);
|
||||||
done();
|
done();
|
||||||
|
@ -280,7 +280,7 @@ describe('validations', function () {
|
||||||
});
|
});
|
||||||
|
|
||||||
it('should return validation metadata', function() {
|
it('should return validation metadata', function() {
|
||||||
var expected = {name:[{validation: 'presence', options: {}}]};
|
var expected = { name:[{ validation: 'presence', options: {}}] };
|
||||||
delete User.validations;
|
delete User.validations;
|
||||||
User.validatesPresenceOf('name');
|
User.validatesPresenceOf('name');
|
||||||
var validations = User.validations;
|
var validations = User.validations;
|
||||||
|
@ -289,14 +289,14 @@ describe('validations', function () {
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
describe('presence', function () {
|
describe('presence', function() {
|
||||||
|
|
||||||
it('should validate presence', function () {
|
it('should validate presence', function() {
|
||||||
User.validatesPresenceOf('name', 'email');
|
User.validatesPresenceOf('name', 'email');
|
||||||
|
|
||||||
var validations = User.validations;
|
var validations = User.validations;
|
||||||
validations.name.should.eql([{validation: 'presence', options: {}}]);
|
validations.name.should.eql([{ validation: 'presence', options: {}}]);
|
||||||
validations.email.should.eql([{validation: 'presence', options: {}}]);
|
validations.email.should.eql([{ validation: 'presence', options: {}}]);
|
||||||
|
|
||||||
var u = new User;
|
var u = new User;
|
||||||
u.isValid().should.not.be.true;
|
u.isValid().should.not.be.true;
|
||||||
|
@ -324,10 +324,10 @@ describe('validations', function () {
|
||||||
u.isValid().should.be.true;
|
u.isValid().should.be.true;
|
||||||
});
|
});
|
||||||
|
|
||||||
it('should skip validation by property (if/unless)', function () {
|
it('should skip validation by property (if/unless)', function() {
|
||||||
User.validatesPresenceOf('domain', {unless: 'createdByScript'});
|
User.validatesPresenceOf('domain', { unless: 'createdByScript' });
|
||||||
|
|
||||||
var user = new User(getValidAttributes())
|
var user = new User(getValidAttributes());
|
||||||
user.isValid().should.be.true;
|
user.isValid().should.be.true;
|
||||||
|
|
||||||
user.createdByScript = false;
|
user.createdByScript = false;
|
||||||
|
@ -340,29 +340,29 @@ describe('validations', function () {
|
||||||
|
|
||||||
});
|
});
|
||||||
|
|
||||||
describe('absence', function () {
|
describe('absence', function() {
|
||||||
|
|
||||||
it('should validate absence', function () {
|
it('should validate absence', function() {
|
||||||
User.validatesAbsenceOf('reserved', { if: 'locked' });
|
User.validatesAbsenceOf('reserved', { if: 'locked' });
|
||||||
var u = new User({reserved: 'foo', locked: true});
|
var u = new User({ reserved: 'foo', locked: true });
|
||||||
u.isValid().should.not.be.true;
|
u.isValid().should.not.be.true;
|
||||||
u.reserved = null;
|
u.reserved = null;
|
||||||
u.isValid().should.be.true;
|
u.isValid().should.be.true;
|
||||||
var u = new User({reserved: 'foo', locked: false});
|
var u = new User({ reserved: 'foo', locked: false });
|
||||||
u.isValid().should.be.true;
|
u.isValid().should.be.true;
|
||||||
});
|
});
|
||||||
|
|
||||||
});
|
});
|
||||||
|
|
||||||
describe('uniqueness', function () {
|
describe('uniqueness', function() {
|
||||||
it('should validate uniqueness', function (done) {
|
it('should validate uniqueness', function(done) {
|
||||||
User.validatesUniquenessOf('email');
|
User.validatesUniquenessOf('email');
|
||||||
var u = new User({email: 'hey'});
|
var u = new User({ email: 'hey' });
|
||||||
Boolean(u.isValid(function (valid) {
|
Boolean(u.isValid(function(valid) {
|
||||||
valid.should.be.true;
|
valid.should.be.true;
|
||||||
u.save(function () {
|
u.save(function() {
|
||||||
var u2 = new User({email: 'hey'});
|
var u2 = new User({ email: 'hey' });
|
||||||
u2.isValid(function (valid) {
|
u2.isValid(function(valid) {
|
||||||
valid.should.be.false;
|
valid.should.be.false;
|
||||||
done();
|
done();
|
||||||
});
|
});
|
||||||
|
@ -370,14 +370,14 @@ describe('validations', function () {
|
||||||
})).should.be.false;
|
})).should.be.false;
|
||||||
});
|
});
|
||||||
|
|
||||||
it('should handle same object modification', function (done) {
|
it('should handle same object modification', function(done) {
|
||||||
User.validatesUniquenessOf('email');
|
User.validatesUniquenessOf('email');
|
||||||
var u = new User({email: 'hey'});
|
var u = new User({ email: 'hey' });
|
||||||
Boolean(u.isValid(function (valid) {
|
Boolean(u.isValid(function(valid) {
|
||||||
valid.should.be.true;
|
valid.should.be.true;
|
||||||
u.save(function () {
|
u.save(function() {
|
||||||
u.name = 'Goghi';
|
u.name = 'Goghi';
|
||||||
u.isValid(function (valid) {
|
u.isValid(function(valid) {
|
||||||
valid.should.be.true;
|
valid.should.be.true;
|
||||||
u.save(done);
|
u.save(done);
|
||||||
});
|
});
|
||||||
|
@ -390,7 +390,7 @@ describe('validations', function () {
|
||||||
var EMAIL = 'user@xample.com';
|
var EMAIL = 'user@xample.com';
|
||||||
var SiteUser = db.define('SiteUser', {
|
var SiteUser = db.define('SiteUser', {
|
||||||
siteId: String,
|
siteId: String,
|
||||||
email: String
|
email: String,
|
||||||
});
|
});
|
||||||
SiteUser.validatesUniquenessOf('email', { scopedTo: ['siteId'] });
|
SiteUser.validatesUniquenessOf('email', { scopedTo: ['siteId'] });
|
||||||
async.waterfall([
|
async.waterfall([
|
||||||
|
@ -413,7 +413,7 @@ describe('validations', function () {
|
||||||
valid.should.be.false;
|
valid.should.be.false;
|
||||||
next();
|
next();
|
||||||
});
|
});
|
||||||
}
|
},
|
||||||
], function(err) {
|
], function(err) {
|
||||||
if (err && err.name == 'ValidationError') {
|
if (err && err.name == 'ValidationError') {
|
||||||
console.error('ValidationError:', err.details.messages);
|
console.error('ValidationError:', err.details.messages);
|
||||||
|
@ -422,14 +422,14 @@ describe('validations', function () {
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
it('should skip blank values', function (done) {
|
it('should skip blank values', function(done) {
|
||||||
User.validatesUniquenessOf('email');
|
User.validatesUniquenessOf('email');
|
||||||
var u = new User({email: ' '});
|
var u = new User({ email: ' ' });
|
||||||
Boolean(u.isValid(function (valid) {
|
Boolean(u.isValid(function(valid) {
|
||||||
valid.should.be.true;
|
valid.should.be.true;
|
||||||
u.save(function () {
|
u.save(function() {
|
||||||
var u2 = new User({email: null});
|
var u2 = new User({ email: null });
|
||||||
u2.isValid(function (valid) {
|
u2.isValid(function(valid) {
|
||||||
valid.should.be.true;
|
valid.should.be.true;
|
||||||
done();
|
done();
|
||||||
});
|
});
|
||||||
|
@ -437,31 +437,31 @@ describe('validations', function () {
|
||||||
})).should.be.false;
|
})).should.be.false;
|
||||||
});
|
});
|
||||||
|
|
||||||
it('should work with if/unless', function (done) {
|
it('should work with if/unless', function(done) {
|
||||||
User.validatesUniquenessOf('email', {
|
User.validatesUniquenessOf('email', {
|
||||||
if: function() { return true; },
|
if: function() { return true; },
|
||||||
unless: function() { return false; }
|
unless: function() { return false; },
|
||||||
});
|
});
|
||||||
var u = new User({email: 'hello'});
|
var u = new User({ email: 'hello' });
|
||||||
Boolean(u.isValid(function (valid) {
|
Boolean(u.isValid(function(valid) {
|
||||||
valid.should.be.true;
|
valid.should.be.true;
|
||||||
done();
|
done();
|
||||||
})).should.be.false;
|
})).should.be.false;
|
||||||
});
|
});
|
||||||
|
|
||||||
it('should work with id property on create', function (done) {
|
it('should work with id property on create', function(done) {
|
||||||
Entry.create({ id: 'entry' }, function(err, entry) {
|
Entry.create({ id: 'entry' }, function(err, entry) {
|
||||||
var e = new Entry({ id: 'entry' });
|
var e = new Entry({ id: 'entry' });
|
||||||
Boolean(e.isValid(function (valid) {
|
Boolean(e.isValid(function(valid) {
|
||||||
valid.should.be.false;
|
valid.should.be.false;
|
||||||
done();
|
done();
|
||||||
})).should.be.false;
|
})).should.be.false;
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
it('should work with id property after create', function (done) {
|
it('should work with id property after create', function(done) {
|
||||||
Entry.findById('entry', function(err, e) {
|
Entry.findById('entry', function(err, e) {
|
||||||
Boolean(e.isValid(function (valid) {
|
Boolean(e.isValid(function(valid) {
|
||||||
valid.should.be.true;
|
valid.should.be.true;
|
||||||
done();
|
done();
|
||||||
})).should.be.false;
|
})).should.be.false;
|
||||||
|
@ -469,83 +469,83 @@ describe('validations', function () {
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
describe('format', function () {
|
describe('format', function() {
|
||||||
it('should validate format');
|
it('should validate format');
|
||||||
it('should overwrite default blank message with custom format message');
|
it('should overwrite default blank message with custom format message');
|
||||||
|
|
||||||
it('should skip missing values when allowing null', function () {
|
it('should skip missing values when allowing null', function() {
|
||||||
User.validatesFormatOf('email', { with: /^\S+@\S+\.\S+$/, allowNull: true });
|
User.validatesFormatOf('email', { with: /^\S+@\S+\.\S+$/, allowNull: true });
|
||||||
var u = new User({});
|
var u = new User({});
|
||||||
u.isValid().should.be.true;
|
u.isValid().should.be.true;
|
||||||
});
|
});
|
||||||
|
|
||||||
it('should skip null values when allowing null', function () {
|
it('should skip null values when allowing null', function() {
|
||||||
User.validatesFormatOf('email', { with: /^\S+@\S+\.\S+$/, allowNull: true });
|
User.validatesFormatOf('email', { with: /^\S+@\S+\.\S+$/, allowNull: true });
|
||||||
var u = new User({ email: null });
|
var u = new User({ email: null });
|
||||||
u.isValid().should.be.true;
|
u.isValid().should.be.true;
|
||||||
});
|
});
|
||||||
|
|
||||||
it('should not skip missing values', function () {
|
it('should not skip missing values', function() {
|
||||||
User.validatesFormatOf('email', { with: /^\S+@\S+\.\S+$/ });
|
User.validatesFormatOf('email', { with: /^\S+@\S+\.\S+$/ });
|
||||||
var u = new User({});
|
var u = new User({});
|
||||||
u.isValid().should.be.false;
|
u.isValid().should.be.false;
|
||||||
});
|
});
|
||||||
|
|
||||||
it('should not skip null values', function () {
|
it('should not skip null values', function() {
|
||||||
User.validatesFormatOf('email', { with: /^\S+@\S+\.\S+$/ });
|
User.validatesFormatOf('email', { with: /^\S+@\S+\.\S+$/ });
|
||||||
var u = new User({ email: null });
|
var u = new User({ email: null });
|
||||||
u.isValid().should.be.false;
|
u.isValid().should.be.false;
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
describe('numericality', function () {
|
describe('numericality', function() {
|
||||||
it('should validate numericality');
|
it('should validate numericality');
|
||||||
});
|
});
|
||||||
|
|
||||||
describe('inclusion', function () {
|
describe('inclusion', function() {
|
||||||
it('should validate inclusion');
|
it('should validate inclusion');
|
||||||
});
|
});
|
||||||
|
|
||||||
describe('exclusion', function () {
|
describe('exclusion', function() {
|
||||||
it('should validate exclusion');
|
it('should validate exclusion');
|
||||||
});
|
});
|
||||||
|
|
||||||
describe('length', function () {
|
describe('length', function() {
|
||||||
it('should validate length');
|
it('should validate length');
|
||||||
});
|
});
|
||||||
|
|
||||||
describe('custom', function () {
|
describe('custom', function() {
|
||||||
it('should validate using custom sync validation', function() {
|
it('should validate using custom sync validation', function() {
|
||||||
User.validate('email', function (err) {
|
User.validate('email', function(err) {
|
||||||
if (this.email === 'hello') err();
|
if (this.email === 'hello') err();
|
||||||
}, { code: 'invalid-email' });
|
}, { code: 'invalid-email' });
|
||||||
var u = new User({email: 'hello'});
|
var u = new User({ email: 'hello' });
|
||||||
Boolean(u.isValid()).should.be.false;
|
Boolean(u.isValid()).should.be.false;
|
||||||
u.errors.codes.should.eql({ email: ['invalid-email'] });
|
u.errors.codes.should.eql({ email: ['invalid-email'] });
|
||||||
});
|
});
|
||||||
|
|
||||||
it('should validate and return detailed error messages', function() {
|
it('should validate and return detailed error messages', function() {
|
||||||
User.validate('global', function (err) {
|
User.validate('global', function(err) {
|
||||||
if (this.email === 'hello' || this.email === 'hey') {
|
if (this.email === 'hello' || this.email === 'hey') {
|
||||||
this.errors.add('email', 'Cannot be `' + this.email + '`', 'invalid-email');
|
this.errors.add('email', 'Cannot be `' + this.email + '`', 'invalid-email');
|
||||||
err(false); // false: prevent global error message
|
err(false); // false: prevent global error message
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
var u = new User({email: 'hello'});
|
var u = new User({ email: 'hello' });
|
||||||
Boolean(u.isValid()).should.be.false;
|
Boolean(u.isValid()).should.be.false;
|
||||||
u.errors.should.eql({ email: ['Cannot be `hello`'] });
|
u.errors.should.eql({ email: ['Cannot be `hello`'] });
|
||||||
u.errors.codes.should.eql({ email: ['invalid-email'] });
|
u.errors.codes.should.eql({ email: ['invalid-email'] });
|
||||||
});
|
});
|
||||||
|
|
||||||
it('should validate using custom async validation', function(done) {
|
it('should validate using custom async validation', function(done) {
|
||||||
User.validateAsync('email', function (err, next) {
|
User.validateAsync('email', function(err, next) {
|
||||||
process.nextTick(next);
|
process.nextTick(next);
|
||||||
}, {
|
}, {
|
||||||
if: function() { return true; },
|
if: function() { return true; },
|
||||||
unless: function() { return false; }
|
unless: function() { return false; },
|
||||||
});
|
});
|
||||||
var u = new User({email: 'hello'});
|
var u = new User({ email: 'hello' });
|
||||||
Boolean(u.isValid(function (valid) {
|
Boolean(u.isValid(function(valid) {
|
||||||
valid.should.be.true;
|
valid.should.be.true;
|
||||||
done();
|
done();
|
||||||
})).should.be.false;
|
})).should.be.false;
|
||||||
|
@ -578,7 +578,7 @@ describe('validations', function () {
|
||||||
|
|
||||||
it('should truncate long arrays', function() {
|
it('should truncate long arrays', function() {
|
||||||
ValidationError.maxPropertyStringLength = 12;
|
ValidationError.maxPropertyStringLength = 12;
|
||||||
var err = givenValidationError('prop', [{ a: 1, b: 2}], 'is invalid');
|
var err = givenValidationError('prop', [{ a: 1, b: 2 }], 'is invalid');
|
||||||
getErrorDetails(err)
|
getErrorDetails(err)
|
||||||
.should.equal('`prop` is invalid (value: [ { a...} ]).');
|
.should.equal('`prop` is invalid (value: [ { a...} ]).');
|
||||||
});
|
});
|
||||||
|
@ -611,7 +611,7 @@ describe('validations', function () {
|
||||||
|
|
||||||
var obj = {
|
var obj = {
|
||||||
errors: errorVal,
|
errors: errorVal,
|
||||||
toJSON: function() { return jsonVal; }
|
toJSON: function() { return jsonVal; },
|
||||||
};
|
};
|
||||||
return new ValidationError(obj);
|
return new ValidationError(obj);
|
||||||
}
|
}
|
||||||
|
|
Loading…
Reference in New Issue