Merge pull request #905 from strongloop/eslint-autofix-2x

Eslint autofix for 2.x
This commit is contained in:
Miroslav Bajtoš 2016-04-18 16:41:28 +02:00
commit feca7481e9
64 changed files with 4957 additions and 4960 deletions

View File

@ -10,36 +10,36 @@ var introspectType = require('../lib/introspection')(ModelBuilder);
var ds = new DataSource('memory');
// 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 = {
owner: 'rfeng',
name: 'MyApp1',
description: 'My first app',
pushSettings: [
{ "platform": "apns",
"apns": {
"pushOptions": {
"gateway": "gateway.sandbox.push.apple.com",
"cert": "credentials/apns_cert_dev.pem",
"key": "credentials/apns_key_dev.pem"
{ 'platform': 'apns',
'apns': {
'pushOptions': {
'gateway': 'gateway.sandbox.push.apple.com',
'cert': 'credentials/apns_cert_dev.pem',
'key': 'credentials/apns_key_dev.pem',
},
"feedbackOptions": {
"gateway": "feedback.sandbox.push.apple.com",
"cert": "credentials/apns_cert_dev.pem",
"key": "credentials/apns_key_dev.pem",
"batchFeedback": true,
"interval": 300
}
}}
]}
'feedbackOptions': {
'gateway': 'feedback.sandbox.push.apple.com',
'cert': 'credentials/apns_cert_dev.pem',
'key': 'credentials/apns_key_dev.pem',
'batchFeedback': true,
'interval': 300,
},
}},
] };
console.log(new Application(application).toObject());
Application.create(application, function (err, app1) {
Application.create(application, function(err, app1) {
console.log('Created: ', app1.toObject());
Application.findById(app1.id, function (err, app2) {
Application.findById(app1.id, function(err, app2) {
console.log('Found: ', app2.toObject());
});
});
@ -55,30 +55,30 @@ var user = {
city: 'San Jose',
state: 'CA',
zipcode: '95131',
country: 'US'
country: 'US',
},
friends: ['John', 'Mary'],
emails: [
{label: 'work', id: 'x@sample.com'},
{label: 'home', id: 'x@home.com'}
{ label: 'work', id: 'x@sample.com' },
{ label: 'home', id: 'x@home.com' },
],
tags: []
tags: [],
};
// Introspect the JSON document to generate a schema
var schema = introspectType(user);
// 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
var obj = new User(user);
console.log(obj.toObject());
User.create(user, function (err, u1) {
User.create(user, function(err, u1) {
console.log('Created: ', u1.toObject());
User.findById(u1.id, function (err, u2) {
User.findById(u1.id, function(err, u2) {
console.log('Found: ', u2.toObject());
});
});

View File

@ -9,11 +9,11 @@ var modelBuilder = new ModelBuilder();
var Post = modelBuilder.define('Post', {
title: { type: String, length: 255 },
content: { type: ModelBuilder.Text },
date: { type: Date, default: function () {
date: { type: Date, default: function() {
return new Date();
} },
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
@ -22,24 +22,24 @@ var User = modelBuilder.define('User', {
bio: ModelBuilder.Text,
approved: Boolean,
joinedAt: Date,
age: Number
age: Number,
});
var Group = modelBuilder.define('Group', {group: String});
var Group = modelBuilder.define('Group', { group: String });
// define any custom method
User.prototype.getNameAndAge = function () {
User.prototype.getNameAndAge = function() {
return this.name + ', ' + this.age;
};
var user = new User({name: 'Joe'});
var user = new User({ name: 'Joe' });
console.log(user);
console.log(modelBuilder.models);
console.log(modelBuilder.definitions);
User.mixin(Group);
var user = new User({name: 'Ray', group: 'Admin'});
var user = new User({ name: 'Ray', group: 'Admin' });
console.log(user);

View File

@ -11,11 +11,11 @@ var ds = new DataSource('memory');
var Post = ds.define('Post', {
title: { type: String, length: 255 },
content: { type: DataSource.Text },
date: { type: Date, default: function () {
date: { type: Date, default: function() {
return new Date;
} },
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
@ -24,31 +24,31 @@ var User = ds.define('User', {
bio: DataSource.Text,
approved: Boolean,
joinedAt: Date,
age: Number
age: Number,
});
var Group = ds.define('Group', {name: String});
var Group = ds.define('Group', { name: String });
// define any custom method
User.prototype.getNameAndAge = function () {
User.prototype.getNameAndAge = function() {
return this.name + ', ' + this.age;
};
var user = new User({name: 'Joe'});
var user = new User({ name: 'Joe' });
console.log(user);
// console.log(ds.models);
// console.log(ds.definitions);
// setup relationships
User.hasMany(Post, {as: 'posts', foreignKey: 'userId'});
User.hasMany(Post, { as: 'posts', foreignKey: 'userId' });
// creates instance methods:
// user.posts(conds)
// user.posts.build(data) // like new Post({userId: user.id});
// user.posts.create(data) // build and save
Post.belongsTo(User, {as: 'author', foreignKey: 'userId'});
Post.belongsTo(User, { as: 'author', foreignKey: 'userId' });
// creates instance methods:
// post.author(callback) -- getter when called with function
// post.author() -- sync getter when called without params
@ -56,46 +56,46 @@ Post.belongsTo(User, {as: 'author', foreignKey: 'userId'});
User.hasAndBelongsToMany('groups');
var user2 = new User({name: 'Smith', age: 14});
user2.save(function (err) {
var user2 = new User({ name: 'Smith', age: 14 });
user2.save(function(err) {
console.log(user2);
var post = user2.posts.build({title: 'Hello world'});
post.save(function (err, data) {
var post = user2.posts.build({ title: 'Hello world' });
post.save(function(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);
});
User.create({name: 'Jeff', age: 12}, function (err, data) {
User.create({ name: 'Jeff', age: 12 }, function(err, data) {
if (err) {
console.log(err);
return;
}
console.log(data);
var post = data.posts.build({title: 'My Post'});
var post = data.posts.build({ title: 'My Post' });
console.log(post);
});
User.create({name: 'Ray'}, function (err, data) {
User.create({ name: 'Ray' }, function(err, data) {
console.log(data);
});
User.scope('minors', {where: {age: {lte: 16}}, include: 'posts'});
User.minors(function (err, kids) {
User.scope('minors', { where: { age: { lte: 16 }}, include: 'posts' });
User.minors(function(err, kids) {
console.log('Kids: ', kids);
});
var Article = ds.define('Article', {title: String});
var Tag = ds.define('Tag', {name: String});
var Article = ds.define('Article', { title: String });
var Tag = ds.define('Tag', { name: String });
Article.hasAndBelongsToMany('tags');
Article.create(function (e, article) {
article.tags.create({name: 'popular'}, function (err, data) {
Article.findOne(function (e, article) {
article.tags(function (e, tags) {
Article.create(function(e, article) {
article.tags.create({ name: 'popular' }, function(err, data) {
Article.findOne(function(e, article) {
article.tags(function(e, tags) {
console.log(tags);
});
});
@ -106,17 +106,17 @@ Article.create(function (e, article) {
var modelBuilder = new ModelBuilder();
Color = modelBuilder.define('Color', {
name: String
name: String,
});
// attach
ds.attach(Color);
Color.create({name: 'red'});
Color.create({name: 'green'});
Color.create({name: 'blue'});
Color.create({ name: 'red' });
Color.create({ name: 'green' });
Color.create({ name: 'blue' });
Color.all(function (err, colors) {
Color.all(function(err, colors) {
console.log(colors);
});

View File

@ -8,54 +8,54 @@ var jdb = require('../index');
var User, Post, Passport, City, Street, Building;
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);
});
User.find({include: 'posts'}, function (err, users) {
User.find({ include: 'posts' }, function(err, 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);
});
Passport.find({
include: {owner: {posts: 'author'}}
}, function (err, passports) {
include: { owner: { posts: 'author' }},
}, function(err, 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);
});
});
function setup(done) {
var db = new jdb.DataSource({connector: 'memory'});
var db = new jdb.DataSource({ connector: 'memory' });
City = db.define('City');
Street = db.define('Street');
Building = db.define('Building');
User = db.define('User', {
name: String,
age: Number
age: Number,
});
Passport = db.define('Passport', {
number: String
number: String,
});
Post = db.define('Post', {
title: String
title: String,
});
Passport.belongsTo('owner', {model: User});
User.hasMany('passports', {foreignKey: 'ownerId'});
User.hasMany('posts', {foreignKey: 'userId'});
Post.belongsTo('author', {model: User, foreignKey: 'userId'});
Passport.belongsTo('owner', { model: User });
User.hasMany('passports', { foreignKey: 'ownerId' });
User.hasMany('posts', { foreignKey: 'userId' });
Post.belongsTo('author', { model: User, foreignKey: 'userId' });
db.automigrate(function () {
db.automigrate(function() {
var createdUsers = [];
var createdPassports = [];
var createdPosts = [];
@ -64,13 +64,13 @@ function setup(done) {
clearAndCreate(
User,
[
{name: 'User A', age: 21},
{name: 'User B', age: 22},
{name: 'User C', age: 23},
{name: 'User D', age: 24},
{name: 'User E', age: 25}
{ name: 'User A', age: 21 },
{ name: 'User B', age: 22 },
{ name: 'User C', age: 23 },
{ name: 'User D', age: 24 },
{ name: 'User E', age: 25 },
],
function (items) {
function(items) {
createdUsers = items;
createPassports();
}
@ -81,11 +81,11 @@ function setup(done) {
clearAndCreate(
Passport,
[
{number: '1', ownerId: createdUsers[0].id},
{number: '2', ownerId: createdUsers[1].id},
{number: '3'}
{ number: '1', ownerId: createdUsers[0].id },
{ number: '2', ownerId: createdUsers[1].id },
{ number: '3' },
],
function (items) {
function(items) {
createdPassports = items;
createPosts();
}
@ -96,13 +96,13 @@ function setup(done) {
clearAndCreate(
Post,
[
{title: 'Post A', userId: createdUsers[0].id},
{title: 'Post B', userId: createdUsers[0].id},
{title: 'Post C', userId: createdUsers[0].id},
{title: 'Post D', userId: createdUsers[1].id},
{title: 'Post E'}
{ title: 'Post A', userId: createdUsers[0].id },
{ title: 'Post B', userId: createdUsers[0].id },
{ title: 'Post C', userId: createdUsers[0].id },
{ title: 'Post D', userId: createdUsers[1].id },
{ title: 'Post E' },
],
function (items) {
function(items) {
createdPosts = items;
done();
}
@ -114,7 +114,7 @@ function setup(done) {
function clearAndCreate(model, data, callback) {
var createdItems = [];
model.destroyAll(function () {
model.destroyAll(function() {
nextItem(null, null);
});

View File

@ -18,21 +18,21 @@ var User = modelBuilder.define('User', {
city: String,
state: String,
zipCode: String,
country: String
country: String,
},
emails: [
{
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: [
{label: 'work', email: 'xyz@sample.com'}
{ label: 'work', email: 'xyz@sample.com' },
],
friends: ['John', 'Mary']});
friends: ['John', 'Mary'] });
console.log(user);
console.log(user.toObject());

View File

@ -9,55 +9,55 @@ var ds = new DataSource('memory');
var Order = ds.createModel('Order', {
items: [String],
orderDate: Date,
qty: Number
qty: Number,
});
var Customer = ds.createModel('Customer', {
name: String
name: String,
});
Order.belongsTo(Customer);
var order1, order2, order3;
Customer.create({name: 'John'}, function (err, customer) {
Order.create({customerId: customer.id, orderDate: new Date(), items: ['Book']}, function (err, order) {
Customer.create({ name: 'John' }, function(err, customer) {
Order.create({ customerId: customer.id, orderDate: new Date(), items: ['Book'] }, function(err, order) {
order1 = order;
order.customer(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(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);
order.save(function(err, order) {
order2 = order;
});
});
var customer3 = order.customer.build({name: 'Tom'});
var customer3 = order.customer.build({ name: 'Tom' });
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) {
Order.create({customerId: customer.id, qty: 3, orderDate: new Date()}, function (err, order) {
Customer.create({ name: 'Ray' }, function(err, customer) {
Order.create({ customerId: customer.id, qty: 3, orderDate: new Date() }, function(err, order) {
order3 = order;
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);
Customer.include([customer], 'orders', function (err, results) {
Customer.include([customer], 'orders', function(err, 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);
});
customer.orders.findById(order3.id, console.log);
@ -67,43 +67,43 @@ Customer.create({name: 'Ray'}, function (err, customer) {
});
var Physician = ds.createModel('Physician', {
name: String
name: String,
});
var Patient = ds.createModel('Patient', {
name: String
name: String,
});
var Appointment = ds.createModel('Appointment', {
physicianId: Number,
patientId: Number,
appointmentDate: Date
appointmentDate: Date,
});
Appointment.belongsTo(Patient);
Appointment.belongsTo(Physician);
Physician.hasMany(Patient, {through: Appointment});
Patient.hasMany(Physician, {through: Appointment});
Physician.hasMany(Patient, { through: Appointment });
Patient.hasMany(Physician, { through: Appointment });
Physician.create({name: 'Dr John'}, function (err, physician1) {
Physician.create({name: 'Dr Smith'}, function (err, physician2) {
Patient.create({name: 'Mary'}, function (err, patient1) {
Patient.create({name: 'Ben'}, function (err, patient2) {
Appointment.create({appointmentDate: new Date(), physicianId: physician1.id, patientId: patient1.id},
function (err, appt1) {
Appointment.create({appointmentDate: new Date(), physicianId: physician1.id, patientId: patient2.id},
function (err, appt2) {
Physician.create({ name: 'Dr John' }, function(err, physician1) {
Physician.create({ name: 'Dr Smith' }, function(err, physician2) {
Patient.create({ name: 'Mary' }, function(err, patient1) {
Patient.create({ name: 'Ben' }, function(err, patient2) {
Appointment.create({ appointmentDate: new Date(), physicianId: physician1.id, patientId: patient1.id },
function(err, appt1) {
Appointment.create({ appointmentDate: new Date(), physicianId: physician1.id, patientId: patient2.id },
function(err, appt2) {
physician1.patients(console.log);
physician1.patients({where: {name: 'Mary'}}, console.log);
physician1.patients({ where: { name: 'Mary' }}, console.log);
patient1.physicians(console.log);
// 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);
// 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);
});
@ -116,32 +116,32 @@ Physician.create({name: 'Dr John'}, function (err, physician1) {
});
var Assembly = ds.createModel('Assembly', {
name: String
name: String,
});
var Part = ds.createModel('Part', {
partNumber: String
partNumber: String,
});
Assembly.hasAndBelongsToMany(Part);
Part.hasAndBelongsToMany(Assembly);
Assembly.create({name: 'car'}, function (err, assembly) {
Part.create({partNumber: 'engine'}, function (err, part) {
assembly.parts.add(part, function (err) {
Assembly.create({ name: 'car' }, function(err, assembly) {
Part.create({ partNumber: 'engine' }, function(err, part) {
assembly.parts.add(part, function(err) {
assembly.parts(function(err, parts) {
console.log('Parts: ', parts);
});
// Build an part?
var part3 = assembly.parts.build({partNumber: 'door'});
var part3 = assembly.parts.build({ partNumber: 'door' });
console.log('Part3: ', part3, part3.constructor.modelName);
// 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);
Assembly.find({include: 'parts'}, function(err, assemblies) {
Assembly.find({ include: 'parts' }, function(err, assemblies) {
console.log('Assemblies: ', assemblies);
});
});

View File

@ -10,12 +10,12 @@ exports.GeoPoint = require('./lib/geo.js').GeoPoint;
exports.ValidationError = require('./lib/validations.js').ValidationError;
Object.defineProperty(exports, 'version', {
get: function() {return require('./package.json').version;}
get: function() { return require('./package.json').version; },
});
var commonTest = './test/common_test';
Object.defineProperty(exports, 'test', {
get: function() {return require(commonTest);}
get: function() { return require(commonTest); },
});
exports.Transaction = require('loopback-connector').Transaction;

View File

@ -49,7 +49,7 @@ Memory.prototype.getTypes = function() {
return ['db', 'nosql', 'memory'];
};
Memory.prototype.connect = function (callback) {
Memory.prototype.connect = function(callback) {
if (this.isTransaction) {
this.onTransactionExec = callback;
} else {
@ -58,17 +58,17 @@ Memory.prototype.connect = function (callback) {
};
function serialize(obj) {
if(obj === null || obj === undefined) {
if (obj === null || obj === undefined) {
return obj;
}
return JSON.stringify(obj);
}
function deserialize(dbObj) {
if(dbObj === null || dbObj === undefined) {
if (dbObj === null || dbObj === undefined) {
return dbObj;
}
if(typeof dbObj === 'string') {
if (typeof dbObj === 'string') {
return JSON.parse(dbObj);
} else {
return dbObj;
@ -81,12 +81,12 @@ Memory.prototype.getCollection = function(model) {
model = modelClass.settings.memory.collection || model;
}
return model;
}
};
Memory.prototype.initCollection = function(model) {
this.collection(model, {});
this.collectionSeq(model, 1);
}
};
Memory.prototype.collection = function(model, val) {
model = this.getCollection(model);
@ -106,14 +106,14 @@ Memory.prototype.loadFromFile = function(callback) {
var localStorage = hasLocalStorage && this.settings.localStorage;
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') {
callback && callback(err);
} else {
parseAndLoad(data);
}
});
} else if(localStorage) {
} else if (localStorage) {
var data = window.localStorage.getItem(localStorage);
data = data || '{}';
parseAndLoad(data);
@ -125,14 +125,14 @@ Memory.prototype.loadFromFile = function(callback) {
if (data) {
try {
data = JSON.parse(data.toString());
} catch(e) {
} catch (e) {
return callback(e);
}
self.ids = data.ids || {};
self.cache = data.models || {};
} else {
if(!self.cache) {
if (!self.cache) {
self.ids = {};
self.cache = {};
}
@ -145,22 +145,22 @@ Memory.prototype.loadFromFile = function(callback) {
* Flush the cache into the json file if necessary
* @param {Function} callback
*/
Memory.prototype.saveToFile = function (result, callback) {
Memory.prototype.saveToFile = function(result, callback) {
var self = this;
var file = this.settings.file;
var hasLocalStorage = typeof window !== 'undefined' && window.localStorage;
var localStorage = hasLocalStorage && this.settings.localStorage;
if (file) {
if(!self.writeQueue) {
if (!self.writeQueue) {
// Create a queue for writes
self.writeQueue = async.queue(function (task, cb) {
self.writeQueue = async.queue(function(task, cb) {
// Flush out the models/ids
var data = JSON.stringify({
ids: self.ids,
models: self.cache
models: self.cache,
}, null, ' ');
fs.writeFile(self.settings.file, data, function (err) {
fs.writeFile(self.settings.file, data, function(err) {
cb(err);
task.callback && task.callback(err, task.data);
});
@ -169,20 +169,20 @@ Memory.prototype.saveToFile = function (result, callback) {
// Enqueue the write
self.writeQueue.push({
data: result,
callback: callback
callback: callback,
});
} else if (localStorage) {
// Flush out the models/ids
var data = JSON.stringify({
ids: self.ids,
models: self.cache
models: self.cache,
}, null, ' ');
window.localStorage.setItem(localStorage, data);
process.nextTick(function () {
process.nextTick(function() {
callback && callback(null, result);
});
} else {
process.nextTick(function () {
process.nextTick(function() {
callback && callback(null, result);
});
}
@ -191,7 +191,7 @@ Memory.prototype.saveToFile = function (result, callback) {
Memory.prototype.define = function defineModel(definition) {
this.constructor.super_.prototype.define.apply(this, [].slice.call(arguments));
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) {
@ -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;
this.exists(model, self.getIdValue(model, data), options, function (err, exists) {
this.exists(model, self.getIdValue(model, data), options, function(err, exists) {
if (exists) {
self.save(model, data, options, function(err, data) {
callback(err, data, { isNewInstance: false });
});
} else {
self.create(model, data, options, function (err, id) {
self.create(model, data, options, function(err, id) {
self.setIdValue(model, data, id);
callback(err, data, { isNewInstance: true });
});
@ -256,7 +256,7 @@ Memory.prototype.findOrCreate = function(model, filter, data, callback) {
var nodes = self._findAllSkippingIncludes(model, filter);
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
return self._createSync(model, data, function(err, id) {
if (err) return callback(err);
@ -272,7 +272,7 @@ Memory.prototype.findOrCreate = function(model, filter, data, callback) {
callback(null, found, false);
});
}
self._models[model].model.include(nodes[0], filter.include, {}, function(err, nodes) {
process.nextTick(function() {
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) {
process.nextTick(function () {
process.nextTick(function() {
callback(null, this.collection(model) && this.collection(model).hasOwnProperty(id));
}.bind(this));
};
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]));
}.bind(this));
};
@ -314,7 +314,7 @@ Memory.prototype.destroy = function destroy(model, id, options, callback) {
this.saveToFile({ count: exists ? 1 : 0 }, callback);
};
Memory.prototype.fromDb = function (model, data) {
Memory.prototype.fromDb = function(model, data) {
if (!data) return null;
data = deserialize(data);
var props = this._models[model].properties;
@ -357,7 +357,7 @@ function getValue(obj, path) {
}
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]);
}.bind(this));
@ -371,17 +371,17 @@ Memory.prototype._findAllSkippingIncludes = function(model, filter) {
// do we need some sorting?
if (filter.order) {
var orders = filter.order;
if (typeof filter.order === "string") {
if (typeof filter.order === 'string') {
orders = [filter.order];
}
orders.forEach(function (key, i) {
orders.forEach(function(key, i) {
var reverse = 1;
var m = key.match(/\s+(A|DE)SC$/i);
if (m) {
key = key.replace(/\s+(A|DE)SC/i, '');
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));
}
@ -408,7 +408,7 @@ Memory.prototype._findAllSkippingIncludes = function(model, filter) {
nodes = nodes.slice(skip, skip + limit);
}
return nodes;
function sorting(a, b) {
var undefinedA, undefinedB;
@ -448,18 +448,18 @@ function applyFilter(filter) {
return where;
}
var keys = Object.keys(where);
return function (obj) {
return function(obj) {
return keys.every(function(key) {
if(key === 'and' || key === 'or') {
if(Array.isArray(where[key])) {
if(key === 'and') {
if (key === 'and' || key === 'or') {
if (Array.isArray(where[key])) {
if (key === 'and') {
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 applyFilter({where: cond})(obj);
return applyFilter({ where: cond })(obj);
});
}
}
@ -475,8 +475,8 @@ function applyFilter(filter) {
if (matcher.neq !== undefined && value.length <= 0) {
return true;
}
return value.some(function (v, i) {
var filter = {where: {}};
return value.some(function(v, i) {
var filter = { where: {}};
filter.where[i] = matcher;
return applyFilter(filter)(value);
});
@ -492,15 +492,15 @@ function applyFilter(filter) {
var dotIndex = key.indexOf('.');
var subValue = obj[key.substring(0, dotIndex)];
if (dotIndex !== -1 && Array.isArray(subValue)) {
var subFilter = {where: {}};
var subKey = key.substring(dotIndex+1);
var subFilter = { where: {}};
var subKey = key.substring(dotIndex + 1);
subFilter.where[subKey] = where[key];
return subValue.some(applyFilter(subFilter));
}
return false;
});
}
};
function toRegExp(pattern) {
if (pattern instanceof RegExp) {
@ -509,7 +509,7 @@ function applyFilter(filter) {
var regex = '';
// 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
pattern = pattern.replace(/([.*+?^=!:${}()|\[\]\/\\])/g, "\\$1");
pattern = pattern.replace(/([.*+?^=!:${}()|\[\]\/\\])/g, '\\$1');
for (var i = 0, n = pattern.length; i < n; i++) {
var char = pattern.charAt(i);
if (char === '\\') {
@ -526,8 +526,7 @@ function applyFilter(filter) {
regex += '\\.';
} else if (char === '*') {
regex += '\\*';
}
else {
} else {
regex += char;
}
}
@ -567,13 +566,12 @@ function applyFilter(filter) {
return compare(example.neq, value) !== 0;
}
if ('between' in example ) {
return ( testInEquality({gte:example.between[0]}, value) &&
testInEquality({lte:example.between[1]}, value) );
if ('between' in example) {
return (testInEquality({ gte: example.between[0] }, value) &&
testInEquality({ lte: example.between[1] }, value));
}
if (example.like || example.nlike) {
var like = example.like || example.nlike;
if (typeof like === 'string') {
like = toRegExp(like);
@ -592,8 +590,8 @@ function applyFilter(filter) {
}
}
// not strict equality
return (example !== null ? example.toString() : example)
== (value != null ? value.toString() : value);
return (example !== null ? example.toString() : example) ==
(value != null ? value.toString() : value);
}
/**
@ -604,7 +602,7 @@ function applyFilter(filter) {
* @private
*/
function compare(val1, val2) {
if(val1 == null || val2 == null) {
if (val1 == null || val2 == null) {
// Either val1 or val2 is null or undefined
return val1 == val2 ? 0 : NaN;
}
@ -647,8 +645,8 @@ Memory.prototype.destroyAll = function destroyAll(model, where, options, callbac
var filter = null;
var count = 0;
if (where) {
filter = applyFilter({where: where});
Object.keys(cache).forEach(function (id) {
filter = applyFilter({ where: where });
Object.keys(cache).forEach(function(id) {
if (!filter || filter(this.fromDb(model, cache[id]))) {
count++;
delete cache[id];
@ -665,13 +663,13 @@ Memory.prototype.count = function count(model, where, options, callback) {
var cache = this.collection(model);
var data = Object.keys(cache);
if (where) {
var filter = {where: where};
data = data.map(function (id) {
var filter = { where: where };
data = data.map(function(id) {
return this.fromDb(model, cache[id]);
}.bind(this));
data = data.filter(applyFilter(filter));
}
process.nextTick(function () {
process.nextTick(function() {
callback(null, data.length);
});
};
@ -682,11 +680,11 @@ Memory.prototype.update =
var cache = this.collection(model);
var filter = null;
where = where || {};
filter = applyFilter({where: where});
filter = applyFilter({ where: where });
var ids = Object.keys(cache);
var count = 0;
async.each(ids, function (id, done) {
async.each(ids, function(id, done) {
var inst = self.fromDb(model, cache[id]);
if (!filter || filter(inst)) {
count++;
@ -697,9 +695,9 @@ Memory.prototype.update =
} else {
process.nextTick(done);
}
}, function (err) {
}, function(err) {
if (err) return cb(err);
self.saveToFile({count: count}, cb);
self.saveToFile({ count: count }, cb);
});
};
@ -745,16 +743,16 @@ Memory.prototype.replaceById = function(model, id, data, options, cb) {
}
var newModelData = {};
for(var key in data) {
for (var key in data) {
var val = data[key];
if(typeof val === 'function') {
if (typeof val === 'function') {
continue; // Skip methods
}
newModelData[key] = val;
}
this.collection(model)[id] = serialize(newModelData);
this.saveToFile(newModelData, function (err) {
this.saveToFile(newModelData, function(err) {
cb(err, self.fromDb(model, newModelData));
});
};
@ -763,13 +761,13 @@ Memory.prototype.replaceOrCreate = function(model, data, options, callback) {
var self = this;
var idName = self.idNames(model)[0];
var idValue = self.getIdValue(model, data);
var filter = {where: {}};
var filter = { where: {}};
filter.where[idName] = idValue;
var nodes = self._findAllSkippingIncludes(model, filter);
var found = nodes[0];
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
return self._createSync(model, data, function(err, id) {
if (err) return process.nextTick(function() { cb(err); });
@ -782,24 +780,24 @@ Memory.prototype.replaceOrCreate = function(model, data, options, callback) {
var id = self.getIdValue(model, data);
self.collection(model)[id] = serialize(data);
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);
};
Memory.prototype.exec = function (callback) {
Memory.prototype.exec = function(callback) {
this.onTransactionExec();
setTimeout(callback, 50);
};
Memory.prototype.buildNearFilter = function (filter) {
Memory.prototype.buildNearFilter = function(filter) {
// noop
}
};
Memory.prototype.automigrate = function (models, cb) {
Memory.prototype.automigrate = function(models, cb) {
var self = this;
if ((!cb) && ('function' === typeof models)) {
@ -831,7 +829,7 @@ Memory.prototype.automigrate = function (models, cb) {
self.initCollection(m);
});
if (cb) process.nextTick(cb);
}
};
function merge(base, update) {
if (!base) {
@ -839,9 +837,9 @@ function merge(base, update) {
}
// 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
for(var key in update) {
for (var key in update) {
var val = update[key];
if(typeof val === 'function') {
if (typeof val === 'function') {
continue; // Skip methods
}
base[key] = val;

View File

@ -47,7 +47,7 @@ Transient.prototype.getTypes = function() {
return ['db', 'nosql', 'transient'];
};
Transient.prototype.connect = function (callback) {
Transient.prototype.connect = function(callback) {
if (this.isTransaction) {
this.onTransactionExec = callback;
} else {
@ -63,26 +63,26 @@ Transient.prototype.generateId = function(model, data, idName) {
if (idType === Number) {
return Math.floor(Math.random() * 10000); // max. 4 digits
} else {
return crypto.randomBytes(Math.ceil(24/2))
return crypto.randomBytes(Math.ceil(24 / 2))
.toString('hex') // convert to hexadecimal format
.slice(0, 24); // return required number of characters
}
};
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) {
process.nextTick(function () { callback(null, null); }.bind(this));
process.nextTick(function() { callback(null, null); }.bind(this));
};
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) {
process.nextTick(function () { callback(null, 0); });
process.nextTick(function() { callback(null, 0); });
};
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.updateAll = function updateAll(model, where, data, cb) {
var count = 0;
this.flush('update', {count: count}, cb);
};
this.flush('update', { count: count }, cb);
};
Transient.prototype.updateAttributes = function updateAttributes(model, id, data, cb) {
if (!id) {
@ -136,15 +136,15 @@ Transient.prototype.destroyAll = function destroyAll(model, where, callback) {
* Flush the cache - noop.
* @param {Function} callback
*/
Transient.prototype.flush = function (action, result, callback) {
process.nextTick(function () { callback && callback(null, result); });
Transient.prototype.flush = function(action, result, callback) {
process.nextTick(function() { callback && callback(null, result); });
};
Transient.prototype.transaction = function () {
Transient.prototype.transaction = function() {
return new Transient(this);
};
Transient.prototype.exec = function (callback) {
Transient.prototype.exec = function(callback) {
this.onTransactionExec();
setTimeout(callback, 50);
};

File diff suppressed because it is too large Load Diff

View File

@ -120,11 +120,11 @@ function DataSource(name, settings, modelBuilder) {
// DataAccessObject - connector defined or supply the default
var dao = (connector && connector.DataAccessObject) || this.constructor.DataAccessObject;
this.DataAccessObject = function () {
this.DataAccessObject = function() {
};
// define DataAccessObject methods
Object.keys(dao).forEach(function (name) {
Object.keys(dao).forEach(function(name) {
var fn = dao[name];
this.DataAccessObject[name] = fn;
@ -135,13 +135,13 @@ function DataSource(name, settings, modelBuilder) {
http: fn.http,
remoteEnabled: fn.shared ? true : false,
scope: this.DataAccessObject,
fnName: name
fnName: name,
});
}
}.bind(this));
// define DataAccessObject.prototype methods
Object.keys(dao.prototype).forEach(function (name) {
Object.keys(dao.prototype).forEach(function(name) {
var fn = dao.prototype[name];
this.DataAccessObject.prototype[name] = fn;
if (typeof fn === 'function') {
@ -152,7 +152,7 @@ function DataSource(name, settings, modelBuilder) {
http: fn.http,
remoteEnabled: fn.shared ? true : false,
scope: this.DataAccessObject.prototype,
fnName: name
fnName: name,
});
}
}.bind(this));
@ -168,7 +168,7 @@ DataSource.DataAccessObject = DataAccessObject;
* Set up the connector instance for backward compatibility with JugglingDB schema/adapter
* @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.adapter = this.connector; // Keep the adapter as an alias to connector
if (this.connector) {
@ -177,14 +177,14 @@ DataSource.prototype._setupConnector = function () {
this.connector.dataSource = this;
}
var dataSource = this;
this.connector.log = function (query, start) {
this.connector.log = function(query, start) {
dataSource.log(query, start);
};
this.connector.logger = function (query) {
this.connector.logger = function(query) {
var t1 = Date.now();
var log = this.log;
return function (q) {
return function(q) {
log(q || query, t1);
};
};
@ -233,7 +233,7 @@ function tryModules(names, loader) {
* @returns {*}
* @private
*/
DataSource._resolveConnector = function (name, loader) {
DataSource._resolveConnector = function(name, loader) {
var names = connectorModuleNames(name);
var connector = tryModules(names, loader);
var error = null;
@ -244,7 +244,7 @@ DataSource._resolveConnector = function (name, loader) {
}
return {
connector: connector,
error: error
error: error,
};
};
@ -255,7 +255,7 @@ DataSource._resolveConnector = function (name, loader) {
* @returns {*}
* @private
*/
DataSource.prototype.setup = function (name, settings) {
DataSource.prototype.setup = function(name, settings) {
var dataSource = this;
var connector;
@ -341,7 +341,7 @@ DataSource.prototype.setup = function (name, settings) {
this.connector = new connector(this.settings);
postInit();
}
} catch(err) {
} catch (err) {
if (err.message) {
err.message = 'Cannot initialize connector ' +
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;
if (dataSource.connected || dataSource.connecting) {
process.nextTick(function () {
process.nextTick(function() {
cb && cb();
});
return;
}
dataSource.connecting = true;
if (dataSource.connector.connect) {
dataSource.connector.connect(function (err, result) {
dataSource.connector.connect(function(err, result) {
if (!err) {
dataSource.connected = true;
dataSource.connecting = false;
@ -374,7 +374,7 @@ DataSource.prototype.setup = function (name, settings) {
cb && cb(err, result);
});
} else {
process.nextTick(function () {
process.nextTick(function() {
dataSource.connected = true;
dataSource.connecting = false;
dataSource.emit('connected');
@ -402,7 +402,7 @@ function isModelDataSourceAttached(model) {
* @param modelClass
* @param scopes
*/
DataSource.prototype.defineScopes = function (modelClass, scopes) {
DataSource.prototype.defineScopes = function(modelClass, scopes) {
if (scopes) {
for (var s in scopes) {
defineScope(modelClass, modelClass, s, scopes[s], {}, scopes[s].options);
@ -415,13 +415,13 @@ DataSource.prototype.defineScopes = function (modelClass, scopes) {
* @param modelClass
* @param relations
*/
DataSource.prototype.defineRelations = function (modelClass, relations) {
DataSource.prototype.defineRelations = function(modelClass, relations) {
var self = this;
// 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)) {
targetModel.once('dataAccessConfigured', function (model) {
targetModel.once('dataAccessConfigured', function(model) {
// Check if the through model doesn't exist or resolved
if (!throughModel || isModelDataSourceAttached(throughModel)) {
// The target model is resolved
@ -438,7 +438,7 @@ DataSource.prototype.defineRelations = function (modelClass, relations) {
}
if (throughModel && !isModelDataSourceAttached(throughModel)) {
// Set up a listener to the through model
throughModel.once('dataAccessConfigured', function (model) {
throughModel.once('dataAccessConfigured', function(model) {
if (isModelDataSourceAttached(targetModel)) {
// The target model is resolved
var params = traverse(relation).clone();
@ -453,9 +453,9 @@ DataSource.prototype.defineRelations = function (modelClass, relations) {
// Set up the relations
if (relations) {
Object.keys(relations).forEach(function (rn) {
Object.keys(relations).forEach(function(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;
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 {Object} settings The settings object
*/
DataSource.prototype.setupDataAccess = function (modelClass, settings) {
DataSource.prototype.setupDataAccess = function(modelClass, settings) {
if (this.connector) {
// Check if the id property should be generated
var idName = modelClass.definition.idName();
@ -515,7 +515,7 @@ DataSource.prototype.setupDataAccess = function (modelClass, settings) {
modelClass.definition.rawProperties[idName].type = idType;
modelClass.definition.properties[idName].type = idType;
if (settings.forceId) {
modelClass.validatesAbsenceOf(idName, {if: 'isNewRecord'});
modelClass.validatesAbsenceOf(idName, { if: 'isNewRecord' });
}
}
if (this.connector.define) {
@ -523,7 +523,7 @@ DataSource.prototype.setupDataAccess = function (modelClass, settings) {
this.connector.define({
model: modelClass,
properties: modelClass.definition.properties,
settings: settings
settings: settings,
});
}
}
@ -642,15 +642,15 @@ DataSource.prototype.createModel = DataSource.prototype.define = function define
* @private
*/
DataSource.prototype.mixin = function (ModelCtor) {
DataSource.prototype.mixin = function(ModelCtor) {
var ops = this.operations();
var DAO = this.DataAccessObject;
// mixin DAO
jutil.mixin(ModelCtor, DAO, {proxyFunctions: true, override: true});
jutil.mixin(ModelCtor, DAO, { proxyFunctions: true, override: true });
// decorate operations as alias functions
Object.keys(ops).forEach(function (name) {
Object.keys(ops).forEach(function(name) {
var op = ops[name];
var scope;
@ -660,15 +660,15 @@ DataSource.prototype.mixin = function (ModelCtor) {
// op.scope[op.fnName].apply(self, arguments);
// }
Object.keys(op)
.filter(function (key) {
.filter(function(key) {
// filter out the following keys
return ~[
'scope',
'fnName',
'prototype'
'prototype',
].indexOf(key);
})
.forEach(function (key) {
.forEach(function(key) {
if (typeof op[key] !== 'undefined') {
op.scope[op.fnName][key] = op[key];
}
@ -680,14 +680,14 @@ DataSource.prototype.mixin = function (ModelCtor) {
/**
* See ModelBuilder.getModel
*/
DataSource.prototype.getModel = function (name, forceCreate) {
DataSource.prototype.getModel = function(name, forceCreate) {
return this.modelBuilder.getModel(name, forceCreate);
};
/**
* See ModelBuilder.getModelDefinition
*/
DataSource.prototype.getModelDefinition = function (name) {
DataSource.prototype.getModelDefinition = function(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'],
* ['rest'], or ['db', 'rdbms', 'mysql']
*/
DataSource.prototype.getTypes = function () {
DataSource.prototype.getTypes = function() {
var getTypes = this.connector && this.connector.getTypes;
var types = getTypes && getTypes() || [];
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.
* @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();
if (Array.isArray(types)) {
// Check each of the types
@ -733,7 +733,7 @@ DataSource.prototype.supportTypes = function (types) {
* @param {Function} modelClass The model constructor
*/
DataSource.prototype.attach = function (modelClass) {
DataSource.prototype.attach = function(modelClass) {
if (modelClass.dataSource === this) {
// Already attached to the data source
return modelClass;
@ -762,7 +762,7 @@ DataSource.prototype.attach = function (modelClass) {
* @param {String} prop Name of property
* @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);
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();
if ((!cb) && ('function' === typeof models)) {
@ -813,13 +813,13 @@ DataSource.prototype.automigrate = function (models, cb) {
return cb.promise;
}
var invalidModels = models.filter(function (m) {
var invalidModels = models.filter(function(m) {
return !(m in attachedModels);
});
if (invalidModels.length) {
process.nextTick(function () {
cb(new Error('Cannot migrate models not attached to this datasource: ' +
process.nextTick(function() {
cb(new Error('Cannot migrate models not attached to this datasource: ' +
invalidModels.join(' ')));
});
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 {Function} [cb] The callback function
*/
DataSource.prototype.autoupdate = function (models, cb) {
DataSource.prototype.autoupdate = function(models, cb) {
this.freeze();
if ((!cb) && ('function' === typeof models)) {
@ -868,12 +868,12 @@ DataSource.prototype.autoupdate = function (models, cb) {
return cb.promise;
}
var invalidModels = models.filter(function (m) {
var invalidModels = models.filter(function(m) {
return !(m in attachedModels);
});
if (invalidModels.length) {
process.nextTick(function () {
process.nextTick(function() {
cb(new Error('Cannot migrate models not attached to this datasource: ' +
invalidModels.join(' ')));
});
@ -898,7 +898,7 @@ DataSource.prototype.autoupdate = function (models, cb) {
* @property {Number} offset Starting index
*
*/
DataSource.prototype.discoverModelDefinitions = function (options, cb) {
DataSource.prototype.discoverModelDefinitions = function(options, cb) {
this.freeze();
if (cb === undefined && typeof options === 'function') {
@ -925,7 +925,7 @@ DataSource.prototype.discoverModelDefinitions = function (options, cb) {
* @property {Number} offset Starting index
* @returns {*}
*/
DataSource.prototype.discoverModelDefinitionsSync = function (options) {
DataSource.prototype.discoverModelDefinitionsSync = function(options) {
this.freeze();
if (this.connector.discoverModelDefinitionsSync) {
return this.connector.discoverModelDefinitionsSync(options);
@ -955,7 +955,7 @@ DataSource.prototype.discoverModelDefinitionsSync = function (options) {
* @param {Function} cb Callback function. Optional
*
*/
DataSource.prototype.discoverModelProperties = function (modelName, options, cb) {
DataSource.prototype.discoverModelProperties = function(modelName, options, cb) {
this.freeze();
if (cb === undefined && typeof options === 'function') {
@ -970,7 +970,7 @@ DataSource.prototype.discoverModelProperties = function (modelName, options, cb)
} else if (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
* @returns {*}
*/
DataSource.prototype.discoverModelPropertiesSync = function (modelName, options) {
DataSource.prototype.discoverModelPropertiesSync = function(modelName, options) {
this.freeze();
if (this.connector.discoverModelPropertiesSync) {
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
* @param {Function} [cb] The callback function
*/
DataSource.prototype.discoverPrimaryKeys = function (modelName, options, cb) {
DataSource.prototype.discoverPrimaryKeys = function(modelName, options, cb) {
this.freeze();
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
* @returns {*}
*/
DataSource.prototype.discoverPrimaryKeysSync = function (modelName, options) {
DataSource.prototype.discoverPrimaryKeysSync = function(modelName, options) {
this.freeze();
if (this.connector.discoverPrimaryKeysSync) {
return this.connector.discoverPrimaryKeysSync(modelName, options);
@ -1060,7 +1060,7 @@ DataSource.prototype.discoverPrimaryKeysSync = function (modelName, options) {
* @param {Function} [cb] The callback function
*
*/
DataSource.prototype.discoverForeignKeys = function (modelName, options, cb) {
DataSource.prototype.discoverForeignKeys = function(modelName, options, cb) {
this.freeze();
if (cb === undefined && typeof options === 'function') {
@ -1085,7 +1085,7 @@ DataSource.prototype.discoverForeignKeys = function (modelName, options, cb) {
* @param {Object} options The options
* @returns {*}
*/
DataSource.prototype.discoverForeignKeysSync = function (modelName, options) {
DataSource.prototype.discoverForeignKeysSync = function(modelName, options) {
this.freeze();
if (this.connector.discoverForeignKeysSync) {
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
* @param {Function} [cb] The callback function
*/
DataSource.prototype.discoverExportedForeignKeys = function (modelName, options, cb) {
DataSource.prototype.discoverExportedForeignKeys = function(modelName, options, cb) {
this.freeze();
if (cb === undefined && typeof options === 'function') {
@ -1140,7 +1140,7 @@ DataSource.prototype.discoverExportedForeignKeys = function (modelName, options,
* @param {Object} options The options
* @returns {*}
*/
DataSource.prototype.discoverExportedForeignKeysSync = function (modelName, options) {
DataSource.prototype.discoverExportedForeignKeysSync = function(modelName, options) {
this.freeze();
if (this.connector.discoverExportedForeignKeysSync) {
return this.connector.discoverExportedForeignKeysSync(modelName, options);
@ -1226,7 +1226,7 @@ function fromDBName(dbName, camelCase) {
* @param {Object} [options] The options
* @param {Function} [cb] The callback function
*/
DataSource.prototype.discoverSchema = function (modelName, options, cb) {
DataSource.prototype.discoverSchema = function(modelName, options, cb) {
options = options || {};
if (!cb && 'function' === typeof options) {
@ -1238,7 +1238,7 @@ DataSource.prototype.discoverSchema = function (modelName, options, cb) {
cb = cb || utils.createPromiseCallback();
this.discoverSchemas(modelName, options, function (err, schemas) {
this.discoverSchemas(modelName, options, function(err, schemas) {
if (err) {
cb && cb(err, schemas);
return;
@ -1262,7 +1262,7 @@ DataSource.prototype.discoverSchema = function (modelName, options, cb) {
* @property {Boolean} views True if views are included; false otherwise.
* @param {Function} [cb] The callback function
*/
DataSource.prototype.discoverSchemas = function (modelName, options, cb) {
DataSource.prototype.discoverSchemas = function(modelName, options, cb) {
options = 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));
}
async.parallel(tasks, function (err, results) {
async.parallel(tasks, function(err, results) {
if (err) {
cb(err);
@ -1326,7 +1326,7 @@ DataSource.prototype.discoverSchemas = function (modelName, options, cb) {
// Handle primary keys
var primaryKeys = results[1] || [];
var pks = {};
primaryKeys.forEach(function (pk) {
primaryKeys.forEach(function(pk) {
pks[pk.columnName] = pk.keySeq;
});
@ -1337,17 +1337,17 @@ DataSource.prototype.discoverSchemas = function (modelName, options, cb) {
var schema = {
name: nameMapper('table', modelName),
options: {
idInjection: false // DO NOT add id property
idInjection: false, // DO NOT add id property
},
properties: {}
properties: {},
};
schema.options[dbType] = {
schema: columns[0].owner,
table: modelName
table: modelName,
};
columns.forEach(function (item) {
columns.forEach(function(item) {
var i = item;
var propName = nameMapper('column', item.columnName);
@ -1357,7 +1357,7 @@ DataSource.prototype.discoverSchemas = function (modelName, options, cb) {
|| item.nullable === 0 || item.nullable === false),
length: item.dataLength,
precision: item.dataPrecision,
scale: item.dataScale
scale: item.dataScale,
};
if (pks[item.columnName]) {
@ -1369,7 +1369,7 @@ DataSource.prototype.discoverSchemas = function (modelName, options, cb) {
dataLength: i.dataLength,
dataPrecision: item.dataPrecision,
dataScale: item.dataScale,
nullable: i.nullable
nullable: i.nullable,
};
});
@ -1388,12 +1388,12 @@ DataSource.prototype.discoverSchemas = function (modelName, options, cb) {
// Handle foreign keys
var fks = {};
var foreignKeys = results[2] || [];
foreignKeys.forEach(function (fk) {
foreignKeys.forEach(function(fk) {
var fkInfo = {
keySeq: fk.keySeq,
owner: fk.pkOwner,
tableName: fk.pkTableName,
columnName: fk.pkColumnName
columnName: fk.pkColumnName,
};
if (fks[fk.fkName]) {
fks[fk.fkName].push(fkInfo);
@ -1407,17 +1407,17 @@ DataSource.prototype.discoverSchemas = function (modelName, options, cb) {
}
schema.options.relations = {};
foreignKeys.forEach(function (fk) {
foreignKeys.forEach(function(fk) {
var propName = nameMapper('column', fk.pkTableName);
schema.options.relations[propName] = {
model: nameMapper('table', fk.pkTableName),
type: 'belongsTo',
foreignKey: nameMapper('column', fk.fkColumnName)
foreignKey: nameMapper('column', fk.fkColumnName),
};
var key = fk.pkOwner + '.' + fk.pkTableName;
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));
}
async.parallel(moreTasks, function (err, results) {
async.parallel(moreTasks, function(err, results) {
var result = results && results[0];
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} views True if views are included; false otherwise.
*/
DataSource.prototype.discoverSchemasSync = function (modelName, options) {
DataSource.prototype.discoverSchemasSync = function(modelName, options) {
var self = this;
var dbType = this.name || this.connector.name;
@ -1477,7 +1477,7 @@ DataSource.prototype.discoverSchemasSync = function (modelName, options) {
// Handle primary keys
var primaryKeys = this.discoverPrimaryKeysSync(modelName, options);
var pks = {};
primaryKeys.forEach(function (pk) {
primaryKeys.forEach(function(pk) {
pks[pk.columnName] = pk.keySeq;
});
@ -1488,17 +1488,17 @@ DataSource.prototype.discoverSchemasSync = function (modelName, options) {
var schema = {
name: nameMapper('table', modelName),
options: {
idInjection: false // DO NOT add id property
idInjection: false, // DO NOT add id property
},
properties: {}
properties: {},
};
schema.options[dbType] = {
schema: columns.length > 0 && columns[0].owner,
table: modelName
table: modelName,
};
columns.forEach(function (item) {
columns.forEach(function(item) {
var i = item;
var propName = nameMapper('column', item.columnName);
@ -1507,7 +1507,7 @@ DataSource.prototype.discoverSchemasSync = function (modelName, options) {
required: (item.nullable === 'N'),
length: item.dataLength,
precision: item.dataPrecision,
scale: item.dataScale
scale: item.dataScale,
};
if (pks[item.columnName]) {
@ -1519,7 +1519,7 @@ DataSource.prototype.discoverSchemasSync = function (modelName, options) {
dataLength: i.dataLength,
dataPrecision: item.dataPrecision,
dataScale: item.dataScale,
nullable: i.nullable
nullable: i.nullable,
};
});
@ -1539,12 +1539,12 @@ DataSource.prototype.discoverSchemasSync = function (modelName, options) {
// Handle foreign keys
var fks = {};
var foreignKeys = this.discoverForeignKeysSync(modelName, options);
foreignKeys.forEach(function (fk) {
foreignKeys.forEach(function(fk) {
var fkInfo = {
keySeq: fk.keySeq,
owner: fk.pkOwner,
tableName: fk.pkTableName,
columnName: fk.pkColumnName
columnName: fk.pkColumnName,
};
if (fks[fk.fkName]) {
fks[fk.fkName].push(fkInfo);
@ -1558,17 +1558,17 @@ DataSource.prototype.discoverSchemasSync = function (modelName, options) {
}
schema.options.relations = {};
foreignKeys.forEach(function (fk) {
foreignKeys.forEach(function(fk) {
var propName = nameMapper('column', fk.pkTableName);
schema.options.relations[propName] = {
model: nameMapper('table', fk.pkTableName),
type: 'belongsTo',
foreignKey: nameMapper('column', fk.fkColumnName)
foreignKey: nameMapper('column', fk.fkColumnName),
};
var key = fk.pkOwner + '.' + fk.pkTableName;
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.
* @param {Function} [cb] The callback function
*/
DataSource.prototype.discoverAndBuildModels = function (modelName, options, cb) {
DataSource.prototype.discoverAndBuildModels = function(modelName, options, cb) {
var self = this;
options = options || {};
this.discoverSchemas(modelName, options, function (err, schemas) {
this.discoverSchemas(modelName, options, function(err, schemas) {
if (err) {
cb && cb(err, schemas);
return;
@ -1643,7 +1643,7 @@ DataSource.prototype.discoverAndBuildModels = function (modelName, options, cb)
* @param {String} modelName The model name
* @param {Object} [options] The options
*/
DataSource.prototype.discoverAndBuildModelsSync = function (modelName, options) {
DataSource.prototype.discoverAndBuildModelsSync = function(modelName, options) {
options = options || {};
var schemas = this.discoverSchemasSync(modelName, options);
@ -1670,7 +1670,7 @@ DataSource.prototype.discoverAndBuildModelsSync = function (modelName, options)
* @param {Object} options Options
* @returns {*}
*/
DataSource.prototype.buildModelFromInstance = function (name, json, options) {
DataSource.prototype.buildModelFromInstance = function(name, json, options) {
// Introspect the JSON document to generate a schema
var schema = ModelBuilder.introspect(json);
@ -1684,7 +1684,7 @@ DataSource.prototype.buildModelFromInstance = function (name, json, options) {
* 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.
*/
DataSource.prototype.isActual = function (models, cb) {
DataSource.prototype.isActual = function(models, cb) {
this.freeze();
if (this.connector.isActual) {
this.connector.isActual(models, cb);
@ -1694,7 +1694,7 @@ DataSource.prototype.isActual = function (models, cb) {
models = undefined;
}
if (cb) {
process.nextTick(function () {
process.nextTick(function() {
cb(null, true);
});
}
@ -1707,7 +1707,7 @@ DataSource.prototype.isActual = function (models, cb) {
*
* @private used by connectors
*/
DataSource.prototype.log = function (sql, t) {
DataSource.prototype.log = function(sql, t) {
debug(sql, t);
this.emit('log', sql, t);
};
@ -1731,7 +1731,7 @@ DataSource.prototype.freeze = function freeze() {
* Return table name for specified `modelName`
* @param {String} modelName The model name
*/
DataSource.prototype.tableName = function (modelName) {
DataSource.prototype.tableName = function(modelName) {
return this.getModelDefinition(modelName).tableName(this.connector.name);
};
@ -1741,7 +1741,7 @@ DataSource.prototype.tableName = function (modelName) {
* @param {String} propertyName The property 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);
};
@ -1751,7 +1751,7 @@ DataSource.prototype.columnName = function (modelName, propertyName) {
* @param {String} propertyName The property name
* @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);
};
@ -1760,7 +1760,7 @@ DataSource.prototype.columnMetadata = function (modelName, propertyName) {
* @param {String} modelName The model name
* @returns {String[]} column names
*/
DataSource.prototype.columnNames = function (modelName) {
DataSource.prototype.columnNames = function(modelName) {
return this.getModelDefinition(modelName).columnNames(this.connector.name);
};
@ -1769,7 +1769,7 @@ DataSource.prototype.columnNames = function (modelName) {
* @param {String} modelName The model name
* @returns {String} columnName for ID
*/
DataSource.prototype.idColumnName = function (modelName) {
DataSource.prototype.idColumnName = function(modelName) {
return this.getModelDefinition(modelName).idColumnName(this.connector.name);
};
@ -1778,7 +1778,7 @@ DataSource.prototype.idColumnName = function (modelName) {
* @param {String} modelName The model name
* @returns {String} property name for ID
*/
DataSource.prototype.idName = function (modelName) {
DataSource.prototype.idName = function(modelName) {
if (!this.getModelDefinition(modelName).idName) {
console.error('No id name', this.getModelDefinition(modelName));
}
@ -1790,7 +1790,7 @@ DataSource.prototype.idName = function (modelName) {
* @param {String} modelName The model name
* @returns {String[]} property names for IDs
*/
DataSource.prototype.idNames = function (modelName) {
DataSource.prototype.idNames = function(modelName) {
return this.getModelDefinition(modelName).idNames();
};
@ -1799,7 +1799,7 @@ DataSource.prototype.idNames = function (modelName) {
* @param {String} modelName The model name
* @returns {Object} The id property definition
*/
DataSource.prototype.idProperty = function (modelName) {
DataSource.prototype.idProperty = function(modelName) {
var def = this.getModelDefinition(modelName);
var idProps = def && def.ids();
return idProps && idProps[0] && idProps[0].property;
@ -1828,7 +1828,7 @@ DataSource.prototype.defineForeignKey = function defineForeignKey(className, key
return;
}
var fkDef = {type: pkType};
var fkDef = { type: pkType };
var foreignMeta = this.columnMetadata(foreignClassName, pkName);
if (foreignMeta && (foreignMeta.dataType || foreignMeta.dataLength)) {
fkDef[this.connector.name] = {};
@ -1840,7 +1840,7 @@ DataSource.prototype.defineForeignKey = function defineForeignKey(className, key
}
}
if (this.connector.defineForeignKey) {
var cb = function (err, keyType) {
var cb = function(err, keyType) {
if (err) throw err;
fkDef.type = keyType || pkType;
// 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) {
var self = this;
if (this.connected && (typeof this.connector.disconnect === 'function')) {
this.connector.disconnect(function (err, result) {
this.connector.disconnect(function(err, result) {
self.connected = false;
cb && cb(err, result);
});
} else {
process.nextTick(function () {
process.nextTick(function() {
cb && cb();
});
}
@ -1914,7 +1914,7 @@ DataSource.prototype.copyModel = function copyModel(Master) {
dataSource.connector.define({
model: Slave,
properties: md.properties,
settings: md.settings
settings: md.settings,
});
}
@ -1928,7 +1928,7 @@ DataSource.prototype.copyModel = function copyModel(Master) {
* @returns {EventEmitter}
* @private
*/
DataSource.prototype.transaction = function () {
DataSource.prototype.transaction = function() {
var dataSource = this;
var transaction = new EventEmitter();
@ -1953,7 +1953,7 @@ DataSource.prototype.transaction = function () {
dataSource.copyModel.call(transaction, dataSource.modelBuilder.models[i]);
}
transaction.exec = function (cb) {
transaction.exec = function(cb) {
transaction.connector.exec(cb);
};
@ -1966,14 +1966,14 @@ DataSource.prototype.transaction = function () {
* @param {String} operation The operation name
*/
DataSource.prototype.enableRemote = function (operation) {
DataSource.prototype.enableRemote = function(operation) {
var op = this.getOperation(operation);
if (op) {
op.remoteEnabled = true;
} else {
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
@ -1995,21 +1995,21 @@ DataSource.prototype.enableRemote = function (operation) {
* @param {String} operation The operation name
*/
DataSource.prototype.disableRemote = function (operation) {
DataSource.prototype.disableRemote = function(operation) {
var op = this.getOperation(operation);
if (op) {
op.remoteEnabled = false;
} else {
throw new Error(operation + ' is not provided by the attached connector');
}
}
};
/**
* Get an operation's metadata.
* @param {String} operation The operation name
*/
DataSource.prototype.getOperation = function (operation) {
DataSource.prototype.getOperation = function(operation) {
var ops = this.operations();
var opKeys = Object.keys(ops);
@ -2020,7 +2020,7 @@ DataSource.prototype.getOperation = function (operation) {
return op;
}
}
}
};
/**
* 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;
}
};
/**
* Define an operation to the data source
@ -2055,7 +2055,7 @@ DataSource.prototype.operations = function () {
* @param {Object} options The options
* @param {Function} fn The function
*/
DataSource.prototype.defineOperation = function (name, options, fn) {
DataSource.prototype.defineOperation = function(name, options, fn) {
options.fn = fn;
options.name = name;
this._operations[name] = options;
@ -2065,7 +2065,7 @@ DataSource.prototype.defineOperation = function (name, options, fn) {
* Check if the backend is a relational DB
* @returns {Boolean}
*/
DataSource.prototype.isRelational = function () {
DataSource.prototype.isRelational = function() {
return this.connector && this.connector.relational;
};
@ -2075,7 +2075,7 @@ DataSource.prototype.isRelational = function () {
* @param {Object} obj ?
* @param {Object} args ?
*/
DataSource.prototype.ready = function (obj, args) {
DataSource.prototype.ready = function(obj, args) {
var self = this;
if (this.connected) {
// Connected
@ -2107,7 +2107,7 @@ DataSource.prototype.ready = function (obj, args) {
}
}
};
onError = function (err) {
onError = function(err) {
// Remove the connected listener
self.removeListener('connected', onConnected);
if (timeoutHandle) {
@ -2126,7 +2126,7 @@ DataSource.prototype.ready = function (obj, args) {
// Set up a timeout to cancel the invocation
var timeout = this.settings.connectionTimeout || 5000;
timeoutHandle = setTimeout(function () {
timeoutHandle = setTimeout(function() {
self.removeListener('error', onError);
self.removeListener('connected', onConnected);
var params = [].slice.call(args);
@ -2146,14 +2146,14 @@ DataSource.prototype.ready = function (obj, args) {
* Ping the underlying connector to test the connections
* @param {Function} [cb] Callback function
*/
DataSource.prototype.ping = function (cb) {
DataSource.prototype.ping = function(cb) {
var self = this;
if (self.connector.ping) {
this.connector.ping(cb);
} else if (self.connector.discoverModelProperties) {
self.discoverModelProperties('dummy', {}, cb);
} else {
process.nextTick(function () {
process.nextTick(function() {
var err = self.connected ? null : 'Not connected';
cb(err);
});
@ -2171,7 +2171,7 @@ function hiddenProperty(obj, key, value) {
writable: false,
enumerable: false,
configurable: false,
value: value
value: value,
});
}
@ -2187,7 +2187,7 @@ function defineReadonlyProp(obj, key, value) {
writable: false,
enumerable: true,
configurable: true,
value: value
value: value,
});
}
@ -2200,6 +2200,6 @@ DataSource.Any = ModelBuilder.Any;
* @deprecated Use ModelBuilder.registerType instead
* @param type
*/
DataSource.registerType = function (type) {
DataSource.registerType = function(type) {
ModelBuilder.registerType(type);
};

View File

@ -13,7 +13,7 @@ exports.nearFilter = function nearFilter(where) {
var result = false;
if (where && typeof where === 'object') {
Object.keys(where).forEach(function (key) {
Object.keys(where).forEach(function(key) {
var ex = where[key];
if (ex && ex.near) {
@ -21,20 +21,20 @@ exports.nearFilter = function nearFilter(where) {
near: ex.near,
maxDistance: ex.maxDistance,
unit: ex.unit,
key: key
key: key,
};
}
});
}
return result;
}
};
/*!
* Filter a set of objects using the given `nearFilter`.
*/
exports.filter = function (arr, filter) {
exports.filter = function(arr, filter) {
var origin = filter.near;
var max = filter.maxDistance > 0 ? filter.maxDistance : false;
var unit = filter.unit;
@ -44,7 +44,7 @@ exports.filter = function (arr, filter) {
var distances = {};
var result = [];
arr.forEach(function (obj) {
arr.forEach(function(obj) {
var loc = obj[key];
// filter out objects without locations
@ -57,7 +57,7 @@ exports.filter = function (arr, filter) {
if (typeof loc.lat !== '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) {
// 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 b = objB[key];
@ -81,31 +81,31 @@ exports.filter = function (arr, filter) {
return 0;
}
});
}
};
exports.GeoPoint = GeoPoint;
/**
/**
* The GeoPoint object represents a physical location.
*
*
* For example:
*
*
* ```js
* var loopback = require(loopback);
* var here = new loopback.GeoPoint({lat: 10.32424, lng: 5.84978});
* ```
*
*
* Embed a latitude / longitude point in a model.
*
*
* ```js
* var CoffeeShop = loopback.createModel('coffee-shop', {
* location: 'GeoPoint'
* });
* ```
*
*
* 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.
*
*
* ```js
* CoffeeShop.attachTo(oracle);
* var here = new GeoPoint({lat: 10.32424, lng: 5.84978});
@ -114,9 +114,9 @@ exports.GeoPoint = GeoPoint;
* });
* ```
* @class GeoPoint
* @property {Number} lat The latitude in degrees.
* @property {Number} lng The longitude in degrees.
*
* @property {Number} lat The latitude in degrees.
* @property {Number} lng The longitude in degrees.
*
* @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} lng The longitude point in degrees. Range: -180 to 180.
@ -131,10 +131,10 @@ function GeoPoint(data) {
return new GeoPoint(data);
}
if(arguments.length === 2) {
if (arguments.length === 2) {
data = {
lat: arguments[0],
lng: arguments[1]
lng: arguments[1],
};
}
@ -147,7 +147,7 @@ function GeoPoint(data) {
if (Array.isArray(data)) {
data = {
lat: Number(data[0]),
lng: Number(data[1])
lng: Number(data[1]),
};
} else {
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');
this.lat = data.lat;
this.lat = data.lat;
this.lng = data.lng;
}
/**
* Determine the spherical distance between two GeoPoints.
*
*
* @param {GeoPoint} pointA Point A
* @param {GeoPoint} pointB Point B
* @options {Object} options Options object with one key, 'type'. See below.
* @property {String} type Unit of measurement, one of:
*
*
* - `miles` (default)
* - `radians`
* - `kilometers`
@ -205,16 +205,16 @@ GeoPoint.distanceBetween = function distanceBetween(a, b, options) {
* Example:
* ```js
* var loopback = require(loopback);
*
*
* var here = new loopback.GeoPoint({lat: 10, lng: 10});
* var there = new loopback.GeoPoint({lat: 5, lng: 5});
*
*
* loopback.GeoPoint.distanceBetween(here, there, {type: 'miles'}) // 438
* ```
* @param {Object} point GeoPoint object to which to measure distance.
* @options {Object} options Options object with one key, 'type'. See below.
* @property {String} type Unit of measurement, one of:
*
*
* - `miles` (default)
* - `radians`
* - `kilometers`
@ -224,7 +224,7 @@ GeoPoint.distanceBetween = function distanceBetween(a, b, options) {
* - `degrees`
*/
GeoPoint.prototype.distanceTo = function (point, options) {
GeoPoint.prototype.distanceTo = function(point, options) {
return GeoPoint.distanceBetween(this, point, options);
};
@ -232,7 +232,7 @@ GeoPoint.prototype.distanceTo = function (point, options) {
* Simple serialization.
*/
GeoPoint.prototype.toString = function () {
GeoPoint.prototype.toString = function() {
return this.lat + ',' + this.lng;
};
@ -255,7 +255,7 @@ var EARTH_RADIUS = {
miles: 3958.75,
feet: 20902200,
radians: 1,
degrees: RAD2DEG
degrees: RAD2DEG,
};
function geoDistance(x1, y1, x2, y2, options) {
@ -268,7 +268,7 @@ function geoDistance(x1, y1, x2, y2, options) {
x2 = x2 * 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
var haversine = function(a) {
return Math.pow(Math.sin(a / 2.0), 2);

View File

@ -36,10 +36,10 @@ Hookable.afterDestroy = null;
// TODO: Evaluate https://github.com/bnoguchi/hooks-js/
Hookable.prototype.trigger = function trigger(actionName, work, data, callback) {
var capitalizedName = capitalize(actionName);
var beforeHook = this.constructor["before" + capitalizedName]
|| this.constructor["pre" + capitalizedName];
var afterHook = this.constructor["after" + capitalizedName]
|| this.constructor["post" + capitalizedName];
var beforeHook = this.constructor['before' + capitalizedName]
|| this.constructor['pre' + capitalizedName];
var afterHook = this.constructor['after' + capitalizedName]
|| this.constructor['post' + capitalizedName];
if (actionName === 'validate') {
beforeHook = beforeHook || this.constructor.beforeValidation;
afterHook = afterHook || this.constructor.afterValidation;
@ -57,7 +57,7 @@ Hookable.prototype.trigger = function trigger(actionName, work, data, callback)
if (work) {
if (beforeHook) {
// 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)
if (arguments.length) {
return callback && callback.apply(null, arguments);

View File

@ -100,11 +100,11 @@ function lookupModel(models, modelName) {
function execTasksWithInterLeave(tasks, callback) {
//let's give others some time to process.
//Context Switch BEFORE Heavy Computation
process.nextTick(function () {
process.nextTick(function() {
//Heavy Computation
async.parallel(tasks, function (err, info) {
async.parallel(tasks, function(err, info) {
//Context Switch AFTER Heavy Computation
process.nextTick(function () {
process.nextTick(function() {
callback(err, info);
});
});
@ -156,7 +156,7 @@ Inclusion.normalizeInclude = normalizeInclude;
* @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) {
cb = options;
options = {};
@ -236,14 +236,14 @@ Inclusion.include = function (objects, include, options, cb) {
if (filter.fields && Array.isArray(subInclude) &&
relation.modelTo.relations) {
includeScope.fields = [];
subInclude.forEach(function (name) {
subInclude.forEach(function(name) {
var rel = relation.modelTo.relations[name];
if (rel && rel.type === 'belongsTo') {
includeScope.fields.push(rel.keyFrom);
}
});
}
utils.mergeQuery(filter, includeScope, {fields: false});
utils.mergeQuery(filter, includeScope, { fields: false });
}
//Let's add a placeholder where query
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.
if(relation.type === 'hasMany' && relation.multiple && !subInclude){
if (relation.type === 'hasMany' && relation.multiple && !subInclude) {
return includeHasManySimple(cb);
}
//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
//on modelTo later in 2nd DB call.
var throughFilter = {
where: {}
where: {},
};
throughFilter.where[relation.keyTo] = {
inq: uniq(sourceIds)
inq: uniq(sourceIds),
};
if (polymorphic) {
//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
var modelToIdName = idName(relation.modelTo);
filter.where[modelToIdName] = {
inq: uniq(targetIds)
inq: uniq(targetIds),
};
//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) {
var targetId = target[modelToIdName];
var objList = targetObjsMap[targetId.toString()];
async.each(objList, function (obj, next) {
async.each(objList, function(obj, next) {
if (!obj) return next();
obj.__cachedRelations[relationName].push(target);
processTargetObj(obj, next);
@ -450,7 +450,7 @@ Inclusion.include = function (objects, include, options, cb) {
obj.__cachedRelations[relationName] = [];
}
filter.where[relation.keyTo] = {
inq: uniq(allTargetIds)
inq: uniq(allTargetIds),
};
relation.applyScope(null, filter);
/**
@ -481,7 +481,7 @@ Inclusion.include = function (objects, include, options, cb) {
async.each(targets, linkManyToMany, next);
function linkManyToMany(target, next) {
var objList = targetObjsMap[target[relation.keyTo].toString()];
async.each(objList, function (obj, next) {
async.each(objList, function(obj, next) {
if (!obj) return next();
obj.__cachedRelations[relationName].push(target);
processTargetObj(obj, next);
@ -503,21 +503,21 @@ Inclusion.include = function (objects, include, options, cb) {
var objIdMap2 = includeUtils.buildOneToOneIdentityMapWithOrigKeys(objs, relation.keyFrom);
filter.where[relation.keyTo] = {
inq: uniq(objIdMap2.getKeys())
inq: uniq(objIdMap2.getKeys()),
};
relation.applyScope(null, filter);
relation.modelTo.find(filter, options, targetFetchHandler);
function targetFetchHandler(err, targets) {
if(err) {
if (err) {
return callback(err);
}
var targetsIdMap = includeUtils.buildOneToManyIdentityMapWithOrigKeys(targets, relation.keyTo);
includeUtils.join(objIdMap2, targetsIdMap, function(obj1, valueToMergeIn){
includeUtils.join(objIdMap2, targetsIdMap, function(obj1, valueToMergeIn) {
defineCachedRelations(obj1);
obj1.__cachedRelations[relationName] = valueToMergeIn;
processTargetObj(obj1, function(){});
processTargetObj(obj1, function() {});
});
callback(err, objs);
}
@ -545,7 +545,7 @@ Inclusion.include = function (objects, include, options, cb) {
obj.__cachedRelations[relationName] = [];
}
filter.where[relation.keyTo] = {
inq: uniq(sourceIds)
inq: uniq(sourceIds),
};
relation.applyScope(null, filter);
options.partitionBy = relation.keyTo;
@ -580,7 +580,7 @@ Inclusion.include = function (objects, include, options, cb) {
function linkManyToOne(target, next) {
//fix for bug in hasMany with referencesMany
var targetIds = [].concat(target[relation.keyTo]);
async.each(targetIds, function (targetId, next) {
async.each(targetIds, function(targetId, next) {
var obj = objIdMap[targetId.toString()];
if (!obj) return next();
obj.__cachedRelations[relationName].push(target);
@ -644,11 +644,11 @@ Inclusion.include = function (objects, include, options, cb) {
* @param callback
*/
function processPolymorphicType(modelType, callback) {
var typeFilter = {where: {}};
var typeFilter = { where: {}};
utils.mergeQuery(typeFilter, filter);
var targetIds = targetIdsByType[modelType];
typeFilter.where[relation.keyTo] = {
inq: uniq(targetIds)
inq: uniq(targetIds),
};
var Model = lookupModel(relation.modelFrom.dataSource.modelBuilder.
models, modelType);
@ -684,7 +684,7 @@ Inclusion.include = function (objects, include, options, cb) {
async.each(targets, linkOneToMany, next);
function linkOneToMany(target, next) {
var objList = targetObjsMap[target[relation.keyTo].toString()];
async.each(objList, function (obj, next) {
async.each(objList, function(obj, next) {
if (!obj) return next();
obj.__cachedRelations[relationName] = target;
processTargetObj(obj, next);
@ -720,7 +720,7 @@ Inclusion.include = function (objects, include, options, cb) {
obj.__cachedRelations[relationName] = null;
}
filter.where[relation.keyTo] = {
inq: uniq(sourceIds)
inq: uniq(sourceIds),
};
relation.applyScope(null, filter);
relation.modelTo.find(filter, options, targetFetchHandler);
@ -787,7 +787,7 @@ Inclusion.include = function (objects, include, options, cb) {
obj.__cachedRelations[relationName] = null;
}
filter.where[relation.keyTo] = {
inq: uniq(targetIds)
inq: uniq(targetIds),
};
relation.applyScope(null, filter);
relation.modelTo.find(filter, options, targetFetchHandler);
@ -815,7 +815,7 @@ Inclusion.include = function (objects, include, options, cb) {
function linkOneToMany(target, next) {
var targetId = target[relation.keyTo];
var objList = objTargetIdMap[targetId.toString()];
async.each(objList, function (obj, next) {
async.each(objList, function(obj, next) {
if (!obj) return next();
obj.__cachedRelations[relationName] = target;
processTargetObj(obj, next);
@ -838,7 +838,7 @@ Inclusion.include = function (objects, include, options, cb) {
* @param callback
*/
function includeEmbeds(callback) {
async.each(objs, function (obj, next) {
async.each(objs, function(obj, next) {
processTargetObj(obj, next);
}, 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);
} else {
related = inst[relationName].bind(inst, undefined);
}
related(options, function (err, result) {
related(options, function(err, result) {
if (err) {
return callback(err);
} else {

View File

@ -18,7 +18,7 @@ module.exports.KVMap = KVMap;
*/
function buildOneToOneIdentityMapWithOrigKeys(objs, idName) {
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 id = obj[idName];
kvMap.set(id, obj);
@ -28,7 +28,7 @@ function buildOneToOneIdentityMapWithOrigKeys(objs, idName) {
function buildOneToManyIdentityMapWithOrigKeys(objs, idName) {
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 id = obj[idName];
var value = kvMap.get(id) || [];
@ -48,7 +48,7 @@ function buildOneToManyIdentityMapWithOrigKeys(objs, idName) {
*/
function join(oneToOneIdMap, oneToManyIdMap, mergeF) {
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 obj = oneToOneIdMap.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}}
* @constructor
*/
function KVMap(){
function KVMap() {
var _originalKeyFieldName = 'originalKey';
var _valueKeyFieldName = 'value';
var _dict = {};
var keyToString = function(key){ return key.toString() };
var keyToString = function(key) { return key.toString(); };
var mapImpl = {
set: function(key, value){
set: function(key, value) {
var recordObj = {};
recordObj[_originalKeyFieldName] = key;
recordObj[_valueKeyFieldName] = value;
_dict[keyToString(key)] = recordObj;
return true;
},
get: function(key){
get: function(key) {
var storeObj = _dict[keyToString(key)];
if(storeObj) {
if (storeObj) {
return storeObj[_valueKeyFieldName];
} else {
return undefined;
}
},
remove: function(key){
remove: function(key) {
delete _dict[keyToString(key)];
return true;
},
@ -91,13 +91,13 @@ function KVMap(){
var result = _dict.hasOwnProperty(keyToString(key));
return result;
},
getKeys: function(){
getKeys: function() {
var result = [];
for(var key in _dict) {
for (var key in _dict) {
result.push(_dict[key][_originalKeyFieldName]);
}
return result;
}
},
};
return mapImpl;

View File

@ -62,6 +62,6 @@ module.exports = function getIntrospector(ModelBuilder) {
ModelBuilder.introspect = introspectType;
return introspectType;
}
};

View File

@ -10,16 +10,16 @@ var util = require('util');
* @param newClass
* @param baseClass
*/
exports.inherits = function (newClass, baseClass, options) {
exports.inherits = function(newClass, baseClass, options) {
util.inherits(newClass, baseClass);
options = options || {
staticProperties: true,
override: false
override: false,
};
if (options.staticProperties) {
Object.keys(baseClass).forEach(function (classProp) {
Object.keys(baseClass).forEach(function(classProp) {
if (classProp !== 'super_' && (!newClass.hasOwnProperty(classProp)
|| options.override)) {
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 options
*/
exports.mixin = function (newClass, mixinClass, options) {
exports.mixin = function(newClass, mixinClass, options) {
if (Array.isArray(newClass._mixins)) {
if (newClass._mixins.indexOf(mixinClass) !== -1) {
return;
@ -49,7 +49,7 @@ exports.mixin = function (newClass, mixinClass, options) {
staticProperties: true,
instanceProperties: true,
override: false,
proxyFunctions: false
proxyFunctions: false,
};
if (options.staticProperties === undefined) {
@ -72,7 +72,7 @@ exports.mixin = function (newClass, mixinClass, options) {
};
function mixInto(sourceScope, targetScope, options) {
Object.keys(sourceScope).forEach(function (propertyName) {
Object.keys(sourceScope).forEach(function(propertyName) {
var targetPropertyExists = targetScope.hasOwnProperty(propertyName);
var sourceProperty = Object.getOwnPropertyDescriptor(sourceScope, propertyName);
var targetProperty = targetPropertyExists && Object.getOwnPropertyDescriptor(targetScope, propertyName);

View File

@ -34,7 +34,7 @@ function List(items, itemType, parent) {
throw err;
}
if(!itemType) {
if (!itemType) {
itemType = items[0] && items[0].constructor;
}
@ -42,25 +42,25 @@ function List(items, itemType, parent) {
itemType = itemType[0];
}
if(itemType === Array) {
if (itemType === Array) {
itemType = Any;
}
Object.defineProperty(arr, 'itemType', {
writable: true,
enumerable: false,
value: itemType
value: itemType,
});
if (parent) {
Object.defineProperty(arr, 'parent', {
writable: true,
enumerable: false,
value: parent
value: parent,
});
}
items.forEach(function (item, i) {
items.forEach(function(item, i) {
if (itemType && !(item instanceof itemType)) {
arr[i] = itemType(item);
} else {
@ -75,15 +75,15 @@ util.inherits(List, Array);
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);
_push.call(this, item);
return item;
};
List.prototype.toObject = function (onlySchema, removeHidden, removeProtected) {
List.prototype.toObject = function(onlySchema, removeHidden, removeProtected) {
var items = [];
this.forEach(function (item) {
this.forEach(function(item) {
if (item && typeof item === 'object' && item.toObject) {
items.push(item.toObject(onlySchema, removeHidden, removeProtected));
} else {
@ -93,11 +93,11 @@ List.prototype.toObject = function (onlySchema, removeHidden, removeProtected) {
return items;
};
List.prototype.toJSON = function () {
List.prototype.toJSON = function() {
return this.toObject(true);
};
List.prototype.toString = function () {
List.prototype.toString = function() {
return JSON.stringify(this.toJSON());
};

View File

@ -40,7 +40,7 @@ MixinProvider.prototype.applyMixin = function applyMixin(modelClass, name, optio
} else {
// Try model name
var model = this.modelBuilder.getModel(name);
if(model) {
if (model) {
debug('Mixin is resolved to a model: %s', name);
modelClass.mixin(model, options);
} else {
@ -62,7 +62,7 @@ MixinProvider.prototype.define = function defineMixin(name, mixin) {
debug('Defining mixin: %s', name);
}
if (isModelClass(mixin)) {
this.mixins[name] = function (Model, options) {
this.mixins[name] = function(Model, options) {
Model.mixin(mixin, options);
};
} else if (typeof mixin === 'function') {

View File

@ -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.
* @returns {*} The model class
*/
ModelBuilder.prototype.getModel = function (name, forceCreate) {
ModelBuilder.prototype.getModel = function(name, forceCreate) {
var model = this.models[name];
if (!model && forceCreate) {
model = this.define(name, {}, {unresolved: true});
model = this.define(name, {}, { unresolved: true });
}
return model;
};
@ -81,7 +81,7 @@ ModelBuilder.prototype.getModel = function (name, forceCreate) {
* @param {String} name The model name
* @returns {ModelDefinition} The model definition
*/
ModelBuilder.prototype.getModelDefinition = function (name) {
ModelBuilder.prototype.getModelDefinition = function(name) {
return this.definitions[name];
};
@ -214,7 +214,7 @@ ModelBuilder.prototype.define = function defineClass(className, properties, sett
// Return the unresolved model
if (settings.unresolved) {
ModelClass.settings = {unresolved: true};
ModelClass.settings = { unresolved: true };
return ModelClass;
}
@ -241,7 +241,7 @@ ModelBuilder.prototype.define = function defineClass(className, properties, sett
// Load and inject the model classes
if (settings.models) {
Object.keys(settings.models).forEach(function (m) {
Object.keys(settings.models).forEach(function(m) {
var model = settings.models[m];
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];
if (idProp !== 'id') {
Object.defineProperty(ModelClass.prototype, 'id', {
get: function () {
get: function() {
var idProp = ModelClass.definition.idNames()[0];
return this.__data[idProp];
},
configurable: true,
enumerable: false
enumerable: false,
});
}
} else {
// Now the id property is an object that consists of multiple keys
Object.defineProperty(ModelClass.prototype, 'id', {
get: function () {
get: function() {
var compositeId = {};
var idNames = ModelClass.definition.idNames();
for (var i = 0, p; i < idNames.length; i++) {
@ -318,12 +318,12 @@ ModelBuilder.prototype.define = function defineClass(className, properties, sett
return compositeId;
},
configurable: true,
enumerable: false
enumerable: false,
});
}
// A function to loop through the properties
ModelClass.forEachProperty = function (cb) {
ModelClass.forEachProperty = function(cb) {
var props = ModelClass.definition.properties;
var keys = Object.keys(props);
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
ModelClass.attachTo = function (dataSource) {
ModelClass.attachTo = function(dataSource) {
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.
*
*/
ModelClass.extend = function (className, subclassProperties, subclassSettings) {
ModelClass.extend = function(className, subclassProperties, subclassSettings) {
var properties = ModelClass.definition.properties;
var settings = ModelClass.definition.settings;
@ -418,7 +418,7 @@ ModelBuilder.prototype.define = function defineClass(className, properties, sett
* Register a property for the model class
* @param {String} propertyName Name of the property.
*/
ModelClass.registerProperty = function (propertyName) {
ModelClass.registerProperty = function(propertyName) {
var properties = modelDefinition.build();
var prop = properties[propertyName];
var DataType = prop.type;
@ -432,14 +432,14 @@ ModelBuilder.prototype.define = function defineClass(className, properties, sett
}
Object.defineProperty(ModelClass.prototype, propertyName, {
get: function () {
get: function() {
if (ModelClass.getter[propertyName]) {
return ModelClass.getter[propertyName].call(this); // Try getter first
} else {
return this.__data && this.__data[propertyName]; // Try __data
}
},
set: function (value) {
set: function(value) {
var DataType = ModelClass.definition.properties[propertyName].type;
if (Array.isArray(DataType) || DataType === Array) {
DataType = List;
@ -474,23 +474,23 @@ ModelBuilder.prototype.define = function defineClass(className, properties, sett
}
},
configurable: true,
enumerable: true
enumerable: true,
});
// FIXME: [rfeng] Do we need to keep the raw data?
// Use $ as the prefix to avoid conflicts with properties such as _id
Object.defineProperty(ModelClass.prototype, '$' + propertyName, {
get: function () {
get: function() {
return this.__data && this.__data[propertyName];
},
set: function (value) {
set: function(value) {
if (!this.__data) {
this.__data = {};
}
this.__data[propertyName] = value;
},
configurable: true,
enumerable: false
enumerable: false,
});
};
@ -563,7 +563,7 @@ function BooleanType(arg) {
* @param {String} propertyName Name of property
* @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.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 {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 keys = Object.keys(props);
for (var i = 0; i < keys.length; i++) {
@ -638,7 +638,7 @@ ModelBuilder.prototype.copyModel = function copyModel(Master) {
modelBuilder.models[className] = Slave;
modelBuilder.definitions[className] = {
properties: md.properties,
settings: md.settings
settings: md.settings,
};
}
@ -653,14 +653,14 @@ function hiddenProperty(where, property, value) {
writable: true,
enumerable: false,
configurable: true,
value: value
value: value,
});
}
/**
* Get the schema name
*/
ModelBuilder.prototype.getSchemaName = function (name) {
ModelBuilder.prototype.getSchemaName = function(name) {
if (name) {
return name;
}
@ -677,7 +677,7 @@ ModelBuilder.prototype.getSchemaName = function (name) {
* Returns {Function} if the type is resolved
* @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) {
return type;
}
@ -697,7 +697,7 @@ ModelBuilder.prototype.resolveType = function (type) {
return schemaType;
} else {
// 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;
}
} else if (type.constructor.name === 'Object') {
@ -706,7 +706,7 @@ ModelBuilder.prototype.resolveType = function (type) {
return this.resolveType(type.type);
} else {
return this.define(this.getSchemaName(null),
type, {anonymous: true, idInjection: false});
type, { anonymous: true, idInjection: false });
}
} else if ('function' === typeof type) {
return type;
@ -726,7 +726,7 @@ ModelBuilder.prototype.resolveType = function (type) {
* @param {*} schemas The schemas
* @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 = {};
// 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(),
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);
schemas[s].name = name;
var model;
if(typeof createModel === 'function') {
if (typeof createModel === 'function') {
model = createModel(schemas[s].name, schemas[s].properties, schemas[s].options);
} else {
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];
if (sourceModel && targetModel) {
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
* @returns {}
*/
ModelBuilder.prototype.buildModelFromInstance = function (name, json, options) {
ModelBuilder.prototype.buildModelFromInstance = function(name, json, options) {
// Introspect the JSON document to generate a schema
var schema = introspect(json);

View File

@ -58,7 +58,7 @@ require('./types')(ModelDefinition);
* Return table name for specified `modelName`
* @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;
if (settings[connectorType]) {
return settings[connectorType].table || settings[connectorType].tableName || this.name;
@ -73,7 +73,7 @@ ModelDefinition.prototype.tableName = function (connectorType) {
* @param propertyName The property name
* @returns {String} columnName
*/
ModelDefinition.prototype.columnName = function (connectorType, propertyName) {
ModelDefinition.prototype.columnName = function(connectorType, propertyName) {
if (!propertyName) {
return propertyName;
}
@ -92,7 +92,7 @@ ModelDefinition.prototype.columnName = function (connectorType, propertyName) {
* @param propertyName The property name
* @returns {Object} column metadata
*/
ModelDefinition.prototype.columnMetadata = function (connectorType, propertyName) {
ModelDefinition.prototype.columnMetadata = function(connectorType, propertyName) {
if (!propertyName) {
return propertyName;
}
@ -110,7 +110,7 @@ ModelDefinition.prototype.columnMetadata = function (connectorType, propertyName
* @param {String} connectorType The connector type, such as 'oracle' or 'mongodb'
* @returns {String[]} column names
*/
ModelDefinition.prototype.columnNames = function (connectorType) {
ModelDefinition.prototype.columnNames = function(connectorType) {
this.build();
var props = this.properties;
var cols = [];
@ -128,7 +128,7 @@ ModelDefinition.prototype.columnNames = function (connectorType) {
* Find the ID properties sorted by the index
* @returns {Object[]} property name/index for IDs
*/
ModelDefinition.prototype.ids = function () {
ModelDefinition.prototype.ids = function() {
if (this._ids) {
return this._ids;
}
@ -143,9 +143,9 @@ ModelDefinition.prototype.ids = function () {
if (typeof id !== 'number') {
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;
});
this._ids = ids;
@ -157,7 +157,7 @@ ModelDefinition.prototype.ids = function () {
* @param {String} modelName The model name
* @returns {String} columnName for ID
*/
ModelDefinition.prototype.idColumnName = function (connectorType) {
ModelDefinition.prototype.idColumnName = function(connectorType) {
return this.columnName(connectorType, this.idName());
};
@ -165,7 +165,7 @@ ModelDefinition.prototype.idColumnName = function (connectorType) {
* Find the ID property name
* @returns {String} property name for ID
*/
ModelDefinition.prototype.idName = function () {
ModelDefinition.prototype.idName = function() {
var id = this.ids()[0];
if (this.properties.id && this.properties.id.id) {
return 'id';
@ -178,9 +178,9 @@ ModelDefinition.prototype.idName = function () {
* Find the ID property names sorted by the index
* @returns {String[]} property names for IDs
*/
ModelDefinition.prototype.idNames = function () {
ModelDefinition.prototype.idNames = function() {
var ids = this.ids();
var names = ids.map(function (id) {
var names = ids.map(function(id) {
return id.name;
});
return names;
@ -190,7 +190,7 @@ ModelDefinition.prototype.idNames = function () {
*
* @returns {{}}
*/
ModelDefinition.prototype.indexes = function () {
ModelDefinition.prototype.indexes = function() {
this.build();
var indexes = {};
if (this.settings.indexes) {
@ -210,7 +210,7 @@ ModelDefinition.prototype.indexes = function () {
* Build a model definition
* @param {Boolean} force Forcing rebuild
*/
ModelDefinition.prototype.build = function (forceRebuild) {
ModelDefinition.prototype.build = function(forceRebuild) {
if (forceRebuild) {
this.properties = null;
this.relations = [];
@ -229,11 +229,11 @@ ModelDefinition.prototype.build = function (forceRebuild) {
source: this.name,
target: type,
type: Array.isArray(prop) ? 'hasMany' : 'belongsTo',
as: p
as: p,
});
} else {
var typeDef = {
type: type
type: type,
};
if (typeof prop === 'object' && prop !== null) {
for (var a in prop) {
@ -254,7 +254,7 @@ ModelDefinition.prototype.build = function (forceRebuild) {
* @param {String} propertyName The property name
* @param {Object} propertyDefinition The property definition
*/
ModelDefinition.prototype.defineProperty = function (propertyName, propertyDefinition) {
ModelDefinition.prototype.defineProperty = function(propertyName, propertyDefinition) {
this.rawProperties[propertyName] = propertyDefinition;
this.build(true);
};
@ -266,7 +266,7 @@ function isModelClass(cls) {
return cls.prototype instanceof ModelBaseClass;
}
ModelDefinition.prototype.toJSON = function (forceRebuild) {
ModelDefinition.prototype.toJSON = function(forceRebuild) {
if (forceRebuild) {
this.json = null;
}
@ -276,11 +276,11 @@ ModelDefinition.prototype.toJSON = function (forceRebuild) {
var json = {
name: this.name,
properties: {},
settings: this.settings
settings: this.settings,
};
this.build(forceRebuild);
var mapper = function (val) {
var mapper = function(val) {
if (val === undefined || val === null) {
return val;
}

View File

@ -31,7 +31,7 @@ var BASE_TYPES = {
'Number': true,
'Date': true,
'Text': true,
'ObjectID': true
'ObjectID': true,
};
/**
@ -44,7 +44,7 @@ var BASE_TYPES = {
*/
function ModelBaseClass(data, options) {
options = options || {};
if(!('applySetters' in options)) {
if (!('applySetters' in options)) {
// Default to true
options.applySetters = true;
}
@ -64,11 +64,11 @@ function ModelBaseClass(data, options) {
* @property {Boolean} persisted Whether the instance has been persisted
* @private
*/
ModelBaseClass.prototype._initProperties = function (data, options) {
ModelBaseClass.prototype._initProperties = function(data, options) {
var self = this;
var ctor = this.constructor;
if(data instanceof ctor) {
if (data instanceof ctor) {
// Convert the data to be plain object to avoid pollutions
data = data.toObject(false);
}
@ -84,7 +84,7 @@ ModelBaseClass.prototype._initProperties = function (data, options) {
var applyDefaultValues = options.applyDefaultValues;
var strict = options.strict;
if(strict === undefined) {
if (strict === undefined) {
strict = ctor.definition.settings.strict;
}
@ -99,14 +99,14 @@ ModelBaseClass.prototype._initProperties = function (data, options) {
writable: true,
enumerable: false,
configurable: true,
value: {}
value: {},
},
__data: {
writable: true,
enumerable: false,
configurable: true,
value: {}
value: {},
},
// Instance level data source
@ -114,7 +114,7 @@ ModelBaseClass.prototype._initProperties = function (data, options) {
writable: true,
enumerable: false,
configurable: true,
value: options.dataSource
value: options.dataSource,
},
// Instance level strict mode
@ -122,14 +122,14 @@ ModelBaseClass.prototype._initProperties = function (data, options) {
writable: true,
enumerable: false,
configurable: true,
value: strict
value: strict,
},
__persisted: {
writable: true,
enumerable: false,
configurable: true,
value: false
value: false,
},
});
@ -138,7 +138,7 @@ ModelBaseClass.prototype._initProperties = function (data, options) {
writable: true,
enumerable: false,
configrable: true,
value: []
value: [],
});
}
} else {
@ -320,13 +320,13 @@ ModelBaseClass.prototype._initProperties = function (data, options) {
if (type.prototype instanceof ModelBaseClass) {
if (!(self.__data[p] instanceof type)
&& typeof self.__data[p] === 'object'
&& self.__data[p] !== null ) {
&& self.__data[p] !== null) {
self.__data[p] = new type(self.__data[p]);
}
} else if (type.name === 'Array' || Array.isArray(type)) {
if (!(self.__data[p] instanceof List)
&& self.__data[p] !== undefined
&& self.__data[p] !== null ) {
&& self.__data[p] !== null) {
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 {Object} params Various property configuration
*/
ModelBaseClass.defineProperty = function (prop, params) {
if(this.dataSource) {
ModelBaseClass.defineProperty = function(prop, params) {
if (this.dataSource) {
this.dataSource.defineProperty(this.modelName, prop, params);
} else {
this.modelBuilder.defineProperty(this.modelName, prop, params);
}
};
ModelBaseClass.getPropertyType = function (propName) {
ModelBaseClass.getPropertyType = function(propName) {
var prop = this.definition.properties[propName];
if (!prop) {
// The property is not part of the definition
@ -361,7 +361,7 @@ ModelBaseClass.getPropertyType = function (propName) {
return prop.type.name;
};
ModelBaseClass.prototype.getPropertyType = function (propName) {
ModelBaseClass.prototype.getPropertyType = function(propName) {
return this.constructor.getPropertyType(propName);
};
@ -369,7 +369,7 @@ ModelBaseClass.prototype.getPropertyType = function (propName) {
* Return string representation of class
* This overrides the default `toString()` method
*/
ModelBaseClass.toString = function () {
ModelBaseClass.toString = function() {
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.
*/
ModelBaseClass.prototype.toObject = function (onlySchema, removeHidden, removeProtected) {
ModelBaseClass.prototype.toObject = function(onlySchema, removeHidden, removeProtected) {
if (onlySchema === undefined) {
onlySchema = true;
}
@ -504,7 +504,7 @@ ModelBaseClass.prototype.toObject = function (onlySchema, removeHidden, removePr
return data;
};
ModelBaseClass.isProtectedProperty = function (propertyName) {
ModelBaseClass.isProtectedProperty = function(propertyName) {
var Model = this;
var settings = Model.definition && Model.definition.settings;
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 settings = Model.definition && Model.definition.settings;
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);
};
ModelBaseClass.prototype.fromObject = function (obj) {
ModelBaseClass.prototype.fromObject = function(obj) {
for (var key in obj) {
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
* initial state.
*/
ModelBaseClass.prototype.reset = function () {
ModelBaseClass.prototype.reset = function() {
var obj = this;
for (var k in obj) {
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[0] === 11 && versionParts[1] >= 14);
ModelBaseClass.prototype.inspect = function (depth) {
ModelBaseClass.prototype.inspect = function(depth) {
if (INSPECT_SUPPORTS_OBJECT_RETVAL)
return this.__data;
return this.__data;
// Workaround for older versions
// See also https://github.com/joyent/node/commit/66280de133
return util.inspect(this.__data, {
showHidden: false,
depth: depth,
colors: false
colors: false,
});
};
ModelBaseClass.mixin = function (anotherClass, options) {
ModelBaseClass.mixin = function(anotherClass, options) {
if (typeof anotherClass === 'string') {
this.modelBuilder.mixins.applyMixin(this, anotherClass, options);
} else {
@ -608,15 +608,15 @@ ModelBaseClass.mixin = function (anotherClass, options) {
}
};
ModelBaseClass.prototype.getDataSource = function () {
ModelBaseClass.prototype.getDataSource = function() {
return this.__dataSource || this.constructor.dataSource;
};
ModelBaseClass.getDataSource = function () {
ModelBaseClass.getDataSource = function() {
return this.dataSource;
};
ModelBaseClass.prototype.setStrict = function (strict) {
ModelBaseClass.prototype.setStrict = function(strict) {
this.__strict = strict;
};

View File

@ -108,7 +108,7 @@ ObserverMixin.notifyObserversOf = function(operation, context, callback) {
);
}
},
function(err) { callback(err, context) }
function(err) { callback(err, context); }
);
});
return callback.promise;

File diff suppressed because it is too large Load Diff

View File

@ -21,12 +21,12 @@ function RelationMixin() {
/**
* Define a "one to many" relationship by specifying the model name
*
*
* Examples:
* ```
* User.hasMany(Post, {as: 'posts', foreignKey: 'authorId'});
* ```
*
*
* ```
* Book.hasMany(Chapter);
* ```
@ -39,24 +39,24 @@ function RelationMixin() {
*
* ```js
* Book.create(function(err, book) {
*
*
* // Create a chapter instance ready to be saved in the data source.
* var chapter = book.chapters.build({name: 'Chapter 1'});
*
*
* // Save the new chapter
* chapter.save();
*
*
* // 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.
* book.chapters.create({name: 'Chapter 2'}, function(err, savedChapter) {
* // this callback is optional
* });
*
* // Query chapters for the book
* book.chapters(function(err, chapters) { // all chapters with bookId = book.id
*
* // Query chapters for the book
* book.chapters(function(err, chapters) { // all chapters with bookId = book.id
* console.log(chapters);
* });
*
*
* book.chapters({where: {name: 'test'}, function(err, chapters) {
* // All chapters with bookId = book.id and name = 'test'
* console.log(chapters);
@ -94,10 +94,10 @@ RelationMixin.hasMany = function hasMany(modelTo, params) {
* ```
* Set the author to be the given user:
* ```
* post.author(user)
* post.author(user)
* ```
* Examples:
*
*
* Suppose the model Post has a *belongsTo* relationship with User (the author of the post). You could declare it this way:
* ```js
* Post.belongsTo(User, {as: 'author', foreignKey: 'userId'});
@ -123,9 +123,9 @@ RelationMixin.hasMany = function hasMany(modelTo, params) {
* @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} foreignKey Name of foreign key property.
*
*
*/
RelationMixin.belongsTo = function (modelTo, params) {
RelationMixin.belongsTo = function(modelTo, params) {
return RelationDefinition.belongsTo(this, modelTo, params);
};
@ -150,9 +150,9 @@ RelationMixin.belongsTo = function (modelTo, params) {
* ```
* 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.
* the relation
* @options {Object} params Configuration parameters; see below.

View File

@ -83,9 +83,9 @@ ScopeDefinition.prototype.related = function(receiver, scopeParams, condOrRefres
if (!self.__cachedRelations || self.__cachedRelations[name] === undefined
|| actualRefresh) {
// 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);
targetModel.find(params, options, function (err, data) {
targetModel.find(params, options, function(err, data) {
if (!err && saveOnCache) {
defineCachedRelations(self);
self.__cachedRelations[name] = data;
@ -97,7 +97,7 @@ ScopeDefinition.prototype.related = function(receiver, scopeParams, condOrRefres
cb(null, self.__cachedRelations[name]);
}
return cb.promise;
}
};
/**
* Define a scope method
@ -106,7 +106,7 @@ ScopeDefinition.prototype.related = function(receiver, scopeParams, condOrRefres
*/
ScopeDefinition.prototype.defineMethod = function(name, fn) {
return this.methods[name] = fn;
}
};
/**
* Define a scope to the class
@ -143,10 +143,10 @@ function defineScope(cls, targetClass, name, params, methods, options) {
name: name,
params: params,
methods: methods,
options: options
options: options,
});
if(isStatic) {
if (isStatic) {
cls.scopes = cls.scopes || {};
cls.scopes[name] = definition;
} else {
@ -169,7 +169,7 @@ function defineScope(cls, targetClass, name, params, methods, options) {
* user.accounts.create(act, cb).
*
*/
get: function () {
get: function() {
var targetModel = definition.targetModel(this);
var self = this;
@ -192,23 +192,23 @@ function defineScope(cls, targetClass, name, params, methods, options) {
cb = options;
options = {};
}
options = options || {}
options = options || {};
// Check if there is a through model
// see https://github.com/strongloop/loopback/issues/1076
if (f._scope.collect &&
condOrRefresh !== null && typeof condOrRefresh === 'object') {
//extract the paging filters to the through model
['limit','offset','skip','order'].forEach(function(pagerFilter){
if(typeof(condOrRefresh[pagerFilter]) !== 'undefined'){
f._scope[pagerFilter] = condOrRefresh[pagerFilter];
delete condOrRefresh[pagerFilter];
}
['limit', 'offset', 'skip', 'order'].forEach(function(pagerFilter) {
if (typeof(condOrRefresh[pagerFilter]) !== 'undefined') {
f._scope[pagerFilter] = condOrRefresh[pagerFilter];
delete condOrRefresh[pagerFilter];
}
});
// Adjust the include so that the condition will be applied to
// the target model
f._scope.include = {
relation: f._scope.collect,
scope: condOrRefresh
scope: condOrRefresh,
};
condOrRefresh = {};
}
@ -237,9 +237,9 @@ function defineScope(cls, targetClass, name, params, methods, options) {
cb = options;
options = {};
}
options = options || {}
options = options || {};
return definition.related(self, f._scope, condOrRefresh, options, cb);
}
};
f.build = build;
f.create = create;
@ -259,21 +259,21 @@ function defineScope(cls, targetClass, name, params, methods, options) {
// Station.scope('active', {where: {isActive: true}});
// Station.scope('subway', {where: {isUndeground: true}});
// Station.active.subway(cb);
Object.keys(targetClass._scopeMeta).forEach(function (name) {
Object.keys(targetClass._scopeMeta).forEach(function(name) {
Object.defineProperty(f, name, {
enumerable: false,
get: function () {
get: function() {
mergeQuery(f._scope, targetModel._scopeMeta[name]);
return f;
}
},
});
}.bind(self));
return f;
}
},
});
// Wrap the property into a function for remoting
var fn = function () {
var fn = function() {
// primaryObject.scopeName, such as user.accounts
var f = this[name];
// 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;
var fn_create = function () {
var fn_create = function() {
var f = this[name].create;
f.apply(this[name], arguments);
};
cls['__create__' + name] = fn_create;
var fn_delete = function () {
var fn_delete = function() {
var f = this[name].destroyAll;
f.apply(this[name], arguments);
};
cls['__delete__' + name] = fn_delete;
var fn_update = function () {
var fn_update = function() {
var f = this[name].updateAll;
f.apply(this[name], arguments);
};
cls['__update__' + name] = fn_update;
var fn_findById = function (cb) {
var fn_findById = function(cb) {
var f = this[name].findById;
f.apply(this[name], arguments);
};
cls['__findById__' + name] = fn_findById;
var fn_findOne = function (cb) {
var fn_findOne = function(cb) {
var f = this[name].findOne;
f.apply(this[name], arguments);
};
cls['__findOne__' + name] = fn_findOne;
var fn_count = function (cb) {
var fn_count = function(cb) {
var f = this[name].count;
f.apply(this[name], arguments);
};
@ -369,7 +369,7 @@ function defineScope(cls, targetClass, name, params, methods, options) {
var targetModel = definition.targetModel(this._receiver);
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);
}
@ -389,7 +389,7 @@ function defineScope(cls, targetClass, name, params, methods, options) {
options = options || {};
var targetModel = definition.targetModel(this._receiver);
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);
}
@ -412,12 +412,12 @@ function defineScope(cls, targetClass, name, params, methods, options) {
}
}
}
options = options || {};
filter = filter || {};
var targetModel = definition.targetModel(this._receiver);
var idName = targetModel.definition.idName();
var query = {where: {}};
var query = { where: {}};
query.where[idName] = id;
query = mergeQuery(query, filter);
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 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);
}

View File

@ -78,7 +78,7 @@ TransactionMixin.beginTransaction = function(options, cb) {
setTimeout(function() {
var context = {
transaction: transaction,
operation: 'timeout'
operation: 'timeout',
};
transaction.notifyObserversOf('timeout', context, function(err) {
if (!err) {
@ -121,7 +121,7 @@ if (Transaction) {
}
var context = {
transaction: self,
operation: 'commit'
operation: 'commit',
};
function work(done) {
@ -155,7 +155,7 @@ if (Transaction) {
}
var context = {
transaction: self,
operation: 'rollback'
operation: 'rollback',
};
function work(done) {

View File

@ -14,7 +14,7 @@ Types.Text = function Text(value) {
this.value = value;
}; // Text type
Types.Text.prototype.toObject = Types.Text.prototype.toJSON = function () {
Types.Text.prototype.toObject = Types.Text.prototype.toJSON = function() {
return this.value;
};
@ -24,7 +24,7 @@ Types.JSON = function JSON(value) {
}
this.value = value;
}; // JSON Object
Types.JSON.prototype.toObject = Types.JSON.prototype.toJSON = function () {
Types.JSON.prototype.toObject = Types.JSON.prototype.toJSON = function() {
return this.value;
};
@ -34,20 +34,20 @@ Types.Any = function Any(value) {
}
this.value = value;
}; // Any Type
Types.Any.prototype.toObject = Types.Any.prototype.toJSON = function () {
Types.Any.prototype.toObject = Types.Any.prototype.toJSON = function() {
return this.value;
};
module.exports = function (modelTypes) {
module.exports = function(modelTypes) {
var GeoPoint = require('./geo').GeoPoint;
for(var t in Types) {
for (var t in Types) {
modelTypes[t] = Types[t];
}
modelTypes.schemaTypes = {};
modelTypes.registerType = function (type, names) {
modelTypes.registerType = function(type, names) {
names = names || [];
names = names.concat([type.name]);
for (var n = 0; n < names.length; n++) {
@ -69,4 +69,4 @@ module.exports = function (modelTypes) {
modelTypes.registerType(Object);
};
module.exports.Types = Types;
module.exports.Types = Types;

View File

@ -135,9 +135,9 @@ function convertToArray(include) {
if (typeof includeEntry === 'string') {
var obj = {};
obj[includeEntry] = true;
normalized.push(obj)
normalized.push(obj);
}
else{
else {
normalized.push(includeEntry);
}
}
@ -163,7 +163,7 @@ function mergeQuery(base, update, spec) {
if (update.where && Object.keys(update.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 {
base.where = update.where;
}
@ -174,7 +174,7 @@ function mergeQuery(base, update, spec) {
if (!base.include) {
base.include = update.include;
} else {
if (spec.nestedInclude === true){
if (spec.nestedInclude === true) {
//specify nestedInclude=true to force nesting of inclusions on scoped
//queries. e.g. In physician.patients.getAsync({include: 'address'}),
//inclusion should be on patient model, not on physician model.
@ -182,7 +182,7 @@ function mergeQuery(base, update, spec) {
base.include = {};
base.include[update.include] = saved;
}
else{
else {
//default behaviour of inclusion merge - merge inclusions at the same
//level. - https://github.com/strongloop/loopback-datasource-juggler/pull/569#issuecomment-95310874
base.include = mergeIncludes(base.include, update.include);
@ -283,7 +283,7 @@ function fieldsToArray(fields, properties, excludeUnknown) {
function selectFields(fields) {
// map function
return function (obj) {
return function(obj) {
var result = {};
var key;
@ -308,7 +308,7 @@ function removeUndefined(query, handleUndefined) {
}
// WARNING: [rfeng] Use map() will cause mongodb to produce invalid BSON
// as traverse doesn't transform the ObjectId correctly
return traverse(query).forEach(function (x) {
return traverse(query).forEach(function(x) {
if (x === undefined) {
switch (handleUndefined) {
case 'nullify':
@ -430,7 +430,7 @@ function defineCachedRelations(obj) {
writable: true,
enumerable: false,
configurable: true,
value: {}
value: {},
});
}
}
@ -449,7 +449,7 @@ function isPlainObject(obj) {
function sortObjectsByIds(idName, ids, objects, strict) {
ids = ids.map(function(id) {
return (typeof id === 'object') ? String(id) : id;
return (typeof id === 'object') ? String(id) : id;
});
var indexOf = function(x) {
@ -485,15 +485,15 @@ function createPromiseCallback() {
var cb;
if (!global.Promise) {
cb = function(){};
cb = function() {};
cb.promise = {};
Object.defineProperty(cb.promise, 'then', { get: throwPromiseNotDefined });
Object.defineProperty(cb.promise, 'catch', { get: throwPromiseNotDefined });
return cb;
}
var promise = new Promise(function (resolve, reject) {
cb = function (err, data) {
var promise = new Promise(function(resolve, reject) {
cb = function(err, data) {
if (err) return reject(err);
return resolve(data);
};

View File

@ -207,7 +207,7 @@ Validatable.validate = getConfigurator('custom');
* @options {Object} Options See below
* @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.
@ -231,7 +231,7 @@ Validatable.validateAsync = getConfigurator('custom', {async: true});
* @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".
*/
Validatable.validatesUniquenessOf = getConfigurator('uniqueness', {async: true});
Validatable.validatesUniquenessOf = getConfigurator('uniqueness', { async: true });
// implementation of validators
@ -292,7 +292,7 @@ function validateInclusion(attr, conf, err) {
if (nullCheck.call(this, attr, conf, err)) return;
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 (~conf.in.indexOf(this[attr])) {
err()
err();
}
}
@ -336,7 +336,7 @@ function validateUniqueness(attr, conf, err, done) {
if (blank(this[attr])) {
return process.nextTick(done);
}
var cond = {where: {}};
var cond = { where: {}};
cond.where[attr] = this[attr];
if (conf && conf.scopedTo) {
@ -349,7 +349,7 @@ function validateUniqueness(attr, conf, err, done) {
var idName = this.constructor.definition.idName();
var isNewRecord = this.isNewRecord();
this.constructor.find(cond, function (error, found) {
this.constructor.find(cond, function(error, found) {
if (error) {
err(error);
} else if (found.length > 1) {
@ -372,11 +372,11 @@ var validators = {
exclusion: validateExclusion,
format: validateFormat,
custom: validateCustom,
uniqueness: validateUniqueness
uniqueness: validateUniqueness,
};
function getConfigurator(name, opts) {
return function () {
return function() {
var args = Array.prototype.slice.call(arguments);
args[1] = args[1] || {};
configure(this, name, args, opts);
@ -415,7 +415,7 @@ function getConfigurator(name, opts) {
* @param {Function} callback called with (valid)
* @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 validations = this.constructor.validations;
@ -426,8 +426,8 @@ Validatable.prototype.isValid = function (callback, data) {
if (typeof validations !== 'object' && !reportDiscardedProperties) {
cleanErrors(this);
if (callback) {
this.trigger('validate', function (validationsDone) {
validationsDone.call(inst, function () {
this.trigger('validate', function(validationsDone) {
validationsDone.call(inst, function() {
callback(valid);
});
}, data, callback);
@ -438,10 +438,10 @@ Validatable.prototype.isValid = function (callback, data) {
Object.defineProperty(this, 'errors', {
enumerable: false,
configurable: true,
value: new Errors
value: new Errors,
});
this.trigger('validate', function (validationsDone) {
this.trigger('validate', function(validationsDone) {
var inst = this,
asyncFail = false;
@ -453,7 +453,7 @@ Validatable.prototype.isValid = function (callback, data) {
if (v.options && v.options.async) {
async = true;
wait += 1;
process.nextTick(function () {
process.nextTick(function() {
validationFailed(inst, attr, v, done);
});
} else {
@ -475,7 +475,7 @@ Validatable.prototype.isValid = function (callback, data) {
}
if (!async) {
validationsDone.call(inst, function () {
validationsDone.call(inst, function() {
if (valid) cleanErrors(inst);
if (callback) {
callback(valid);
@ -486,7 +486,7 @@ Validatable.prototype.isValid = function (callback, data) {
function done(fail) {
asyncFail = asyncFail || fail;
if (--wait === 0) {
validationsDone.call(inst, function () {
validationsDone.call(inst, function() {
if (valid && !asyncFail) cleanErrors(inst);
if (callback) {
callback(valid && !asyncFail);
@ -511,7 +511,7 @@ function cleanErrors(inst) {
Object.defineProperty(inst, 'errors', {
enumerable: false,
configurable: true,
value: false
value: false,
});
}
@ -559,7 +559,7 @@ function validationFailed(inst, attr, conf, cb) {
fail = true;
});
if (cb) {
validatorArguments.push(function () {
validatorArguments.push(function() {
cb(fail);
});
}
@ -593,19 +593,19 @@ var defaultMessages = {
length: {
min: 'too short',
max: 'too long',
is: 'length is wrong'
is: 'length is wrong',
},
common: {
blank: 'is blank',
'null': 'is null'
'null': 'is null',
},
numericality: {
'int': 'is not an integer',
'number': 'is not a number'
'number': 'is not a number',
},
inclusion: 'is not included in the list',
exclusion: 'is reserved',
uniqueness: 'is not unique'
uniqueness: 'is not unique',
};
function nullCheck(attr, conf, err) {
@ -647,7 +647,7 @@ function configure(cls, validation, args, opts) {
writable: true,
configurable: true,
enumerable: false,
value: {}
value: {},
});
}
args = [].slice.call(args);
@ -661,7 +661,7 @@ function configure(cls, validation, args, opts) {
conf.customValidator = args.pop();
}
conf.validation = validation;
args.forEach(function (attr) {
args.forEach(function(attr) {
if (typeof attr === 'string') {
var validation = extend({}, conf);
validation.options = opts || {};
@ -675,11 +675,11 @@ function Errors() {
Object.defineProperty(this, 'codes', {
enumerable: false,
configurable: true,
value: {}
value: {},
});
}
Errors.prototype.add = function (field, message, code) {
Errors.prototype.add = function(field, message, code) {
code = code || 'invalid';
if (!this[field]) {
this[field] = [];
@ -691,7 +691,7 @@ Errors.prototype.add = function (field, message, code) {
function ErrorCodes(messages) {
var c = this;
Object.keys(messages).forEach(function (field) {
Object.keys(messages).forEach(function(field) {
c[field] = messages[field].codes;
});
}
@ -763,7 +763,7 @@ function ValidationError(obj) {
this.details = {
context: context,
codes: obj.errors && obj.errors.codes,
messages: obj.errors
messages: obj.errors,
};
if (Error.captureStackTrace) {
@ -813,7 +813,7 @@ function formatPropertyError(propertyName, propertyValue, errorMessage) {
showHidden: false,
color: false,
// show top-level object properties only
depth: Array.isArray(propertyValue) ? 1 : 0
depth: Array.isArray(propertyValue) ? 1 : 0,
});
formattedValue = truncatePropertyString(formattedValue);
} else {
@ -839,5 +839,5 @@ function truncatePropertyString(value) {
len -= 3;
}
return value.slice(0, len-4) + '...' + tail;
return value.slice(0, len - 4) + '...' + tail;
}

View File

@ -17,12 +17,12 @@ var Memory = require('../lib/connectors/memory').Memory;
var HOOK_NAMES = [
'access',
'before save', 'persist', 'after save',
'before delete', 'after delete'
'before delete', 'after delete',
];
var dataSources = [
createOptimizedDataSource(),
createUnoptimizedDataSource()
createUnoptimizedDataSource(),
];
var observedContexts = [];
@ -34,7 +34,7 @@ Promise.onPossiblyUnhandledRejection(function(err) {
var operations = [
function find(ds) {
return ds.TestModel.find({ where: { id: '1' } });
return ds.TestModel.find({ where: { id: '1' }});
},
function count(ds) {
@ -47,13 +47,13 @@ var operations = [
function findOrCreate_found(ds) {
return ds.TestModel.findOrCreate(
{ where: { name: ds.existingInstance.name } },
{ where: { name: ds.existingInstance.name }},
{ name: ds.existingInstance.name });
},
function findOrCreate_create(ds) {
return ds.TestModel.findOrCreate(
{ where: { name: 'new-record' } },
{ where: { name: 'new-record' }},
{ name: 'new-record' });
},
@ -134,7 +134,7 @@ function setupTestModels() {
var TestModel = ds.TestModel = ds.createModel('TestModel', {
id: { type: String, id: true, default: uid },
name: { type: String, required: true },
extra: { type: String, required: false }
extra: { type: String, required: false },
});
});
return Promise.resolve();
@ -155,7 +155,7 @@ function runner(fn) {
observedContexts.push({
operation: fn.name,
connector: ds.name,
hooks: {}
hooks: {},
});
return fn(ds);
});
@ -171,11 +171,11 @@ function resetStorage(ds) {
});
return TestModel.deleteAll()
.then(function() {
return TestModel.create({ name: 'first' })
return TestModel.create({ name: 'first' });
})
.then(function(instance) {
// Look it up from DB so that default values are retrieved
return TestModel.findById(instance.id)
return TestModel.findById(instance.id);
})
.then(function(instance) {
ds.existingInstance = instance;
@ -184,7 +184,7 @@ function resetStorage(ds) {
.then(function() {
HOOK_NAMES.forEach(function(hook) {
TestModel.observe(hook, function(ctx, next) {
var row = observedContexts[observedContexts.length-1];
var row = observedContexts[observedContexts.length - 1];
row.hooks[hook] = Object.keys(ctx);
next();
});
@ -193,7 +193,7 @@ function resetStorage(ds) {
}
function report() {
console.log('<style>')
console.log('<style>');
console.log('td { font-family: "monospace": }');
console.log('td, th {');
console.log(' vertical-align: text-top;');
@ -204,7 +204,7 @@ function report() {
// merge rows where Optimized and Unoptimized produce the same context
observedContexts.forEach(function(row, ix) {
if (!ix) return;
var last = observedContexts[ix-1];
var last = observedContexts[ix - 1];
if (row.operation != last.operation) return;
if (JSON.stringify(row.hooks) !== JSON.stringify(last.hooks)) return;
last.merge = true;

View File

@ -9,36 +9,36 @@ var jdb = require('../');
var DataSource = jdb.DataSource;
var ds, Item, Variant;
describe('Datasource-specific field types for foreign keys', function () {
before(function () {
describe('Datasource-specific field types for foreign keys', function() {
before(function() {
ds = new DataSource('memory');
Item = ds.define('Item', {
"myProp": {
"id": true,
"type": "string",
"memory": {
"dataType": "string"
}
}
'myProp': {
'id': true,
'type': 'string',
'memory': {
'dataType': 'string',
},
},
});
Variant = ds.define('Variant', {}, {
relations: {
"item": {
"type": "belongsTo",
"as": "item",
"model": "Item",
"foreignKey": "myProp"
}
}
'item': {
'type': 'belongsTo',
'as': 'item',
'model': 'Item',
'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');
should.exist(VariantDefinition);
should.exist(VariantDefinition.properties.myProp.memory);
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();
});
})

View File

@ -160,7 +160,7 @@ describe('async observer', function() {
it('passes context to final callback', function(done) {
var context = {};
TestModel.notifyObserversOf('event', context, function(err, ctx) {
(ctx || "null").should.equal(context);
(ctx || 'null').should.equal(context);
done();
});
});

View File

@ -8,52 +8,52 @@ var should = require('./init.js');
var async = require('async');
var db, User;
describe('basic-querying', function () {
describe('basic-querying', function() {
before(function (done) {
before(function(done) {
db = getSchema();
User = db.define('User', {
seq: {type: Number, index: true},
name: {type: String, index: true, sort: true},
email: {type: String, index: true},
birthday: {type: Date, index: true},
role: {type: String, index: true},
order: {type: Number, index: true, sort: true},
vip: {type: Boolean}
seq: { type: Number, index: true },
name: { type: String, index: true, sort: true },
email: { type: String, index: true },
birthday: { type: Date, index: true },
role: { type: String, index: true },
order: { type: Number, index: true, sort: true },
vip: { type: Boolean },
});
db.automigrate(done);
});
describe('ping', function () {
it('should be able to test connections', function (done) {
db.ping(function (err) {
describe('ping', function() {
it('should be able to test connections', function(done) {
db.ping(function(err) {
should.not.exist(err);
done();
});
});
});
describe('findById', function () {
describe('findById', function() {
before(function (done) {
before(function(done) {
User.destroyAll(done);
});
it('should query by id: not found', function (done) {
User.findById(1, function (err, u) {
it('should query by id: not found', function(done) {
User.findById(1, function(err, u) {
should.not.exist(u);
should.not.exist(err);
done();
});
});
it('should query by id: found', function (done) {
User.create(function (err, u) {
it('should query by id: found', function(done) {
User.create(function(err, u) {
should.not.exist(err);
should.exist(u.id);
User.findById(u.id, function (err, u) {
User.findById(u.id, function(err, u) {
should.exist(u);
should.not.exist(err);
u.should.be.an.instanceOf(User);
@ -64,7 +64,7 @@ describe('basic-querying', function () {
});
describe('findByIds', function () {
describe('findByIds', function() {
var createdUsers;
before(function(done) {
var people = [
@ -73,7 +73,7 @@ describe('basic-querying', function () {
{ name: 'c' },
{ name: 'd', vip: true },
{ name: 'e' },
{ name: 'f' }
{ name: 'f' },
];
db.automigrate(['User'], function(err) {
User.create(people, function(err, users) {
@ -103,11 +103,11 @@ describe('basic-querying', function () {
it('should query by ids and condition', function(done) {
User.findByIds([
createdUsers[0].id,
createdUsers[1].id,
createdUsers[2].id,
createdUsers[3].id],
{ where: { vip: true } }, function(err, users) {
createdUsers[0].id,
createdUsers[1].id,
createdUsers[2].id,
createdUsers[3].id],
{ where: { vip: true }}, function(err, users) {
should.exist(users);
should.not.exist(err);
var names = users.map(function(u) {
@ -125,12 +125,12 @@ describe('basic-querying', function () {
});
describe('find', function () {
describe('find', function() {
before(seed);
it('should query collection', function (done) {
User.find(function (err, users) {
it('should query collection', function(done) {
User.find(function(err, users) {
should.exists(users);
should.not.exists(err);
users.should.have.lengthOf(6);
@ -138,8 +138,8 @@ describe('basic-querying', function () {
});
});
it('should query limited collection', function (done) {
User.find({limit: 3}, function (err, users) {
it('should query limited collection', function(done) {
User.find({ limit: 3 }, function(err, users) {
should.exists(users);
should.not.exists(err);
users.should.have.lengthOf(3);
@ -147,8 +147,8 @@ describe('basic-querying', function () {
});
});
it('should query collection with skip & limit', function (done) {
User.find({skip: 1, limit: 4, order: 'seq'}, function (err, users) {
it('should query collection with skip & limit', function(done) {
User.find({ skip: 1, limit: 4, order: 'seq' }, function(err, users) {
should.exists(users);
should.not.exists(err);
users[0].seq.should.be.eql(1);
@ -157,8 +157,8 @@ describe('basic-querying', function () {
});
});
it('should query collection with offset & limit', function (done) {
User.find({offset: 2, limit: 3, order: 'seq'}, function (err, users) {
it('should query collection with offset & limit', function(done) {
User.find({ offset: 2, limit: 3, order: 'seq' }, function(err, users) {
should.exists(users);
should.not.exists(err);
users[0].seq.should.be.eql(2);
@ -167,8 +167,8 @@ describe('basic-querying', function () {
});
});
it('should query filtered collection', function (done) {
User.find({where: {role: 'lead'}}, function (err, users) {
it('should query filtered collection', function(done) {
User.find({ where: { role: 'lead' }}, function(err, users) {
should.exists(users);
should.not.exists(err);
users.should.have.lengthOf(2);
@ -176,30 +176,30 @@ describe('basic-querying', function () {
});
});
it('should query collection sorted by numeric field', function (done) {
User.find({order: 'order'}, function (err, users) {
it('should query collection sorted by numeric field', function(done) {
User.find({ order: 'order' }, function(err, users) {
should.exists(users);
should.not.exists(err);
users.forEach(function (u, i) {
users.forEach(function(u, i) {
u.order.should.eql(i + 1);
});
done();
});
});
it('should query collection desc sorted by numeric field', function (done) {
User.find({order: 'order DESC'}, function (err, users) {
it('should query collection desc sorted by numeric field', function(done) {
User.find({ order: 'order DESC' }, function(err, users) {
should.exists(users);
should.not.exists(err);
users.forEach(function (u, i) {
users.forEach(function(u, i) {
u.order.should.eql(users.length - i);
});
done();
});
});
it('should query collection sorted by string field', function (done) {
User.find({order: 'name'}, function (err, users) {
it('should query collection sorted by string field', function(done) {
User.find({ order: 'name' }, function(err, users) {
should.exists(users);
should.not.exists(err);
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) {
User.find({order: 'name DESC'}, function (err, users) {
it('should query collection desc sorted by string field', function(done) {
User.find({ order: 'name DESC' }, function(err, users) {
should.exists(users);
should.not.exists(err);
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) {
User.find({where: {and: [
{name: 'John Lennon'},
{role: 'lead'}
]}}, function (err, users) {
it('should support "and" operator that is satisfied', function(done) {
User.find({ where: { and: [
{ name: 'John Lennon' },
{ role: 'lead' },
] }}, function(err, users) {
should.not.exist(err);
users.should.have.property('length', 1);
done();
});
});
it('should support "and" operator that is not satisfied', function (done) {
User.find({where: {and: [
{name: 'John Lennon'},
{role: 'member'}
]}}, function (err, users) {
it('should support "and" operator that is not satisfied', function(done) {
User.find({ where: { and: [
{ name: 'John Lennon' },
{ role: 'member' },
] }}, function(err, users) {
should.not.exist(err);
users.should.have.property('length', 0);
done();
});
});
it('should support "or" that is satisfied', function (done) {
User.find({where: {or: [
{name: 'John Lennon'},
{role: 'lead'}
]}}, function (err, users) {
it('should support "or" that is satisfied', function(done) {
User.find({ where: { or: [
{ name: 'John Lennon' },
{ role: 'lead' },
] }}, function(err, users) {
should.not.exist(err);
users.should.have.property('length', 2);
done();
});
});
it('should support "or" operator that is not satisfied', function (done) {
User.find({where: {or: [
{name: 'XYZ'},
{role: 'Hello1'}
]}}, function (err, users) {
it('should support "or" operator that is not satisfied', function(done) {
User.find({ where: { or: [
{ name: 'XYZ' },
{ role: 'Hello1' },
] }}, function(err, users) {
should.not.exist(err);
users.should.have.property('length', 0);
done();
});
});
it('should support date "gte" that is satisfied', function (done) {
User.find({order: 'seq', where: { birthday: { "gte": new Date('1980-12-08') }
}}, function (err, users) {
it('should support date "gte" that is satisfied', function(done) {
User.find({ order: 'seq', where: { birthday: { 'gte': new Date('1980-12-08') },
}}, function(err, users) {
should.not.exist(err);
users.should.have.property('length', 1);
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) {
User.find({order: 'seq', where: { birthday: { "gt": new Date('1980-12-08') }
}}, function (err, users) {
it('should support date "gt" that is not satisfied', function(done) {
User.find({ order: 'seq', where: { birthday: { 'gt': new Date('1980-12-08') },
}}, function(err, users) {
should.not.exist(err);
users.should.have.property('length', 0);
done();
});
});
it('should support date "gt" that is satisfied', function (done) {
User.find({order: 'seq', where: { birthday: { "gt": new Date('1980-12-07') }
}}, function (err, users) {
it('should support date "gt" that is satisfied', function(done) {
User.find({ order: 'seq', where: { birthday: { 'gt': new Date('1980-12-07') },
}}, function(err, users) {
should.not.exist(err);
users.should.have.property('length', 1);
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) {
User.find({order: 'seq', where: { birthday: { "lt": new Date('1980-12-07') }
}}, function (err, users) {
it('should support date "lt" that is satisfied', function(done) {
User.find({ order: 'seq', where: { birthday: { 'lt': new Date('1980-12-07') },
}}, function(err, users) {
should.not.exist(err);
users.should.have.property('length', 1);
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) {
User.find({order: 'seq', where: { order: { "gte": 3}
}}, function (err, users) {
it('should support number "gte" that is satisfied', function(done) {
User.find({ order: 'seq', where: { order: { 'gte': 3 },
}}, function(err, users) {
should.not.exist(err);
users.should.have.property('length', 4);
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) {
User.find({order: 'seq', where: { order: { "gt": 6 }
}}, function (err, users) {
it('should support number "gt" that is not satisfied', function(done) {
User.find({ order: 'seq', where: { order: { 'gt': 6 },
}}, function(err, users) {
should.not.exist(err);
users.should.have.property('length', 0);
done();
});
});
it('should support number "gt" that is satisfied', function (done) {
User.find({order: 'seq', where: { order: { "gt": 5 }
}}, function (err, users) {
it('should support number "gt" that is satisfied', function(done) {
User.find({ order: 'seq', where: { order: { 'gt': 5 },
}}, function(err, users) {
should.not.exist(err);
users.should.have.property('length', 1);
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) {
User.find({order: 'seq', where: { order: { "lt": 2 }
}}, function (err, users) {
it('should support number "lt" that is satisfied', function(done) {
User.find({ order: 'seq', where: { order: { 'lt': 2 },
}}, function(err, users) {
should.not.exist(err);
users.should.have.property('length', 1);
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) {
User.find({order: 'seq', where: { order: { "gt": null }
}}, function (err, users) {
it('should support number "gt" that is satisfied by null value', function(done) {
User.find({ order: 'seq', where: { order: { 'gt': null },
}}, function(err, users) {
should.not.exist(err);
users.should.have.property('length', 0);
done();
});
});
it('should support number "lt" that is not satisfied by null value', function (done) {
User.find({order: 'seq', where: { order: { "lt": null }
}}, function (err, users) {
it('should support number "lt" that is not satisfied by null value', function(done) {
User.find({ order: 'seq', where: { order: { 'lt': null },
}}, function(err, users) {
should.not.exist(err);
users.should.have.property('length', 0);
done();
});
});
it('should support string "gte" that is satisfied by null value', function (done) {
User.find({order: 'seq', where: { name: { "gte": null}
}}, function (err, users) {
it('should support string "gte" that is satisfied by null value', function(done) {
User.find({ order: 'seq', where: { name: { 'gte': null },
}}, function(err, users) {
should.not.exist(err);
users.should.have.property('length', 0);
done();
});
});
it('should support string "gte" that is satisfied', function (done) {
User.find({order: 'seq', where: { name: { "gte": 'Paul McCartney'}
}}, function (err, users) {
it('should support string "gte" that is satisfied', function(done) {
User.find({ order: 'seq', where: { name: { 'gte': 'Paul McCartney' },
}}, function(err, users) {
should.not.exist(err);
users.should.have.property('length', 4);
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) {
User.find({order: 'seq', where: { name: { "gt": 'xyz' }
}}, function (err, users) {
it('should support string "gt" that is not satisfied', function(done) {
User.find({ order: 'seq', where: { name: { 'gt': 'xyz' },
}}, function(err, users) {
should.not.exist(err);
users.should.have.property('length', 0);
done();
});
});
it('should support string "gt" that is satisfied', function (done) {
User.find({order: 'seq', where: { name: { "gt": 'Paul McCartney' }
}}, function (err, users) {
it('should support string "gt" that is satisfied', function(done) {
User.find({ order: 'seq', where: { name: { 'gt': 'Paul McCartney' },
}}, function(err, users) {
should.not.exist(err);
users.should.have.property('length', 3);
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) {
User.find({order: 'seq', where: { name: { "lt": 'Paul McCartney' }
}}, function (err, users) {
it('should support string "lt" that is satisfied', function(done) {
User.find({ order: 'seq', where: { name: { 'lt': 'Paul McCartney' },
}}, function(err, users) {
should.not.exist(err);
users.should.have.property('length', 2);
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) {
User.find({order: 'seq', where: { vip: { "gte": true}
}}, function (err, users) {
it('should support boolean "gte" that is satisfied', function(done) {
User.find({ order: 'seq', where: { vip: { 'gte': true },
}}, function(err, users) {
should.not.exist(err);
users.should.have.property('length', 3);
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) {
User.find({order: 'seq', where: { vip: { "gt": true }
}}, function (err, users) {
it('should support boolean "gt" that is not satisfied', function(done) {
User.find({ order: 'seq', where: { vip: { 'gt': true },
}}, function(err, users) {
should.not.exist(err);
users.should.have.property('length', 0);
done();
});
});
it('should support boolean "gt" that is satisfied', function (done) {
User.find({order: 'seq', where: { vip: { "gt": false }
}}, function (err, users) {
it('should support boolean "gt" that is satisfied', function(done) {
User.find({ order: 'seq', where: { vip: { 'gt': false },
}}, function(err, users) {
should.not.exist(err);
users.should.have.property('length', 3);
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) {
User.find({order: 'seq', where: { vip: { "lt": true }
}}, function (err, users) {
it('should support boolean "lt" that is satisfied', function(done) {
User.find({ order: 'seq', where: { vip: { 'lt': true },
}}, function(err, users) {
should.not.exist(err);
users.should.have.property('length', 2);
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;
function sample(fields) {
return {
expect: function (arr) {
expect: function(arr) {
remaining++;
User.find({fields: fields}, function (err, users) {
User.find({ fields: fields }, function(err, users) {
remaining--;
if (err) return done(err);
@ -467,11 +467,11 @@ describe('basic-querying', function () {
done();
}
users.forEach(function (user) {
users.forEach(function(user) {
var obj = user.toObject();
Object.keys(obj)
.forEach(function (key) {
.forEach(function(key) {
// if the obj has an unexpected value
if (obj[key] !== undefined && arr.indexOf(key) === -1) {
console.log('Given fields:', fields);
@ -482,14 +482,14 @@ describe('basic-querying', function () {
});
});
});
}
}
},
};
}
sample({name: true}).expect(['name']);
sample({name: false}).expect(['id', 'seq', 'email', 'role', 'order', 'birthday', 'vip']);
sample({name: false, id: true}).expect(['id']);
sample({id: true}).expect(['id']);
sample({ name: true }).expect(['name']);
sample({ name: false }).expect(['id', 'seq', 'email', 'role', 'order', 'birthday', 'vip']);
sample({ name: false, id: true }).expect(['id']);
sample({ id: true }).expect(['id']);
sample('id').expect(['id']);
sample(['id']).expect(['id']);
sample(['email']).expect(['email']);
@ -497,12 +497,12 @@ describe('basic-querying', function () {
});
describe('count', function () {
describe('count', function() {
before(seed);
it('should query total count', function (done) {
User.count(function (err, n) {
it('should query total count', function(done) {
User.count(function(err, n) {
should.not.exist(err);
should.exist(n);
n.should.equal(6);
@ -510,8 +510,8 @@ describe('basic-querying', function () {
});
});
it('should query filtered count', function (done) {
User.count({role: 'lead'}, function (err, n) {
it('should query filtered count', function(done) {
User.count({ role: 'lead' }, function(err, n) {
should.not.exist(err);
should.exist(n);
n.should.equal(2);
@ -520,13 +520,13 @@ describe('basic-querying', function () {
});
});
describe('findOne', function () {
describe('findOne', function() {
before(seed);
it('should find first record (default sort by id)', function (done) {
User.all({order: 'id'}, function (err, users) {
User.findOne(function (e, u) {
it('should find first record (default sort by id)', function(done) {
User.all({ order: 'id' }, function(err, users) {
User.findOne(function(e, u) {
should.not.exist(e);
should.exist(u);
u.id.toString().should.equal(users[0].id.toString());
@ -535,8 +535,8 @@ describe('basic-querying', function () {
});
});
it('should find first record', function (done) {
User.findOne({order: 'order'}, function (e, u) {
it('should find first record', function(done) {
User.findOne({ order: 'order' }, function(e, u) {
should.not.exist(e);
should.exist(u);
u.order.should.equal(1);
@ -545,8 +545,8 @@ describe('basic-querying', function () {
});
});
it('should find last record', function (done) {
User.findOne({order: 'order DESC'}, function (e, u) {
it('should find last record', function(done) {
User.findOne({ order: 'order DESC' }, function(e, u) {
should.not.exist(e);
should.exist(u);
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({
where: {role: 'lead'},
order: 'order DESC'
}, function (e, u) {
where: { role: 'lead' },
order: 'order DESC',
}, function(e, u) {
should.not.exist(e);
should.exist(u);
u.order.should.equal(2);
@ -568,9 +568,9 @@ describe('basic-querying', function () {
});
});
it('should work even when find by id', function (done) {
User.findOne(function (e, u) {
User.findOne({where: {id: u.id}}, function (err, user) {
it('should work even when find by id', function(done) {
User.findOne(function(e, u) {
User.findOne({ where: { id: u.id }}, function(err, user) {
should.not.exist(err);
should.exist(user);
done();
@ -580,13 +580,13 @@ describe('basic-querying', function () {
});
describe('exists', function () {
describe('exists', function() {
before(seed);
it('should check whether record exist', function (done) {
User.findOne(function (e, u) {
User.exists(u.id, function (err, exists) {
it('should check whether record exist', function(done) {
User.findOne(function(e, u) {
User.exists(u.id, function(err, exists) {
should.not.exist(err);
should.exist(exists);
exists.should.be.ok;
@ -595,9 +595,9 @@ describe('basic-querying', function () {
});
});
it('should check whether record not exist', function (done) {
User.destroyAll(function () {
User.exists(42, function (err, exists) {
it('should check whether record not exist', function(done) {
User.destroyAll(function() {
User.exists(42, function(err, exists) {
should.not.exist(err);
exists.should.not.be.ok;
done();
@ -615,7 +615,7 @@ describe('basic-querying', function () {
// `undefined` is not tested because the `removeUndefined` function
// in `lib/dao.js` removes it before coercion
invalidDataTypes.forEach(function(invalidDataType) {
User.find({where: {name: {regexp: invalidDataType}}}, function(err,
User.find({ where: { name: { regexp: invalidDataType }}}, function(err,
users) {
should.exist(err);
});
@ -632,25 +632,25 @@ describe.skip('queries', function() {
var db = getSchema();
Todo = db.define('Todo', {
id: false,
content: {type: 'string'}
content: { type: 'string' },
}, {
idInjection: false
idInjection: false,
});
db.automigrate(['Todo'], done);
});
beforeEach(function resetFixtures(done) {
Todo.destroyAll(function() {
Todo.create([
{content: 'Buy eggs'},
{content: 'Buy milk'},
{content: 'Buy sausages'}
{ content: 'Buy eggs' },
{ content: 'Buy milk' },
{ content: 'Buy sausages' },
], done);
});
});
context('that do not require an id', function() {
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);
done();
});
@ -659,7 +659,7 @@ describe.skip('queries', function() {
it('should work for updateOrCreate/upsert', function(done) {
var aliases = ['updateOrCreate', 'upsert'];
async.each(aliases, function(alias, cb) {
Todo[alias]({content: 'Buy ham'}, function(err) {
Todo[alias]({ content: 'Buy ham' }, function(err) {
should.not.exist(err);
cb();
});
@ -667,14 +667,14 @@ describe.skip('queries', function() {
});
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);
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);
done();
});
@ -707,14 +707,14 @@ describe.skip('queries', function() {
});
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);
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);
done();
});
@ -742,15 +742,15 @@ describe.skip('queries', function() {
it('should return an error for deleteById/destroyById/removeById',
function(done) {
var aliases = ['deleteById', 'destroyById', 'removeById'];
async.each(aliases, function(alias, cb) {
Todo[alias](1, function(err) {
var aliases = ['deleteById', 'destroyById', 'removeById'];
async.each(aliases, function(alias, cb) {
Todo[alias](1, function(err) {
should.exist(err);
err.message.should.equal(expectedErrMsg);
cb();
});
}, done);
});
}, done);
});
it('should return an error for instance.save', function(done) {
var todo = new Todo();
@ -784,7 +784,7 @@ describe.skip('queries', function() {
it('should return an error for instance.updateAttributes', function(done) {
Todo.findOne(function(err, todo) {
todo.updateAttributes({content: 'Buy ham'}, function(err) {
todo.updateAttributes({ content: 'Buy ham' }, function(err) {
should.exist(err);
err.message.should.equal(expectedErrMsg);
done();
@ -803,7 +803,7 @@ function seed(done) {
role: 'lead',
birthday: new Date('1980-12-08'),
order: 2,
vip: true
vip: true,
},
{
seq: 1,
@ -812,18 +812,18 @@ function seed(done) {
role: 'lead',
birthday: new Date('1942-06-18'),
order: 1,
vip: true
vip: true,
},
{seq: 2, name: 'George Harrison', order: 5, vip: false},
{seq: 3, name: 'Ringo Starr', order: 6, vip: false},
{seq: 4, name: 'Pete Best', order: 4},
{seq: 5, name: 'Stuart Sutcliffe', order: 3, vip: true}
{ seq: 2, name: 'George Harrison', order: 5, vip: false },
{ seq: 3, name: 'Ringo Starr', order: 6, vip: false },
{ seq: 4, name: 'Pete Best', order: 4 },
{ seq: 5, name: 'Stuart Sutcliffe', order: 3, vip: true },
];
async.series([
User.destroyAll.bind(User),
function(cb) {
async.each(beatles, User.create.bind(User), cb);
}
},
], done);
}

View File

@ -28,13 +28,13 @@ module.exports = function testSchema(exportCasesHere, dataSource) {
}
var start;
batch['should connect to database'] = function (test) {
batch['should connect to database'] = function(test) {
start = Date.now();
if (dataSource.connected) return test.done();
dataSource.on('connected', test.done);
};
dataSource.log = function (a) {
dataSource.log = function(a) {
console.log(a);
nbSchemaRequests++;
};
@ -43,7 +43,7 @@ module.exports = function testSchema(exportCasesHere, dataSource) {
testOrm(dataSource);
batch['all tests done'] = function (test) {
batch['all tests done'] = function(test) {
test.done();
process.nextTick(allTestsDone);
};
@ -59,19 +59,19 @@ Object.defineProperty(module.exports, 'it', {
writable: true,
enumerable: false,
configurable: true,
value: it
value: it,
});
Object.defineProperty(module.exports, 'skip', {
writable: true,
enumerable: false,
configurable: true,
value: skip
value: skip,
});
function clearAndCreate(model, data, callback) {
var createdItems = [];
model.destroyAll(function () {
model.destroyAll(function() {
nextItem(null, null);
});
@ -95,7 +95,7 @@ function testOrm(dataSource) {
var Post, User, Passport, Log, Dog;
it('should define class', function (test) {
it('should define class', function(test) {
User = dataSource.define('User', {
name: { type: String, index: true },
@ -104,52 +104,52 @@ function testOrm(dataSource) {
approved: Boolean,
joinedAt: Date,
age: Number,
passwd: { type: String, index: true }
passwd: { type: String, index: true },
});
Dog = dataSource.define('Dog', {
name: { type: String, limit: 64, allowNull: false }
name: { type: String, limit: 64, allowNull: false },
});
Log = dataSource.define('Log', {
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', {
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);
Post = dataSource.define('Post', {
title: { type: String, length: 255, index: true },
subject: { type: String },
content: { type: Text },
date: { type: Date, default: function () {
return new Date
date: { type: Date, default: function() {
return new Date;
}, index: true },
published: { type: Boolean, default: false, index: true },
likes: [],
related: [RelatedPost]
}, {table: 'posts'});
related: [RelatedPost],
}, { table: 'posts' });
function RelatedPost() {
}
RelatedPost.prototype.someMethod = function () {
RelatedPost.prototype.someMethod = function() {
return this.parent;
};
Post.validateAsync('title', function (err, done) {
Post.validateAsync('title', function(err, done) {
process.nextTick(done);
});
User.hasMany(Post, {as: 'posts', foreignKey: 'userId'});
User.hasMany(Post, { as: 'posts', foreignKey: 'userId' });
// creates instance methods:
// user.posts(conds)
// user.posts.build(data) // like new Post({userId: user.id});
@ -164,18 +164,18 @@ function testOrm(dataSource) {
// user.latestPost.build(data)
// user.latestPost.create(data)
Post.belongsTo(User, {as: 'author', foreignKey: 'userId'});
Post.belongsTo(User, { as: 'author', foreignKey: 'userId' });
// creates instance methods:
// post.author(callback) -- getter when called with function
// post.author() -- sync getter when called without params
// post.author(user) -- setter when called with object
Passport = dataSource.define('Passport', {
number: String
number: String,
});
Passport.belongsTo(User, {as: 'owner', foreignKey: 'ownerId'});
User.hasMany(Passport, {as: 'passports', foreignKey: 'ownerId'});
Passport.belongsTo(User, { as: 'owner', foreignKey: 'ownerId' });
User.hasMany(Passport, { as: 'passports', foreignKey: 'ownerId' });
var user = new User;
@ -188,7 +188,7 @@ function testOrm(dataSource) {
// instance methods
test.ok(user.save instanceof Function);
dataSource.automigrate(function (err) {
dataSource.automigrate(function(err) {
if (err) {
console.log('Error while migrating');
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',
now = Date.now(),
post = new Post({title: hw}),
anotherPost = Post({title: 'Resig style constructor'});
post = new Post({ title: hw }),
anotherPost = Post({ title: 'Resig style constructor' });
test.equal(post.title, hw);
test.ok(!post.propertyChanged('title'), 'property changed: title');
@ -218,31 +218,31 @@ function testOrm(dataSource) {
test.done();
});
it('should save object', function (test) {
it('should save object', function(test) {
var title = 'Initial title', title2 = 'Hello world',
date = new Date;
Post.create({
title: title,
date: date
}, function (err, obj) {
date: date,
}, function(err, obj) {
test.ok(obj.id, 'Object id should present');
test.equals(obj.title, title);
// test.equals(obj.date, date);
obj.title = title2;
test.ok(obj.propertyChanged('title'), 'Title changed');
obj.save(function (err, obj) {
obj.save(function(err, obj) {
test.equal(obj.title, title2);
test.ok(!obj.propertyChanged('title'));
var p = new Post({title: 1});
var p = new Post({ title: 1 });
p.title = 2;
p.save(function (err, obj) {
p.save(function(err, obj) {
test.ok(!p.propertyChanged('title'));
p.title = 3;
test.ok(p.propertyChanged('title'));
test.equal(p.title_was, 2);
p.save(function () {
p.save(function() {
test.equal(p.title_was, 3);
test.ok(!p.propertyChanged('title'));
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',
date = new Date;
Post.create({
title: title,
date: date
}, function (err, obj) {
date: date,
}, function(err, obj) {
test.ok(obj.id);
test.equals(obj.title, title);
test.equals(obj.date, date);
Post.findById(obj.id, function () {
Post.findById(obj.id, function() {
test.equal(obj.title, title);
test.equal(obj.date.toString(), date.toString());
test.done();
@ -271,13 +271,13 @@ function testOrm(dataSource) {
});
});
it('should save only dataSource-defined field in database', function (test) {
Post.create({title: '1602', nonSchemaField: 'some value'}, function (err, post) {
it('should save only dataSource-defined field in database', function(test) {
Post.create({ title: '1602', nonSchemaField: 'some value' }, function(err, post) {
test.ok(!post.nonSchemaField);
post.a = 1;
post.save(function () {
post.save(function() {
test.ok(post.a);
post.reload(function (err, psto) {
post.reload(function(err, psto) {
test.ok(!psto.a);
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 post = new Post({title: title});
post.save(function (err, savedPost) {
var post = new Post({ title: title });
post.save(function(err, savedPost) {
test.strictEqual(post, savedPost);
test.done();
});
});
it('should destroy object', function (test) {
Post.create(function (err, post) {
Post.exists(post.id, function (err, exists) {
it('should destroy object', function(test) {
Post.create(function(err, post) {
Post.exists(post.id, function(err, exists) {
test.ok(exists, 'Object exists');
post.destroy(function () {
Post.exists(post.id, function (err, exists) {
post.destroy(function() {
Post.exists(post.id, function(err, exists) {
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...');
Post.findById(post.id, function (err, obj) {
Post.findById(post.id, function(err, obj) {
test.equal(obj, null, 'Param obj should be null');
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';
User.setter.passwd = function (password) {
User.setter.passwd = function(password) {
this._passwd = calcHash(password, salt);
};
@ -361,15 +361,15 @@ function testOrm(dataSource) {
// });
// });
it('should update single attribute', function (test) {
Post.create({title: 'title', content: 'content', published: true}, function (err, post) {
it('should update single attribute', function(test) {
Post.create({ title: 'title', content: 'content', published: true }, function(err, post) {
post.content = 'New content';
post.updateAttribute('title', 'New title', function () {
post.updateAttribute('title', 'New title', function() {
test.equal(post.title, 'New title');
test.ok(!post.propertyChanged('title'));
test.equal(post.content, 'New content', 'dirty state saved');
test.ok(post.propertyChanged('content'));
post.reload(function (err, post) {
post.reload(function(err, post) {
test.equal(post.title, 'New title');
test.ok(!post.propertyChanged('title'), 'title not changed');
test.equal(post.content, 'content', 'real value turned back');
@ -381,22 +381,22 @@ function testOrm(dataSource) {
});
var countOfposts, countOfpostsFiltered;
it('should fetch collection', function (test) {
Post.all(function (err, posts) {
it('should fetch collection', function(test) {
Post.all(function(err, posts) {
countOfposts = posts.length;
test.ok(countOfposts > 0);
test.ok(posts[0] instanceof Post);
countOfpostsFiltered = posts.filter(function (p) {
countOfpostsFiltered = posts.filter(function(p) {
return p.title === 'title';
}).length;
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;
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.create({ title: 'title', content: 'content', published: true, date: d }, function(err, post) {
Post.all({ where: { title: 'title', date: d, published: true }}, function(err, res) {
test.equals(res.length, 1, 'Filtering Posts returns one post');
test.done();
});
@ -409,7 +409,7 @@ function testOrm(dataSource) {
dataSource.name !== 'neo4j' &&
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.posts, 'posts relation should exist on User');
test.equal(User.relations.posts.type, 'hasMany', 'Type of hasMany relation is hasMany');
@ -426,15 +426,15 @@ function testOrm(dataSource) {
test.done();
});
it('should handle hasMany relationship', function (test) {
User.create(function (err, u) {
it('should handle hasMany relationship', function(test) {
User.create(function(err, u) {
if (err) return console.log(err);
test.ok(u.posts, 'Method defined: posts');
test.ok(u.posts.build, 'Method defined: posts.build');
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);
u.posts(function (err, posts) {
u.posts(function(err, posts) {
test.equal(posts.pop().id.toString(), post.id.toString());
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);
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);
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'
if (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) {
u.posts.create({}, function (e, p) {
u.posts({where: {id: p.id}}, function (e, posts) {
User.create(function(e, u) {
u.posts.create({}, function(e, p) {
u.posts({ where: { id: p.id }}, function(e, posts) {
test.equal(posts.length, 1, 'There should be only 1 post.');
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) {
// u.posts.create({}, function (e, p) {
// find all posts for a user.
// 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
for (var i = 0; i < posts.length; i++) {
var post = posts[i];
if (post.userId) {
// 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.create(function (err, voidUser) {
Post.create({userId: user.id}, function () {
User.findById(post.userId, function(err, user) {
User.create(function(err, voidUser) {
Post.create({ userId: user.id }, function() {
// There can't be any concurrency because we are counting requests
// We are first testing cases when user has posts
user.posts(function (err, data) {
user.posts(function(err, data) {
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, 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.');
@ -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)
test.done();
} 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.');
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.');
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
voidUser.posts(function (err, data) {
voidUser.posts(function(err, data) {
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(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.');
voidUser.posts(true, function (err, data3) {
voidUser.posts(true, function(err, data3) {
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.');
@ -555,24 +555,24 @@ function testOrm(dataSource) {
// });
// });
it('should support scopes', function (test) {
it('should support scopes', function(test) {
var wait = 2;
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(Post.published._scope.where.published === true);
var post = Post.published.build();
test.ok(post.published, 'Can build');
test.ok(post.isNewRecord());
Post.published.create(function (err, psto) {
Post.published.create(function(err, psto) {
if (err) return console.log(err);
test.ok(psto.published);
test.ok(!psto.isNewRecord());
done();
});
User.create(function (err, u) {
User.create(function(err, u) {
if (err) return console.log(err);
test.ok(typeof u.posts.published == 'function');
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('content'), 'Text');
var p = new Post;
@ -595,26 +595,26 @@ function testOrm(dataSource) {
test.done();
});
it('should handle ORDER clause', function (test) {
it('should handle ORDER clause', function(test) {
var titles = [
{ title: 'Title A', subject: "B" },
{ title: 'Title Z', subject: "A" },
{ title: 'Title M', subject: "C" },
{ title: 'Title A', subject: "A" },
{ title: 'Title B', subject: "A" },
{ title: 'Title C', subject: "D" }
{ title: 'Title A', subject: 'B' },
{ title: 'Title Z', subject: 'A' },
{ title: 'Title M', subject: 'C' },
{ title: 'Title A', subject: 'A' },
{ title: 'Title B', subject: 'A' },
{ title: 'Title C', subject: 'D' },
];
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 * 9),
new Date(1000 * 0),
new Date(1000 * 17),
new Date(1000 * 10),
new Date(1000 * 9)
new Date(1000 * 9),
];
titles.forEach(function (t, i) {
Post.create({title: t.title, subject: t.subject, date: dates[i]}, done);
titles.forEach(function(t, i) {
Post.create({ title: t.title, subject: t.subject, date: dates[i] }, done);
});
var i = 0, tests = 0;
@ -643,10 +643,10 @@ function testOrm(dataSource) {
function doStringTest() {
tests += 1;
Post.all({order: 'title'}, function (err, posts) {
Post.all({ order: 'title' }, function(err, posts) {
if (err) console.log(err);
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);
});
finished();
@ -655,10 +655,10 @@ function testOrm(dataSource) {
function doNumberTest() {
tests += 1;
Post.all({order: 'date'}, function (err, posts) {
Post.all({ order: 'date' }, function(err, posts) {
if (err) console.log(err);
test.equal(posts.length, 6);
dates.sort(numerically).forEach(function (d, i) {
dates.sort(numerically).forEach(function(d, i) {
if (posts[i])
test.equal(posts[i].date.toString(), d.toString(), 'doNumberTest');
});
@ -668,11 +668,11 @@ function testOrm(dataSource) {
function doFilterAndSortTest() {
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);
console.log(posts.length);
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]) {
test.equal(posts[i].title, t, 'doFilterAndSortTest');
}
@ -683,10 +683,10 @@ function testOrm(dataSource) {
function doFilterAndSortReverseTest() {
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);
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]) {
test.equal(posts[i].title, t, 'doFilterAndSortReverseTest');
}
@ -697,28 +697,28 @@ function testOrm(dataSource) {
function doMultipleSortTest() {
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);
test.equal(posts.length, 6);
test.equal(posts[0].title, "Title A");
test.equal(posts[0].subject, "A");
test.equal(posts[1].title, "Title A");
test.equal(posts[1].subject, "B");
test.equal(posts[5].title, "Title Z");
test.equal(posts[0].title, 'Title A');
test.equal(posts[0].subject, 'A');
test.equal(posts[1].title, 'Title A');
test.equal(posts[1].subject, 'B');
test.equal(posts[5].title, 'Title Z');
finished();
});
}
function doMultipleReverseSortTest() {
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);
test.equal(posts.length, 6);
test.equal(posts[0].title, "Title A");
test.equal(posts[0].subject, "B");
test.equal(posts[1].title, "Title A");
test.equal(posts[1].subject, "A");
test.equal(posts[5].title, "Title Z");
test.equal(posts[0].title, 'Title A');
test.equal(posts[0].subject, 'B');
test.equal(posts[1].title, 'Title A');
test.equal(posts[1].subject, 'A');
test.equal(posts[5].title, 'Title Z');
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 emails = [
'john@hcompany.com',
@ -886,18 +886,18 @@ function testOrm(dataSource) {
'tin@hcompany.com',
'mike@hcompany.com',
'susan@hcompany.com',
'test@hcompany.com'
'test@hcompany.com',
];
User.destroyAll(function () {
emails.forEach(function (email) {
User.destroyAll(function() {
emails.forEach(function(email) {
wait += 1;
User.create({email: email, name: 'Nick'}, done);
User.create({ email: email, name: 'Nick' }, done);
});
});
var tests = 2;
function done() {
process.nextTick(function () {
process.nextTick(function() {
if (--wait === 0) {
doSortTest();
doReverseSortTest();
@ -906,9 +906,9 @@ function testOrm(dataSource) {
}
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();
users.forEach(function (user, i) {
users.forEach(function(user, i) {
test.equal(_emails[i], user.email, 'ASC sorting');
});
testDone();
@ -916,9 +916,9 @@ function testOrm(dataSource) {
}
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();
users.forEach(function (user, i) {
users.forEach(function(user, i) {
test.equal(_emails[i], user.email, 'DESC sorting');
});
testDone();
@ -930,12 +930,12 @@ function testOrm(dataSource) {
}
});
it('should return id in find result even after updateAttributes', function (test) {
Post.create(function (err, post) {
it('should return id in find result even after updateAttributes', function(test) {
Post.create(function(err, post) {
var id = post.id;
test.ok(post.published === false);
post.updateAttributes({title: 'hey', published: true}, function () {
Post.find(id, function (err, post) {
post.updateAttributes({ title: 'hey', published: true }, function() {
Post.find(id, function(err, post) {
test.ok(!!post.published, 'Update boolean field');
test.ok(post.id);
test.done();
@ -944,8 +944,8 @@ function testOrm(dataSource) {
});
});
it('should handle belongsTo correctly', function (test) {
var passport = new Passport({ownerId: 16});
it('should handle belongsTo correctly', function(test) {
var passport = new Passport({ ownerId: 16 });
// sync getter
test.equal(passport.owner(), 16);
// sync setter
@ -954,18 +954,18 @@ function testOrm(dataSource) {
test.done();
});
it('should query one record', function (test) {
it('should query one record', function(test) {
test.expect(4);
Post.findOne(function (err, post) {
Post.findOne(function(err, post) {
test.ok(post && post.id);
Post.findOne({ where: { title: 'hey' } }, function (err, post) {
Post.findOne({ where: { title: 'hey' }}, function(err, post) {
if (err) {
console.log(err);
return test.done();
}
test.equal(post && post.constructor.modelName, 'Post');
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.done();
});
@ -1023,13 +1023,13 @@ function testOrm(dataSource) {
// });
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 = {
id: 1,
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;
test.ok(updatedPost);
if (!updatedPost) throw Error('No post!');
@ -1040,7 +1040,7 @@ function testOrm(dataSource) {
test.equal(newData.title, updatedPost.toObject().title);
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 (!post) throw Error('No post!');
if (dataSource.name !== 'mongodb') {
@ -1048,10 +1048,10 @@ function testOrm(dataSource) {
}
test.equal(newData.title, post.toObject().title);
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);
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!');
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.setter.passwd = function (pass) {
User.setter.passwd = function(pass) {
this._passwd = pass + 'salt';
};
var u = new User({passwd: 'qwerty'});
var u = new User({ passwd: 'qwerty' });
test.equal(u.passwd, 'qwertysalt');
u.save(function (err, user) {
User.findById(user.id, function (err, user) {
u.save(function(err, user) {
User.findById(user.id, function(err, user) {
test.ok(user !== u);
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.equal(users[0].passwd, 'qwertysalt');
User.create({passwd: 'asalat'}, function (err, usr) {
User.create({ passwd: 'asalat' }, function(err, usr) {
test.equal(usr.passwd, 'asalatsalt');
User.upsert({passwd: 'heyman'}, function (err, us) {
User.upsert({ passwd: 'heyman' }, function(err, us) {
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.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 like = post.likes.push({foo: 'bar'});
var like = post.likes.push({ foo: 'bar' });
test.equal(like.constructor.name, 'ListItem');
var related = post.related.push({hello: 'world'});
var related = post.related.push({ hello: 'world' });
test.ok(related.someMethod);
post.save(function (err, p) {
post.save(function(err, p) {
test.equal(p.likes.nextid, 2);
p.likes.push({second: 2});
p.likes.push({third: 3});
p.save(function (err) {
Post.findById(p.id, function (err, pp) {
p.likes.push({ second: 2 });
p.likes.push({ third: 3 });
p.save(function(err) {
Post.findById(p.id, function(err, pp) {
test.equal(pp.likes.length, 3);
test.ok(pp.likes[3].third);
test.ok(pp.likes[2].second);
@ -1112,8 +1112,8 @@ function testOrm(dataSource) {
test.equal(pp.likes.length, 1);
test.ok(!pp.likes[1]);
test.ok(pp.likes[3]);
pp.save(function () {
Post.findById(p.id, function (err, pp) {
pp.save(function() {
Post.findById(p.id, function(err, pp) {
test.equal(pp.likes.length, 1);
test.ok(!pp.likes[1]);
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();
User.findOrCreate({where: {email: email}}, function (err, u, created) {
User.findOrCreate({ where: { email: email }}, function(err, u, created) {
test.ok(u);
test.ok(!u.age);
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.ok(!u2.age);
test.ok(!created);

View File

@ -8,61 +8,61 @@ var should = require('./init.js');
var async = require('async');
var db, User, options, filter;
describe('crud-with-options', function () {
describe('crud-with-options', function() {
before(function (done) {
before(function(done) {
db = getSchema();
User = db.define('User', {
seq: {type: Number, index: true},
name: {type: String, index: true, sort: true},
email: {type: String, index: true},
birthday: {type: Date, index: true},
role: {type: String, index: true},
order: {type: Number, index: true, sort: true},
vip: {type: Boolean}
seq: { type: Number, index: true },
name: { type: String, index: true, sort: true },
email: { type: String, index: true },
birthday: { type: Date, index: true },
role: { type: String, index: true },
order: { type: Number, index: true, sort: true },
vip: { type: Boolean },
});
options = {};
filter = {fields: ['name', 'id']};
filter = { fields: ['name', 'id'] };
db.automigrate(['User'], done);
});
describe('findById', function () {
describe('findById', function() {
before(function (done) {
before(function(done) {
User.destroyAll(done);
});
it('should allow findById(id, options, cb)', function (done) {
User.findById(1, options, function (err, u) {
it('should allow findById(id, options, cb)', function(done) {
User.findById(1, options, function(err, u) {
should.not.exist(u);
should.not.exist(err);
done();
});
});
it('should allow findById(id, filter, cb)', function (done) {
User.findById(1, filter, function (err, u) {
it('should allow findById(id, filter, cb)', function(done) {
User.findById(1, filter, function(err, u) {
should.not.exist(u);
should.not.exist(err);
done();
});
});
it('should allow findById(id)', function () {
it('should allow findById(id)', function() {
User.findById(1);
});
it('should allow findById(id, filter)', function () {
it('should allow findById(id, filter)', function() {
User.findById(1, filter);
});
it('should allow findById(id, options)', function () {
it('should allow findById(id, options)', function() {
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);
});
@ -72,7 +72,7 @@ describe('crud-with-options', function () {
User.findById(1, '123', function(err, u) {
});
}).should.throw('The filter argument must be an object');
done();
done();
});
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',
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.exist(u.id);
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',
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.exist(u.id);
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',
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.exist(u.id);
User.findById(u.id, filter, options, function(err, u) {
@ -143,7 +143,7 @@ describe('crud-with-options', function () {
it('should allow promise-style findById',
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);
return User.findById(u.id).then(function(u) {
should.exist(u);
@ -189,7 +189,7 @@ describe('crud-with-options', function () {
});
describe('findByIds', function () {
describe('findByIds', function() {
before(function(done) {
var people = [
@ -198,7 +198,7 @@ describe('crud-with-options', function () {
{ id: 3, name: 'c' },
{ id: 4, name: 'd', vip: true },
{ id: 5, name: 'e' },
{ id: 6, name: 'f' }
{ id: 6, name: 'f' },
];
// Use automigrate so that serial keys are 1-6
db.automigrate(['User'], function(err) {
@ -208,8 +208,8 @@ describe('crud-with-options', function () {
});
});
it('should allow findByIds(ids, cb)', function (done) {
User.findByIds([3, 2, 1], function (err, users) {
it('should allow findByIds(ids, cb)', function(done) {
User.findByIds([3, 2, 1], function(err, users) {
should.exist(users);
should.not.exist(err);
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)',
function(done) {
User.findByIds([4, 3, 2, 1],
{ where: { vip: true } }, options, function(err, users) {
{ where: { vip: true }}, options, function(err, users) {
should.exist(users);
should.not.exist(err);
var names = users.map(function(u) {
@ -234,7 +234,7 @@ describe('crud-with-options', function () {
});
describe('find', function () {
describe('find', function() {
before(seed);
@ -248,7 +248,7 @@ describe('crud-with-options', function () {
});
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.not.exists(err);
users.should.have.lengthOf(3);
@ -266,15 +266,15 @@ describe('crud-with-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() {
User.find({limit: 3});
User.find({ limit: 3 });
});
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.not.exists(err);
users.should.have.lengthOf(3);
@ -292,7 +292,7 @@ describe('crud-with-options', function () {
it('should throw on an invalid options arg', function() {
(function() {
User.find({limit: 3}, 'invalid option', function(err, users) {
User.find({ limit: 3 }, 'invalid option', function(err, users) {
// noop
});
}).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() {
(function() {
User.find({limit: 3}, {}, 'invalid cb');
User.find({ limit: 3 }, {}, 'invalid cb');
}).should.throw('The cb argument must be a function');
});
});
describe('count', function () {
describe('count', function() {
before(seed);
it('should allow count(cb)', function (done) {
User.count(function (err, n) {
it('should allow count(cb)', function(done) {
User.count(function(err, n) {
should.not.exist(err);
should.exist(n);
n.should.equal(6);
@ -319,8 +319,8 @@ describe('crud-with-options', function () {
});
});
it('should allow count(where, cb)', function (done) {
User.count({role: 'lead'}, function (err, n) {
it('should allow count(where, cb)', function(done) {
User.count({ role: 'lead' }, function(err, n) {
should.not.exist(err);
should.exist(n);
n.should.equal(2);
@ -328,8 +328,8 @@ describe('crud-with-options', function () {
});
});
it('should allow count(where, options, cb)', function (done) {
User.count({role: 'lead'}, options, function (err, n) {
it('should allow count(where, options, cb)', function(done) {
User.count({ role: 'lead' }, options, function(err, n) {
should.not.exist(err);
should.exist(n);
n.should.equal(2);
@ -339,13 +339,13 @@ describe('crud-with-options', function () {
});
describe('findOne', function () {
describe('findOne', function() {
before(seed);
it('should allow findOne(cb)', function (done) {
User.find({order: 'id'}, function (err, users) {
User.findOne(function (e, u) {
it('should allow findOne(cb)', function(done) {
User.find({ order: 'id' }, function(err, users) {
User.findOne(function(e, u) {
should.not.exist(e);
should.exist(u);
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) {
User.findOne({order: 'order'}, options, function (e, u) {
it('should allow findOne(filter, options, cb)', function(done) {
User.findOne({ order: 'order' }, options, function(e, u) {
should.not.exist(e);
should.exist(u);
u.order.should.equal(1);
@ -364,8 +364,8 @@ describe('crud-with-options', function () {
});
});
it('should allow findOne(filter, cb)', function (done) {
User.findOne({order: 'order'}, function (e, u) {
it('should allow findOne(filter, cb)', function(done) {
User.findOne({ order: 'order' }, function(e, u) {
should.not.exist(e);
should.exist(u);
u.order.should.equal(1);
@ -374,8 +374,8 @@ describe('crud-with-options', function () {
});
});
it('should allow trailing undefined args', function (done) {
User.findOne({order: 'order'}, function (e, u) {
it('should allow trailing undefined args', function(done) {
User.findOne({ order: 'order' }, function(e, u) {
should.not.exist(e);
should.exist(u);
u.order.should.equal(1);
@ -386,13 +386,13 @@ describe('crud-with-options', function () {
});
describe('exists', function () {
describe('exists', function() {
before(seed);
it('should allow exists(id, cb)', function (done) {
User.findOne(function (e, u) {
User.exists(u.id, function (err, exists) {
it('should allow exists(id, cb)', function(done) {
User.findOne(function(e, u) {
User.exists(u.id, function(err, exists) {
should.not.exist(err);
should.exist(exists);
exists.should.be.ok;
@ -401,9 +401,9 @@ describe('crud-with-options', function () {
});
});
it('should allow exists(id, options, cb)', function (done) {
User.destroyAll(function () {
User.exists(42, options, function (err, exists) {
it('should allow exists(id, options, cb)', function(done) {
User.destroyAll(function() {
User.exists(42, options, function(err, exists) {
should.not.exist(err);
exists.should.not.be.ok;
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 opts;
@ -434,17 +434,17 @@ describe('crud-with-options', function () {
});
describe('destroyAll with options', function () {
describe('destroyAll with options', function() {
beforeEach(seed);
it('should allow destroyAll(where, options, cb)', function (done) {
User.destroyAll({name: 'John Lennon'}, options, function (err) {
it('should allow destroyAll(where, options, cb)', function(done) {
User.destroyAll({ name: 'John Lennon' }, options, function(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);
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);
data.length.should.equal(1);
done();
@ -453,13 +453,13 @@ describe('crud-with-options', function () {
});
});
it('should allow destroyAll(where, cb)', function (done) {
User.destroyAll({name: 'John Lennon'}, function (err) {
it('should allow destroyAll(where, cb)', function(done) {
User.destroyAll({ name: 'John Lennon' }, function(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);
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);
data.length.should.equal(1);
done();
@ -468,13 +468,13 @@ describe('crud-with-options', function () {
});
});
it('should allow destroyAll(cb)', function (done) {
User.destroyAll(function (err) {
it('should allow destroyAll(cb)', function(done) {
User.destroyAll(function(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);
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);
data.length.should.equal(0);
done();
@ -485,17 +485,17 @@ describe('crud-with-options', function () {
});
describe('updateAll ', function () {
describe('updateAll ', function() {
beforeEach(seed);
it('should allow updateAll(where, data, cb)', function (done) {
User.update({name: 'John Lennon'}, {name: 'John Smith'}, function (err) {
it('should allow updateAll(where, data, cb)', function(done) {
User.update({ name: 'John Lennon' }, { name: 'John Smith' }, function(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);
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);
data.length.should.equal(1);
done();
@ -505,13 +505,13 @@ describe('crud-with-options', function () {
});
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) {
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);
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);
data.length.should.equal(1);
done();
@ -520,12 +520,12 @@ describe('crud-with-options', function () {
});
});
it('should allow updateAll(data, cb)', function (done) {
User.update({name: 'John Smith'}, function () {
User.find({where: {name: 'John Lennon'}}, function (err, data) {
it('should allow updateAll(data, cb)', function(done) {
User.update({ name: 'John Smith' }, function() {
User.find({ where: { name: 'John Lennon' }}, function(err, data) {
should.not.exist(err);
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);
data.length.should.equal(6);
done();
@ -547,7 +547,7 @@ function seed(done) {
role: 'lead',
birthday: new Date('1980-12-08'),
order: 2,
vip: true
vip: true,
},
{
seq: 1,
@ -556,18 +556,18 @@ function seed(done) {
role: 'lead',
birthday: new Date('1942-06-18'),
order: 1,
vip: true
vip: true,
},
{seq: 2, name: 'George Harrison', order: 5, vip: false},
{seq: 3, name: 'Ringo Starr', order: 6, vip: false},
{seq: 4, name: 'Pete Best', order: 4},
{seq: 5, name: 'Stuart Sutcliffe', order: 3, vip: true}
{ seq: 2, name: 'George Harrison', order: 5, vip: false },
{ seq: 3, name: 'Ringo Starr', order: 6, vip: false },
{ seq: 4, name: 'Pete Best', order: 4 },
{ seq: 5, name: 'Stuart Sutcliffe', order: 3, vip: true },
];
async.series([
User.destroyAll.bind(User),
function(cb) {
async.each(beatles, User.create.bind(User), cb);
}
},
], done);
}

View File

@ -19,7 +19,7 @@ describe('DataSource', function() {
// this is what LoopBack does
return new DataSource({
name: 'dsname',
connector: throwingConnector
connector: throwingConnector,
});
}).should.throw(/loopback-connector-throwing/);
});

View File

@ -8,9 +8,9 @@ var should = require('./init.js');
var db, Model;
describe('datatypes', function () {
describe('datatypes', function() {
before(function (done) {
before(function(done) {
db = getSchema();
Nested = db.define('Nested', {});
@ -19,45 +19,45 @@ describe('datatypes', function () {
date: Date,
num: Number,
bool: Boolean,
list: {type: [String]},
list: { type: [String] },
arr: Array,
nested: Nested
nested: Nested,
});
db.automigrate(['Model'], done);
});
it('should return 400 when property of type array is set to string value',
function (done) {
function(done) {
var myModel = db.define('myModel', {
list: { type: ['object'] }
list: { type: ['object'] },
});
(function(){
(function() {
myModel.create({ list: 'This string will crash the server' });
}).should.throw({ statusCode: 400 });
done();
});
});
it('should return 400 when property of type array is set to object value',
function (done) {
function(done) {
var myModel = db.define('myModel', {
list: { type: ['object'] }
list: { type: ['object'] },
});
(function(){
myModel.create({ list: { key: 'This string will crash the server' } });
(function() {
myModel.create({ list: { key: 'This string will crash the server' }});
}).should.throw({ statusCode: 400 });
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;
Model.create({
str: 'hello', date: d, num: '3', bool: 1, list: ['test'], arr: [1, 'str']
}, function (err, m) {
str: 'hello', date: d, num: '3', bool: 1, list: ['test'], arr: [1, 'str'],
}, function(err, m) {
should.not.exists(err);
should.exist(m && m.id);
m.str.should.be.type('string');
@ -71,7 +71,7 @@ describe('datatypes', function () {
});
function testFind(next) {
Model.findById(id, function (err, m) {
Model.findById(id, function(err, m) {
should.not.exist(err);
should.exist(m);
m.str.should.be.type('string');
@ -87,7 +87,7 @@ describe('datatypes', function () {
}
function testAll() {
Model.findOne(function (err, m) {
Model.findOne(function(err, m) {
should.not.exist(err);
should.exist(m);
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;
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.exist(m && m.id);
@ -114,7 +114,7 @@ describe('datatypes', function () {
m.num.should.be.type('number');
m.bool.should.be.type('boolean');
id = m.id;
testDataInDB(function () {
testDataInDB(function() {
testUpdate(function() {
testDataInDB(done);
});
@ -127,8 +127,8 @@ describe('datatypes', function () {
// update using updateAttributes
m.updateAttributes({
id: m.id, num: '10'
}, function (err, m) {
id: m.id, num: '10',
}, function(err, m) {
should.not.exist(err);
m.num.should.be.type('number');
done();
@ -154,18 +154,18 @@ describe('datatypes', function () {
});
it('should not coerce nested objects into ModelConstructor types', function() {
var coerced = Model._coerce({ nested: { foo: 'bar' } });
coerced.nested.constructor.name.should.equal('Object');
var coerced = Model._coerce({ nested: { foo: 'bar' }});
coerced.nested.constructor.name.should.equal('Object');
});
it('rejects array value converted to NaN for a required property',
function(done) {
db = getSchema();
Model = db.define('RequiredNumber', {
num: { type: Number, required: true }
num: { type: Number, required: true },
});
db.automigrate(['Model'], function () {
Model.create({ num: [1,2,3] }, function(err, inst) {
db.automigrate(['Model'], function() {
Model.create({ num: [1, 2, 3] }, function(err, inst) {
should.exist(err);
err.should.have.property('name').equal('ValidationError');
done();
@ -180,10 +180,10 @@ describe('datatypes', function () {
'TestModel',
{
desc: { type: String, required: false },
stars: { type: Number, required: false }
stars: { type: Number, required: false },
},
{
persistUndefinedAsNull: true
persistUndefinedAsNull: true,
});
isStrict = TestModel.definition.settings.strict;
@ -212,7 +212,7 @@ describe('datatypes', function () {
delete EXPECTED.extra;
}
var data ={ desc: undefined, extra: undefined };
var data = { desc: undefined, extra: undefined };
TestModel.create(data, function(err, created) {
if (err) return done(err);
@ -271,14 +271,14 @@ describe('datatypes', function () {
if (TestModel.dataSource.connector.all.length === 4) {
TestModel.dataSource.connector.all(
TestModel.modelName,
{where: {id: created.id}},
{ where: { id: created.id }},
{},
cb
);
} else {
TestModel.dataSource.connector.all(
TestModel.modelName,
{where: {id: created.id}},
{ where: { id: created.id }},
cb
);
}
@ -294,7 +294,7 @@ describe('datatypes', function () {
inst.__data.dx = undefined;
inst.toObject(false).should.have.properties({
desc: null, stars: null, extra: null, dx: null
desc: null, stars: null, extra: null, dx: null,
});
});
});

View File

@ -18,108 +18,108 @@ var db, Category, Product, Tool, Widget, Thing, Person;
var setupProducts = function(ids, done) {
async.series([
function(next) {
Tool.create({name: 'Tool Z'}, function(err, inst) {
Tool.create({ name: 'Tool Z' }, function(err, inst) {
ids.toolZ = inst.id;
next();
});
},
function(next) {
Widget.create({name: 'Widget Z'}, function(err, inst) {
Widget.create({ name: 'Widget Z' }, function(err, inst) {
ids.widgetZ = inst.id;
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;
next();
});
},
function(next) {
Widget.create({name: 'Widget A'}, function(err, inst) {
Widget.create({ name: 'Widget A' }, function(err, inst) {
ids.widgetA = inst.id;
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;
next();
});
}
},
], done);
};
describe('default scope', function () {
before(function (done) {
describe('default scope', function() {
before(function(done) {
db = getSchema();
Category = db.define('Category', {
name: String
name: String,
});
Product = db.define('Product', {
name: String,
kind: String,
description: String,
active: { type: Boolean, default: true }
active: { type: Boolean, default: true },
}, {
scope: { order: 'name' },
scopes: { active: { where: { active: true } } }
scopes: { active: { where: { active: true }}},
});
Product.lookupModel = function(data) {
var m = this.dataSource.models[data.kind];
if (m.base === this) return m;
return this;
};
Tool = db.define('Tool', Product.definition.properties, {
base: 'Product',
scope: { where: { kind: 'Tool' }, order: 'name' },
scopes: { active: { where: { active: true } } },
mongodb: { collection: 'Product' },
memory: { collection: 'Product' }
base: 'Product',
scope: { where: { kind: 'Tool' }, order: 'name' },
scopes: { active: { where: { active: true }}},
mongodb: { collection: 'Product' },
memory: { collection: 'Product' },
});
Widget = db.define('Widget', Product.definition.properties, {
base: 'Product',
properties: { kind: 'Widget' },
scope: { where: { kind: 'Widget' }, order: 'name' },
scopes: { active: { where: { active: true } } },
mongodb: { collection: 'Product' },
memory: { collection: 'Product' }
base: 'Product',
properties: { kind: 'Widget' },
scope: { where: { kind: 'Widget' }, order: 'name' },
scopes: { active: { where: { active: true }}},
mongodb: { collection: 'Product' },
memory: { collection: 'Product' },
});
Person = db.define('Person', { name: String }, {
scope: { include: 'things' }
scope: { include: 'things' },
});
// inst is only valid for instance methods
// like save, updateAttributes
var scopeFn = function(target, inst) {
return { where: { kind: this.modelName } };
return { where: { kind: this.modelName }};
};
var propertiesFn = function(target, inst) {
return { kind: this.modelName };
};
Thing = db.define('Thing', Product.definition.properties, {
base: 'Product',
attributes: propertiesFn,
scope: scopeFn,
mongodb: { collection: 'Product' },
memory: { collection: 'Product' }
base: 'Product',
attributes: propertiesFn,
scope: scopeFn,
mongodb: { collection: 'Product' },
memory: { collection: 'Product' },
});
Category.hasMany(Product);
Category.hasMany(Tool, {scope: {order: 'name DESC'}});
Category.hasMany(Tool, { scope: { order: 'name DESC' }});
Category.hasMany(Widget);
Category.hasMany(Thing);
Product.belongsTo(Category);
Tool.belongsTo(Category);
Widget.belongsTo(Category);
@ -127,31 +127,31 @@ describe('default scope', function () {
Person.hasMany(Thing);
Thing.belongsTo(Person);
db.automigrate(done);
});
describe('manipulation', function() {
var ids = {};
before(function(done) {
db.automigrate(done);
});
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.kind.should.equal('Tool');
p.setAttributes({ kind: 'ignored' });
p.kind.should.equal('Tool');
p.setAttribute('kind', 'other'); // currently not enforced
p.kind.should.equal('other');
});
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);
p.name.should.equal('Product A');
p.kind.should.equal('Tool');
@ -159,9 +159,9 @@ describe('default scope', 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);
p.name.should.equal('Product B');
p.kind.should.equal('Widget');
@ -169,10 +169,10 @@ describe('default scope', function () {
done();
});
});
it('should update a scoped instance - updateAttributes', function(done) {
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);
p.name.should.equal('Product A');
p.kind.should.equal('Tool');
@ -181,7 +181,7 @@ describe('default scope', function () {
});
});
});
it('should update a scoped instance - save', function(done) {
Tool.findById(ids.productA, function(err, p) {
p.description = 'Something...';
@ -198,28 +198,28 @@ describe('default scope', function () {
});
});
});
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) {
should.not.exist(err);
p.name.should.equal('Product A');
p.kind.should.equal('Tool');
p.description.should.equal('Anything...');
done();
should.not.exist(err);
p.name.should.equal('Product A');
p.kind.should.equal('Tool');
p.description.should.equal('Anything...');
done();
});
});
});
describe('findById', function() {
var ids = {};
before(function (done) {
before(function(done) {
db.automigrate(setupProducts.bind(null, ids, done));
});
it('should apply default scope', function(done) {
Product.findById(ids.toolA, function(err, inst) {
should.not.exist(err);
@ -228,7 +228,7 @@ describe('default scope', function () {
done();
});
});
it('should apply default scope - tool', function(done) {
Tool.findById(ids.toolA, function(err, inst) {
should.not.exist(err);
@ -236,7 +236,7 @@ describe('default scope', function () {
done();
});
});
it('should apply default scope (no match)', function(done) {
Widget.findById(ids.toolA, function(err, inst) {
should.not.exist(err);
@ -244,17 +244,17 @@ describe('default scope', function () {
done();
});
});
});
describe('find', function() {
var ids = {};
before(function (done) {
before(function(done) {
db.automigrate(setupProducts.bind(null, ids, done));
});
it('should apply default scope - order', function(done) {
Product.find(function(err, products) {
should.not.exist(err);
@ -264,17 +264,17 @@ describe('default scope', function () {
products[2].name.should.equal('Widget A');
products[3].name.should.equal('Widget B');
products[4].name.should.equal('Widget Z');
products[0].should.be.instanceof(Product);
products[0].should.be.instanceof(Tool);
products[2].should.be.instanceof(Product);
products[2].should.be.instanceof(Widget);
done();
});
});
it('should apply default scope - order override', function(done) {
Product.find({ order: 'name DESC' }, function(err, products) {
should.not.exist(err);
@ -287,7 +287,7 @@ describe('default scope', function () {
done();
});
});
it('should apply default scope - tool', function(done) {
Tool.find(function(err, products) {
should.not.exist(err);
@ -297,9 +297,9 @@ describe('default scope', 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);
products.should.have.length(2);
products[0].name.should.equal('Widget A');
@ -307,7 +307,7 @@ describe('default scope', function () {
done();
});
});
it('should apply default scope - order (widget)', function(done) {
Widget.find({ order: 'name DESC' }, function(err, products) {
should.not.exist(err);
@ -318,17 +318,17 @@ describe('default scope', function () {
done();
});
});
});
describe('exists', function() {
var ids = {};
before(function (done) {
before(function(done) {
db.automigrate(setupProducts.bind(null, ids, done));
});
it('should apply default scope', function(done) {
Product.exists(ids.widgetA, function(err, exists) {
should.not.exist(err);
@ -336,7 +336,7 @@ describe('default scope', function () {
done();
});
});
it('should apply default scope - tool', function(done) {
Tool.exists(ids.toolZ, function(err, exists) {
should.not.exist(err);
@ -344,7 +344,7 @@ describe('default scope', function () {
done();
});
});
it('should apply default scope - widget', function(done) {
Widget.exists(ids.widgetA, function(err, exists) {
should.not.exist(err);
@ -352,7 +352,7 @@ describe('default scope', function () {
done();
});
});
it('should apply default scope - tool (no match)', function(done) {
Tool.exists(ids.widgetA, function(err, exists) {
should.not.exist(err);
@ -360,7 +360,7 @@ describe('default scope', function () {
done();
});
});
it('should apply default scope - widget (no match)', function(done) {
Widget.exists(ids.toolZ, function(err, exists) {
should.not.exist(err);
@ -368,17 +368,17 @@ describe('default scope', function () {
done();
});
});
});
describe('count', function() {
var ids = {};
before(function (done) {
before(function(done) {
db.automigrate(setupProducts.bind(null, ids, done));
});
it('should apply default scope - order', function(done) {
Product.count(function(err, count) {
should.not.exist(err);
@ -386,7 +386,7 @@ describe('default scope', function () {
done();
});
});
it('should apply default scope - tool', function(done) {
Tool.count(function(err, count) {
should.not.exist(err);
@ -394,7 +394,7 @@ describe('default scope', function () {
done();
});
});
it('should apply default scope - widget', function(done) {
Widget.count(function(err, count) {
should.not.exist(err);
@ -402,29 +402,29 @@ describe('default scope', 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);
count.should.equal(1);
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);
count.should.equal(0);
done();
});
});
});
describe('removeById', function() {
var ids = {};
function isDeleted(id, done) {
Product.exists(id, function(err, exists) {
should.not.exist(err);
@ -432,25 +432,25 @@ describe('default scope', function () {
done();
});
};
before(function (done) {
before(function(done) {
db.automigrate(setupProducts.bind(null, ids, done));
});
it('should apply default scope', function(done) {
Product.removeById(ids.widgetZ, function(err) {
should.not.exist(err);
isDeleted(ids.widgetZ, done);
});
});
it('should apply default scope - tool', function(done) {
Tool.removeById(ids.toolA, function(err) {
should.not.exist(err);
isDeleted(ids.toolA, done);
});
});
it('should apply default scope - no match', function(done) {
Tool.removeById(ids.widgetA, function(err) {
should.not.exist(err);
@ -461,14 +461,14 @@ describe('default scope', function () {
});
});
});
it('should apply default scope - widget', function(done) {
Widget.removeById(ids.widgetA, function(err) {
should.not.exist(err);
isDeleted(ids.widgetA, done);
});
});
it('should apply default scope - verify', function(done) {
Product.find(function(err, products) {
should.not.exist(err);
@ -478,21 +478,21 @@ describe('default scope', function () {
done();
});
});
});
describe('update', function() {
var ids = {};
before(function (done) {
before(function(done) {
db.automigrate(setupProducts.bind(null, ids, 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);
Widget.find({where: { active: true }}, function(err, products) {
Widget.find({ where: { active: true }}, function(err, products) {
should.not.exist(err);
products.should.have.length(3);
products[0].name.should.equal('Widget A');
@ -502,9 +502,9 @@ describe('default scope', function () {
});
});
});
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);
Product.findById(ids.widgetA, function(err, product) {
should.not.exist(err);
@ -513,9 +513,9 @@ describe('default scope', function () {
});
});
});
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);
products.should.have.length(4);
products[0].name.should.equal('Tool Z');
@ -525,19 +525,19 @@ describe('default scope', function () {
done();
});
});
});
describe('remove', function() {
var ids = {};
before(function (done) {
before(function(done) {
db.automigrate(setupProducts.bind(null, ids, 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);
Product.find(function(err, products) {
products.should.have.length(4);
@ -549,9 +549,9 @@ describe('default scope', function () {
});
});
});
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);
Product.find(function(err, products) {
products.should.have.length(4);
@ -563,7 +563,7 @@ describe('default scope', function () {
});
});
});
it('should apply default scope - deleteAll', function(done) {
Tool.deleteAll(function(err) {
should.not.exist(err);
@ -575,9 +575,9 @@ describe('default scope', function () {
});
});
});
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);
Product.find(function(err, products) {
products.should.have.length(3);
@ -588,7 +588,7 @@ describe('default scope', function () {
});
});
});
it('should apply default scope - destroyAll', function(done) {
Widget.destroyAll(function(err) {
should.not.exist(err);
@ -599,17 +599,17 @@ describe('default scope', function () {
});
});
});
});
describe('scopes', function() {
var ids = {};
before(function (done) {
before(function(done) {
db.automigrate(setupProducts.bind(null, ids, done));
});
it('should merge with default scope', function(done) {
Product.active(function(err, products) {
should.not.exist(err);
@ -620,7 +620,7 @@ describe('default scope', function () {
done();
});
});
it('should merge with default scope - tool', function(done) {
Tool.active(function(err, products) {
should.not.exist(err);
@ -629,7 +629,7 @@ describe('default scope', function () {
done();
});
});
it('should merge with default scope - widget', function(done) {
Widget.active(function(err, products) {
should.not.exist(err);
@ -639,89 +639,89 @@ describe('default scope', function () {
done();
});
});
});
describe('scope function', function() {
before(function(done) {
db.automigrate(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.kind.should.equal('Widget');
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.kind.should.equal('Thing');
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.kind.should.equal('Widget');
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.kind.should.equal('Thing');
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[0].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.should.eql(['Thing', 'Widget']);
done();
});
});
});
describe('relations', function() {
var ids = {};
before(function (done) {
before(function(done) {
db.automigrate(done);
});
before(function (done) {
Category.create({name: 'Category A'}, function(err, cat) {
before(function(done) {
Category.create({ name: 'Category A' }, function(err, cat) {
ids.categoryA = cat.id;
async.series([
function(next) {
cat.widgets.create({name: 'Widget B', kind: 'ignored'}, next);
cat.widgets.create({ name: 'Widget B', kind: 'ignored' }, next);
},
function(next) {
cat.widgets.create({name: 'Widget A'}, next);
cat.widgets.create({ name: 'Widget A' }, next);
},
function(next) {
cat.tools.create({name: 'Tool A'}, next);
cat.tools.create({ name: 'Tool A' }, next);
},
function(next) {
cat.things.create({name: 'Thing A'}, next);
}
cat.things.create({ name: 'Thing A' }, next);
},
], done);
});
});
it('should apply default scope - products', function(done) {
Category.findById(ids.categoryA, function(err, cat) {
should.not.exist(err);
@ -732,21 +732,21 @@ describe('default scope', function () {
products[1].name.should.equal('Tool A');
products[2].name.should.equal('Widget A');
products[3].name.should.equal('Widget B');
products[0].should.be.instanceof(Product);
products[0].should.be.instanceof(Thing);
products[1].should.be.instanceof(Product);
products[1].should.be.instanceof(Tool);
products[2].should.be.instanceof(Product);
products[2].should.be.instanceof(Widget);
done();
});
});
});
it('should apply default scope - widgets', function(done) {
Category.findById(ids.categoryA, function(err, cat) {
should.not.exist(err);
@ -763,7 +763,7 @@ describe('default scope', function () {
});
});
});
it('should apply default scope - tools', function(done) {
Category.findById(ids.categoryA, function(err, cat) {
should.not.exist(err);
@ -779,7 +779,7 @@ describe('default scope', function () {
});
});
});
it('should apply default scope - things', function(done) {
Category.findById(ids.categoryA, function(err, cat) {
should.not.exist(err);
@ -795,13 +795,13 @@ describe('default scope', function () {
});
});
});
it('should create related item with default scope', function(done) {
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) {
Category.findById(ids.categoryA, function(err, cat) {
should.not.exist(err);
@ -819,11 +819,11 @@ describe('default scope', function () {
describe('with include option', function() {
before(function (done) {
before(function(done) {
db.automigrate(done);
});
before(function (done) {
before(function(done) {
Person.create({ id: 1, name: 'Person A' }, function(err, person) {
person.things.create({ name: 'Thing A' }, done);
});

View File

@ -8,45 +8,45 @@ var should = require('./init.js');
var db = getSchema();
describe('defaults', function () {
describe('defaults', function() {
var Server;
before(function () {
before(function() {
Server = db.define('Server', {
host: String,
port: {type: Number, default: 80},
createdAt: {type: Date, default: '$now'}
port: { type: Number, default: 80 },
createdAt: { type: Date, default: '$now' },
});
});
it('should apply defaults on new', function () {
it('should apply defaults on new', function() {
var s = new Server;
s.port.should.equal(80);
});
it('should apply defaults on create', function (done) {
Server.create(function (err, s) {
it('should apply defaults on create', function(done) {
Server.create(function(err, s) {
s.port.should.equal(80);
done();
});
});
it('should apply defaults on read', function (done) {
it('should apply defaults on read', function(done) {
db.defineProperty('Server', 'host', {
type: String,
default: 'localhost'
default: 'localhost',
});
Server.all(function (err, servers) {
Server.all(function(err, servers) {
(new String('localhost')).should.equal(servers[0].host);
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) {
should.not.exist(err);
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].should.have.property('host');
servers[0].should.have.property('port', undefined);
@ -55,17 +55,17 @@ describe('defaults', function () {
});
});
it('should apply defaults in upsert create', function (done) {
Server.upsert({port: 8181 }, function(err, server) {
it('should apply defaults in upsert create', function(done) {
Server.upsert({ port: 8181 }, function(err, server) {
should.not.exist(err);
should.exist(server.createdAt);
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.upsert({id:server.id, port: 1337 }, function(err, s) {
Server.upsert({ id:server.id, port: 1337 }, function(err, s) {
should.not.exist(err);
(Number(1337)).should.equal(s.port);
server.createdAt.should.eql(s.createdAt);

View File

@ -11,11 +11,11 @@ describe('Memory connector with mocked discovery', function() {
var ds;
before(function() {
ds = new DataSource({connector: 'memory'});
ds = new DataSource({ connector: 'memory' });
var models = [{type: 'table', name: 'CUSTOMER', owner: 'STRONGLOOP'},
{type: 'table', name: 'INVENTORY', owner: 'STRONGLOOP'},
{type: 'table', name: 'LOCATION', owner: 'STRONGLOOP'}];
var models = [{ type: 'table', name: 'CUSTOMER', owner: 'STRONGLOOP' },
{ type: 'table', name: 'INVENTORY', owner: 'STRONGLOOP' },
{ type: 'table', name: 'LOCATION', owner: 'STRONGLOOP' }];
ds.discoverModelDefinitions = function(options, cb) {
process.nextTick(function() {
@ -31,7 +31,7 @@ describe('Memory connector with mocked discovery', function() {
dataLength: 20,
dataPrecision: null,
dataScale: null,
nullable: 0
nullable: 0,
},
{
owner: 'STRONGLOOP',
@ -41,7 +41,7 @@ describe('Memory connector with mocked discovery', function() {
dataLength: 20,
dataPrecision: null,
dataScale: null,
nullable: 0
nullable: 0,
},
{
owner: 'STRONGLOOP',
@ -51,7 +51,7 @@ describe('Memory connector with mocked discovery', function() {
dataLength: null,
dataPrecision: 10,
dataScale: 0,
nullable: 1
nullable: 1,
},
{
owner: 'STRONGLOOP',
@ -61,7 +61,7 @@ describe('Memory connector with mocked discovery', function() {
dataLength: null,
dataPrecision: 10,
dataScale: 0,
nullable: 1
nullable: 1,
}];
ds.discoverModelProperties = function(modelName, options, cb) {
@ -88,7 +88,7 @@ describe('Memory connector with mocked discovery', function() {
nameMapper: function(type, name) {
// Convert all names to lower case
return name.toLowerCase();
}
},
}, function(err, schemas) {
if (err) return done(err);
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',
function(done) {
ds.discoverSchemas('INVENTORY', {nameMapper: null}, function(err, schemas) {
ds.discoverSchemas('INVENTORY', { nameMapper: null }, function(err, schemas) {
if (err) return done(err);
schemas.should.have.property('STRONGLOOP.INVENTORY');
var s = schemas['STRONGLOOP.INVENTORY'];
@ -117,16 +117,16 @@ describe('Memory connector with mocked discovery', function() {
function(done) {
var models = {
inventory: {
product: {type: 'string'},
location: {type: 'string'}
}
product: { type: 'string' },
location: { type: 'string' },
},
};
ds.connector.discoverSchemas = function(modelName, options, cb) {
process.nextTick(function() {
cb(null, models);
});
};
ds.discoverSchemas('INVENTORY', {nameMapper: null}, function(err, schemas) {
ds.discoverSchemas('INVENTORY', { nameMapper: null }, function(err, schemas) {
if (err) return done(err);
schemas.should.be.eql(models);
done();
@ -137,9 +137,9 @@ describe('Memory connector with mocked discovery', function() {
function(done) {
var models = {
inventory: {
product: {type: 'string'},
location: {type: 'string'}
}
product: { type: 'string' },
location: { type: 'string' },
},
};
ds.connector.discoverSchemas = function(modelName, options, cb) {
process.nextTick(function() {
@ -174,9 +174,9 @@ describe('Memory connector with mocked discovery', function() {
.catch(function(err) {
done(err);
});
});
});
describe('discoverSchema', function(){
describe('discoverSchema', function() {
var models;
var schema;
before(function() {
@ -184,7 +184,7 @@ describe('Memory connector with mocked discovery', function() {
name: 'Inventory',
options: {
idInjection: false,
memory: { schema: 'STRONGLOOP', table: 'INVENTORY' }
memory: { schema: 'STRONGLOOP', table: 'INVENTORY' },
},
properties: {
available: {
@ -195,12 +195,12 @@ describe('Memory connector with mocked discovery', function() {
dataPrecision: 10,
dataScale: 0,
dataType: 'int',
nullable: 1
nullable: 1,
},
precision: 10,
required: false,
scale: 0,
type: undefined
type: undefined,
},
locationId: {
length: 20,
@ -210,12 +210,12 @@ describe('Memory connector with mocked discovery', function() {
dataPrecision: null,
dataScale: null,
dataType: 'varchar',
nullable: 0
nullable: 0,
},
precision: null,
required: true,
scale: null,
type: undefined
type: undefined,
},
productId: {
length: 20,
@ -225,12 +225,12 @@ describe('Memory connector with mocked discovery', function() {
dataPrecision: null,
dataScale: null,
dataType: 'varchar',
nullable: 0
nullable: 0,
},
precision: null,
required: true,
scale: null,
type: undefined
type: undefined,
},
total: {
length: null,
@ -240,15 +240,15 @@ describe('Memory connector with mocked discovery', function() {
dataPrecision: 10,
dataScale: 0,
dataType: 'int',
nullable: 1
nullable: 1,
},
precision: 10,
required: false,
scale: 0,
type: undefined
}
}
} ;
type: undefined,
},
},
};
});
it('should discover schema using `discoverSchema`', function(done) {
@ -275,21 +275,21 @@ describe('Memory connector with mocked discovery', function() {
schemas.should.be.eql(schema);
done();
})
.catch(function(err){
.catch(function(err) {
done(err);
});
});
});
});
describe('discoverModelDefinitions', function(){
describe('discoverModelDefinitions', function() {
var ds;
before(function(){
ds = new DataSource({connector: 'memory'});
before(function() {
ds = new DataSource({ connector: 'memory' });
var models = [{type: 'table', name: 'CUSTOMER', owner: 'STRONGLOOP'},
{type: 'table', name: 'INVENTORY', owner: 'STRONGLOOP'},
{type: 'table', name: 'LOCATION', owner: 'STRONGLOOP'}];
var models = [{ type: 'table', name: 'CUSTOMER', owner: 'STRONGLOOP' },
{ type: 'table', name: 'INVENTORY', owner: 'STRONGLOOP' },
{ type: 'table', name: 'LOCATION', owner: 'STRONGLOOP' }];
ds.connector.discoverModelDefinitions = function(options, cb) {
process.nextTick(function() {
@ -307,7 +307,7 @@ describe('discoverModelDefinitions', function(){
});
tableNames.should.be.eql(
["CUSTOMER", "INVENTORY", "LOCATION"]
['CUSTOMER', 'INVENTORY', 'LOCATION']
);
done();
});
@ -322,7 +322,7 @@ describe('discoverModelDefinitions', function(){
});
tableNames.should.be.eql(
["CUSTOMER", "INVENTORY", "LOCATION"]
['CUSTOMER', 'INVENTORY', 'LOCATION']
);
done();
};
@ -338,21 +338,21 @@ describe('discoverModelDefinitions', function(){
});
tableNames.should.be.eql(
["CUSTOMER", "INVENTORY", "LOCATION"]
['CUSTOMER', 'INVENTORY', 'LOCATION']
);
done();
})
.catch(function(err){
.catch(function(err) {
done(err);
});
});
});
describe('discoverModelProperties', function(){
describe('discoverModelProperties', function() {
var ds;
var modelProperties;
before(function(){
ds = new DataSource({connector: 'memory'});
before(function() {
ds = new DataSource({ connector: 'memory' });
modelProperties = [{
owner: 'STRONGLOOP',
@ -362,38 +362,38 @@ describe('discoverModelProperties', function(){
dataLength: 20,
dataPrecision: null,
dataScale: null,
nullable: 0
nullable: 0,
},
{
owner: 'STRONGLOOP',
tableName: 'INVENTORY',
columnName: 'LOCATION_ID',
dataType: 'varchar',
dataLength: 20,
dataPrecision: null,
dataScale: null,
nullable: 0
},
{
owner: 'STRONGLOOP',
tableName: 'INVENTORY',
columnName: 'AVAILABLE',
dataType: 'int',
dataLength: null,
dataPrecision: 10,
dataScale: 0,
nullable: 1
},
{
owner: 'STRONGLOOP',
tableName: 'INVENTORY',
columnName: 'TOTAL',
dataType: 'int',
dataLength: null,
dataPrecision: 10,
dataScale: 0,
nullable: 1
}];
{
owner: 'STRONGLOOP',
tableName: 'INVENTORY',
columnName: 'LOCATION_ID',
dataType: 'varchar',
dataLength: 20,
dataPrecision: null,
dataScale: null,
nullable: 0,
},
{
owner: 'STRONGLOOP',
tableName: 'INVENTORY',
columnName: 'AVAILABLE',
dataType: 'int',
dataLength: null,
dataPrecision: 10,
dataScale: 0,
nullable: 1,
},
{
owner: 'STRONGLOOP',
tableName: 'INVENTORY',
columnName: 'TOTAL',
dataType: 'int',
dataLength: null,
dataPrecision: 10,
dataScale: 0,
nullable: 1,
}];
ds.connector.discoverModelProperties = function(modelName, options, cb) {
process.nextTick(function() {
@ -404,11 +404,11 @@ describe('discoverModelProperties', function(){
it('should callback function, passed as options parameter', function(done) {
var options = function(err, schemas) {
if (err) return done(err);
if (err) return done(err);
schemas.should.be.eql(modelProperties);
done();
};
schemas.should.be.eql(modelProperties);
done();
};
ds.discoverModelProperties('INVENTORY', options);
});
@ -428,32 +428,32 @@ describe('discoverModelProperties', function(){
schemas.should.be.eql(modelProperties);
done();
})
.catch(function(err){
.catch(function(err) {
done(err);
});
});
});
describe('discoverPrimaryKeys', function(){
describe('discoverPrimaryKeys', function() {
var ds;
var modelProperties;
before(function(){
ds = new DataSource({connector: 'memory'});
before(function() {
ds = new DataSource({ connector: 'memory' });
primaryKeys = [
{
{
owner: 'STRONGLOOP',
tableName: 'INVENTORY',
columnName: 'PRODUCT_ID',
keySeq: 1,
pkName: 'ID_PK'
},
{
pkName: 'ID_PK',
},
{
owner: 'STRONGLOOP',
tableName: 'INVENTORY',
columnName: 'LOCATION_ID',
keySeq: 2,
pkName: 'ID_PK'
pkName: 'ID_PK',
}];
ds.connector.discoverPrimaryKeys = function(modelName, options, cb) {
@ -488,19 +488,19 @@ describe('discoverPrimaryKeys', function(){
modelPrimaryKeys.should.be.eql(primaryKeys);
done();
})
.catch(function(err){
.catch(function(err) {
done(err);
});
});
});
describe('discoverForeignKeys', function(){
describe('discoverForeignKeys', function() {
var ds;
var modelProperties;
before(function(){
ds = new DataSource({connector: 'memory'});
before(function() {
ds = new DataSource({ connector: 'memory' });
foreignKeys = [{
foreignKeys = [{
fkOwner: 'STRONGLOOP',
fkName: 'PRODUCT_FK',
fkTableName: 'INVENTORY',
@ -509,7 +509,7 @@ describe('discoverForeignKeys', function(){
pkOwner: 'STRONGLOOP',
pkName: 'PRODUCT_PK',
pkTableName: 'PRODUCT',
pkColumnName: 'ID'
pkColumnName: 'ID',
}];
ds.connector.discoverForeignKeys = function(modelName, options, cb) {
@ -545,17 +545,17 @@ describe('discoverForeignKeys', function(){
modelForeignKeys.should.be.eql(foreignKeys);
done();
})
.catch(function(err){
.catch(function(err) {
done(err);
});
});
});
describe('discoverExportedForeignKeys', function(){
describe('discoverExportedForeignKeys', function() {
var ds;
var modelProperties;
before(function(){
ds = new DataSource({connector: 'memory'});
before(function() {
ds = new DataSource({ connector: 'memory' });
exportedForeignKeys = [{
fkName: 'PRODUCT_FK',
@ -566,7 +566,7 @@ describe('discoverExportedForeignKeys', function(){
pkName: 'PRODUCT_PK',
pkOwner: 'STRONGLOOP',
pkTableName: 'PRODUCT',
pkColumnName: 'ID'
pkColumnName: 'ID',
}];
ds.connector.discoverExportedForeignKeys = function(modelName, options, cb) {
@ -602,7 +602,7 @@ describe('discoverExportedForeignKeys', function(){
modelForeignKeys.should.be.eql(exportedForeignKeys);
done();
})
.catch(function(err){
.catch(function(err) {
done(err);
});
});

View File

@ -11,9 +11,9 @@ describe('events', function() {
this.db = getSchema();
this.TestModel = this.db.define('TestModel');
this.db.automigrate(function(err) {
if(err) return done(err);
if (err) return done(err);
test.TestModel.create(function(err, inst) {
if(err) return done(err);
if (err) return done(err);
test.inst = inst;
done();
});
@ -23,30 +23,30 @@ describe('events', function() {
listener.apply(this, arguments);
done();
});
}
};
});
describe('changed', function() {
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);
model.save();
});
it('should be emitted after upsert', function(done) {
this.shouldEmitEvent('changed', assertValidChangedArgs, done);
this.TestModel.upsert({name: 'batbaz'});
this.TestModel.upsert({ name: 'batbaz' });
});
it('should be emitted after create', function(done) {
this.shouldEmitEvent('changed', assertValidChangedArgs, done);
this.TestModel.create({name: '...'});
this.TestModel.create({ name: '...' });
});
it('should be emitted after updateAttributes', function(done) {
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"
process.nextTick(function() {
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) {
where.name.should.equal('foo');
}, done);
this.TestModel.destroyAll({name: 'foo'});
this.TestModel.destroyAll({ name: 'foo' });
});
});
});

View File

@ -11,39 +11,39 @@ require('should');
var GeoPoint = require('../lib/geo').GeoPoint;
var DELTA = 0.0000001;
describe('GeoPoint', function () {
describe('GeoPoint', function() {
describe('constructor', function() {
it('should support a valid array', function () {
it('should support a valid array', function() {
var point = new GeoPoint([-34, 150]);
point.lat.should.equal(-34);
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 });
point.lat.should.equal(-34);
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');
point.lat.should.equal(-34);
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);
point.lat.should.equal(-34);
point.lng.should.equal(150);
});
it('should reject invalid parameters', function () {
it('should reject invalid parameters', function() {
/*jshint -W024 */
var fn = function() {
new GeoPoint('150,-34');
@ -63,7 +63,7 @@ describe('GeoPoint', function () {
fn = function() {
new GeoPoint({
lat: 150,
lng: null
lng: null,
});
};
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 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);
distance.should.be.a.Number;
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:
* - `radians`
@ -114,27 +114,27 @@ describe('GeoPoint', function () {
* - `degrees`
*/
var distance = here.distanceTo(there, { type: 'radians'});
var distance = here.distanceTo(there, { type: 'radians' });
distance.should.be.a.Number;
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.approximately(0.04985613511367009, DELTA);
distance = here.distanceTo(there, { type: 'meters'});
distance = here.distanceTo(there, { type: 'meters' });
distance.should.be.a.Number;
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.approximately(0.03097916611592679, DELTA);
distance = here.distanceTo(there, { type: 'feet'});
distance = here.distanceTo(there, { type: 'feet' });
distance.should.be.a.Number;
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.approximately(0.0004483676593058972, DELTA);
});

View File

@ -13,42 +13,42 @@ var j = require('../'),
db, User;
describe('hooks', function () {
describe('hooks', function() {
before(function (done) {
before(function(done) {
db = getSchema();
User = db.define('User', {
email: {type: String, index: true},
email: { type: String, index: true },
name: String,
password: String,
state: String
state: String,
});
db.automigrate('User', done);
});
describe('initialize', function () {
describe('initialize', function() {
afterEach(function () {
afterEach(function() {
User.afterInitialize = null;
});
it('should be triggered on new', function (done) {
User.afterInitialize = function () {
it('should be triggered on new', function(done) {
User.afterInitialize = function() {
done();
};
new User;
});
it('should be triggered on create', function (done) {
it('should be triggered on create', function(done) {
var user;
User.afterInitialize = function () {
User.afterInitialize = function() {
if (this.name === 'Nickolay') {
this.name += ' Rozental';
}
};
User.create({name: 'Nickolay'}, function (err, u) {
User.create({ name: 'Nickolay' }, function(err, u) {
u.id.should.be.ok;
u.name.should.equal('Nickolay Rozental');
done();
@ -57,116 +57,116 @@ describe('hooks', function () {
});
describe('create', function () {
describe('create', function() {
afterEach(removeHooks('Create'));
it('should be triggered on create', function (done) {
it('should be triggered on create', function(done) {
addHooks('Create', done);
User.create();
});
it('should not be triggered on new', function () {
User.beforeCreate = function (next) {
it('should not be triggered on new', function() {
User.beforeCreate = function(next) {
should.fail('This should not be called');
next();
};
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);
(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;
User.dataSource.connector.create = function (modelName, id, cb) {
User.dataSource.connector.create = function(modelName, id, cb) {
cb(new Error('error'));
}
};
User.afterCreate = function () {
User.afterCreate = function() {
throw new Error('shouldn\'t be called');
};
User.create(function (err, user) {
User.create(function(err, user) {
User.dataSource.connector.create = old;
done();
});
});
it('afterCreate should not be triggered on failed beforeCreate', function (done) {
User.beforeCreate = function (next, data) {
it('afterCreate should not be triggered on failed beforeCreate', function(done) {
User.beforeCreate = function(next, data) {
// Skip next()
next(new Error('fail in beforeCreate'));
};
var old = User.dataSource.connector.create;
User.dataSource.connector.create = function (modelName, id, cb) {
throw new Error('shouldn\'t be called');
}
User.afterCreate = function () {
User.dataSource.connector.create = function(modelName, id, cb) {
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;
done();
});
});
});
describe('save', function () {
describe('save', function() {
afterEach(removeHooks('Save'));
it('should be triggered on create', function (done) {
it('should be triggered on create', function(done) {
addHooks('Save', done);
User.create();
});
it('should be triggered on new+save', function (done) {
it('should be triggered on new+save', function(done) {
addHooks('Save', done);
(new User).save();
});
it('should be triggered on updateAttributes', function (done) {
User.create(function (err, user) {
it('should be triggered on updateAttributes', function(done) {
User.create(function(err, user) {
addHooks('Save', done);
user.updateAttributes({name: 'Anatoliy'});
user.updateAttributes({ name: 'Anatoliy' });
});
});
it('should be triggered on save', function (done) {
User.create(function (err, user) {
it('should be triggered on save', function(done) {
User.create(function(err, user) {
addHooks('Save', done);
user.name = 'Hamburger';
user.save();
});
});
it('should save full object', function (done) {
User.create(function (err, user) {
User.beforeSave = function (next, data) {
it('should save full object', function(done) {
User.create(function(err, user) {
User.beforeSave = function(next, data) {
data.should.have.keys('id', 'name', 'email',
'password', 'state')
'password', 'state');
done();
};
user.save();
});
});
it('should save actual modifications to database', function (done) {
User.beforeSave = function (next, data) {
it('should save actual modifications to database', function(done) {
User.beforeSave = function(next, data) {
data.password = 'hash';
next();
};
User.destroyAll(function () {
User.destroyAll(function() {
User.create({
email: 'james.bond@example.com',
password: '53cr3t'
}, function () {
password: '53cr3t',
}, function() {
User.findOne({
where: {email: 'james.bond@example.com'}
}, function (err, jb) {
where: { email: 'james.bond@example.com' },
}, function(err, jb) {
jb.password.should.equal('hash');
done();
});
@ -174,22 +174,22 @@ describe('hooks', function () {
});
});
it('should save actual modifications on updateAttributes', function (done) {
User.beforeSave = function (next, data) {
it('should save actual modifications on updateAttributes', function(done) {
User.beforeSave = function(next, data) {
data.password = 'hash';
next();
};
User.destroyAll(function () {
User.destroyAll(function() {
User.create({
email: 'james.bond@example.com'
}, function (err, u) {
u.updateAttribute('password', 'new password', function (e, u) {
email: 'james.bond@example.com',
}, function(err, u) {
u.updateAttribute('password', 'new password', function(e, u) {
should.not.exist(e);
should.exist(u);
u.password.should.equal('hash');
User.findOne({
where: {email: 'james.bond@example.com'}
}, function (err, jb) {
where: { email: 'james.bond@example.com' },
}, function(err, jb) {
jb.password.should.equal('hash');
done();
});
@ -198,9 +198,9 @@ describe('hooks', function () {
});
});
it('beforeSave should be able to skip next', function (done) {
User.create(function (err, user) {
User.beforeSave = function (next, data) {
it('beforeSave should be able to skip next', function(done) {
User.create(function(err, user) {
User.beforeSave = function(next, data) {
next(null, 'XYZ');
};
user.save(function(err, result) {
@ -212,97 +212,97 @@ describe('hooks', function () {
});
describe('update', function () {
describe('update', function() {
afterEach(removeHooks('Update'));
it('should not be triggered on create', function () {
User.beforeUpdate = function (next) {
it('should not be triggered on create', function() {
User.beforeUpdate = function(next) {
should.fail('This should not be called');
next();
};
User.create();
});
it('should not be triggered on new+save', function () {
User.beforeUpdate = function (next) {
it('should not be triggered on new+save', function() {
User.beforeUpdate = function(next) {
should.fail('This should not be called');
next();
};
(new User).save();
});
it('should be triggered on updateAttributes', function (done) {
User.create(function (err, user) {
it('should be triggered on updateAttributes', function(done) {
User.create(function(err, user) {
addHooks('Update', done);
user.updateAttributes({name: 'Anatoliy'});
user.updateAttributes({ name: 'Anatoliy' });
});
});
it('should be triggered on save', function (done) {
User.create(function (err, user) {
it('should be triggered on save', function(done) {
User.create(function(err, user) {
addHooks('Update', done);
user.name = 'Hamburger';
user.save();
});
});
it('should update limited set of fields', function (done) {
User.create(function (err, user) {
User.beforeUpdate = function (next, data) {
it('should update limited set of fields', function(done) {
User.create(function(err, user) {
User.beforeUpdate = function(next, data) {
data.should.have.keys('name', 'email');
done();
};
user.updateAttributes({name: 1, email: 2});
user.updateAttributes({ name: 1, email: 2 });
});
});
it('should not trigger after-hook on failed save', function (done) {
User.afterUpdate = function () {
it('should not trigger after-hook on failed save', function(done) {
User.afterUpdate = function() {
should.fail('afterUpdate shouldn\'t be called');
};
User.create(function (err, user) {
User.create(function(err, user) {
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;
cb(new Error('Error'));
}
};
user.save(function (err) {
user.save(function(err) {
done();
});
});
});
});
describe('destroy', function () {
describe('destroy', function() {
afterEach(removeHooks('Destroy'));
it('should be triggered on destroy', function (done) {
it('should be triggered on destroy', function(done) {
var hook = 'not called';
User.beforeDestroy = function (next) {
User.beforeDestroy = function(next) {
hook = 'called';
next();
};
User.afterDestroy = function (next) {
User.afterDestroy = function(next) {
hook.should.eql('called');
next();
};
User.create(function (err, user) {
User.create(function(err, user) {
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;
User.dataSource.connector.destroy = function (modelName, id, cb) {
User.dataSource.connector.destroy = function(modelName, id, cb) {
cb(new Error('error'));
}
User.afterDestroy = function () {
should.fail('afterDestroy shouldn\'t be called')
};
User.create(function (err, user) {
user.destroy(function (err) {
User.afterDestroy = function() {
should.fail('afterDestroy shouldn\'t be called');
};
User.create(function(err, user) {
user.destroy(function(err) {
User.dataSource.connector.destroy = destroy;
done();
});
@ -311,64 +311,64 @@ describe('hooks', function () {
});
describe('lifecycle', function () {
describe('lifecycle', function() {
var life = [], user;
before(function (done) {
User.beforeSave = function (d) {
before(function(done) {
User.beforeSave = function(d) {
life.push('beforeSave');
d();
};
User.beforeCreate = function (d) {
User.beforeCreate = function(d) {
life.push('beforeCreate');
d();
};
User.beforeUpdate = function (d) {
User.beforeUpdate = function(d) {
life.push('beforeUpdate');
d();
};
User.beforeDestroy = function (d) {
User.beforeDestroy = function(d) {
life.push('beforeDestroy');
d();
};
User.beforeValidate = function (d) {
User.beforeValidate = function(d) {
life.push('beforeValidate');
d();
};
User.afterInitialize = function () {
User.afterInitialize = function() {
life.push('afterInitialize');
};
User.afterSave = function (d) {
User.afterSave = function(d) {
life.push('afterSave');
d();
};
User.afterCreate = function (d) {
User.afterCreate = function(d) {
life.push('afterCreate');
d();
};
User.afterUpdate = function (d) {
User.afterUpdate = function(d) {
life.push('afterUpdate');
d();
};
User.afterDestroy = function (d) {
User.afterDestroy = function(d) {
life.push('afterDestroy');
d();
};
User.afterValidate = function (d) {
User.afterValidate = function(d) {
life.push('afterValidate');
d();
};
User.create(function (e, u) {
User.create(function(e, u) {
user = u;
life = [];
done();
});
});
beforeEach(function () {
beforeEach(function() {
life = [];
});
it('should describe create sequence', function (done) {
User.create(function () {
it('should describe create sequence', function(done) {
User.create(function() {
life.should.eql([
'afterInitialize',
'beforeValidate',
@ -376,15 +376,15 @@ describe('hooks', function () {
'beforeCreate',
'beforeSave',
'afterSave',
'afterCreate'
'afterCreate',
]);
done();
});
});
it('should describe new+save sequence', function (done) {
it('should describe new+save sequence', function(done) {
var u = new User;
u.save(function () {
u.save(function() {
life.should.eql([
'afterInitialize',
'beforeValidate',
@ -392,14 +392,14 @@ describe('hooks', function () {
'beforeCreate',
'beforeSave',
'afterSave',
'afterCreate'
'afterCreate',
]);
done();
});
});
it('should describe updateAttributes sequence', function (done) {
user.updateAttributes({name: 'Antony'}, function () {
it('should describe updateAttributes sequence', function(done) {
user.updateAttributes({ name: 'Antony' }, function() {
life.should.eql([
'beforeValidate',
'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(
user.constructor._validations,
'Expected user to have no validations, but she have');
user.isValid(function (valid) {
user.isValid(function(valid) {
valid.should.be.true;
life.should.eql([
'beforeValidate',
'afterValidate'
'afterValidate',
]);
done();
});
});
it('should describe destroy sequence', function (done) {
user.destroy(function () {
it('should describe destroy sequence', function(done) {
user.destroy(function() {
life.should.eql([
'beforeDestroy',
'afterDestroy'
'afterDestroy',
]);
done();
});
@ -443,12 +443,12 @@ describe('hooks', function () {
function addHooks(name, done) {
var called = false, random = String(Math.floor(Math.random() * 1000));
User['before' + name] = function (next, data) {
User['before' + name] = function(next, data) {
called = true;
data.email = random;
next();
};
User['after' + name] = function (next) {
User['after' + name] = function(next) {
(new Boolean(called)).should.equal(true);
this.should.have.property('email', random);
done();
@ -456,7 +456,7 @@ function addHooks(name, done) {
}
function removeHooks(name) {
return function () {
return function() {
User['after' + name] = null;
User['before' + name] = null;
};

View File

@ -12,14 +12,14 @@ var DataSource = require('../').DataSource;
var db, User, Profile, AccessToken, Post, Passport, City, Street, Building, Assembly, Part;
describe('include', function () {
describe('include', function() {
before(setup);
it('should fetch belongsTo relation', function (done) {
Passport.find({include: 'owner'}, function (err, passports) {
it('should fetch belongsTo relation', function(done) {
Passport.find({ include: 'owner' }, function(err, passports) {
passports.length.should.be.ok;
passports.forEach(function (p) {
passports.forEach(function(p) {
p.__cachedRelations.should.have.property('owner');
// The relation should be promoted as the 'owner' property
@ -39,19 +39,19 @@ describe('include', function () {
});
});
it('should fetch hasMany relation', function (done) {
User.find({include: 'posts'}, function (err, users) {
it('should fetch hasMany relation', function(done) {
User.find({ include: 'posts' }, function(err, users) {
should.not.exist(err);
should.exist(users);
users.length.should.be.ok;
users.forEach(function (u) {
users.forEach(function(u) {
// The relation should be promoted as the 'owner' property
u.should.have.property('posts');
// The __cachedRelations should be removed from json output
u.toJSON().should.not.have.property('__cachedRelations');
u.__cachedRelations.should.have.property('posts');
u.__cachedRelations.posts.forEach(function (p) {
u.__cachedRelations.posts.forEach(function(p) {
p.userId.should.eql(u.id);
});
});
@ -59,13 +59,13 @@ describe('include', function () {
});
});
it('should fetch Passport - Owner - Posts', function (done) {
Passport.find({include: {owner: 'posts'}}, function (err, passports) {
it('should fetch Passport - Owner - Posts', function(done) {
Passport.find({ include: { owner: 'posts' }}, function(err, passports) {
should.not.exist(err);
should.exist(passports);
passports.length.should.be.ok;
passports.forEach(function (p) {
passports.forEach(function(p) {
p.__cachedRelations.should.have.property('owner');
// The relation should be promoted as the 'owner' property
@ -82,7 +82,7 @@ describe('include', function () {
user.__cachedRelations.should.have.property('posts');
user.should.have.property('posts');
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);
});
}
@ -91,8 +91,8 @@ describe('include', function () {
});
});
it('should fetch Passport - Owner - empty Posts', function (done) {
Passport.findOne({where: {number: '4'}, include: {owner: 'posts'}}, function (err, passport) {
it('should fetch Passport - Owner - empty Posts', function(done) {
Passport.findOne({ where: { number: '4' }, include: { owner: 'posts' }}, function(err, passport) {
should.not.exist(err);
should.exist(passport);
passport.__cachedRelations.should.have.property('owner');
@ -113,8 +113,8 @@ describe('include', function () {
});
});
it('should fetch Passport - Owner - Posts - alternate syntax', function (done) {
Passport.find({include: {owner: {relation: 'posts'}}}, function (err, passports) {
it('should fetch Passport - Owner - Posts - alternate syntax', function(done) {
Passport.find({ include: { owner: { relation: 'posts' }}}, function(err, passports) {
should.not.exist(err);
should.exist(passports);
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({
include: {owner: {posts: 'author'}}
}, function (err, passports) {
include: { owner: { posts: 'author' }},
}, function(err, passports) {
should.not.exist(err);
should.exist(passports);
passports.length.should.be.ok;
passports.forEach(function (p) {
passports.forEach(function(p) {
p.__cachedRelations.should.have.property('owner');
var user = p.__cachedRelations.owner;
if (!p.ownerId) {
@ -140,7 +140,7 @@ describe('include', function () {
should.exist(user);
user.id.should.eql(p.ownerId);
user.__cachedRelations.should.have.property('posts');
user.__cachedRelations.posts.forEach(function (pp) {
user.__cachedRelations.posts.forEach(function(pp) {
pp.should.have.property('id');
pp.userId.should.eql(user.id);
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({
include: {owner: {relation: 'posts', scope:{
include: { owner: { relation: 'posts', scope:{
fields: ['title'], include: ['author'],
order: 'title DESC'
}}}
}, function (err, passports) {
order: 'title DESC',
}}},
}, function(err, passports) {
should.not.exist(err);
should.exist(passports);
passports.length.should.equal(4);
@ -196,11 +196,11 @@ describe('include', function () {
relation: 'posts', scope: {
fields: ['title'], include: ['author'],
order: 'title DESC',
limit: 2
}
}
limit: 2,
},
},
},
limit: 1
limit: 1,
}, function(err, passports) {
if (err) return done(err);
passports.length.should.equal(1);
@ -209,29 +209,29 @@ describe('include', function () {
});
});
it('should fetch Users with include scope on Posts - belongsTo', function (done) {
Post.find({
include: { relation: 'author', scope:{ fields: ['name'] }}
}, function (err, posts) {
should.not.exist(err);
should.exist(posts);
posts.length.should.equal(5);
it('should fetch Users with include scope on Posts - belongsTo', function(done) {
Post.find({
include: { relation: 'author', scope:{ fields: ['name'] }},
}, function(err, posts) {
should.not.exist(err);
should.exist(posts);
posts.length.should.equal(5);
var author = posts[0].author();
author.name.should.equal('User A');
author.should.have.property('id');
author.should.have.property('age', undefined);
var author = posts[0].author();
author.name.should.equal('User A');
author.should.have.property('id');
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({
include: {relation: 'posts', scope:{
order: 'title DESC'
}}
}, function (err, users) {
include: { relation: 'posts', scope:{
order: 'title DESC',
}},
}, function(err, users) {
should.not.exist(err);
should.exist(users);
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({
include: {relation: 'passports', scope:{
where: { number: '2' }
}}
}, function (err, users) {
include: { relation: 'passports', scope:{
where: { number: '2' },
}},
}, function(err, users) {
should.not.exist(err);
should.exist(users);
users.length.should.equal(5);
@ -277,12 +277,12 @@ describe('include', function () {
});
});
it('should fetch User - Posts AND Passports', function (done) {
User.find({include: ['posts', 'passports']}, function (err, users) {
it('should fetch User - Posts AND Passports', function(done) {
User.find({ include: ['posts', 'passports'] }, function(err, users) {
should.not.exist(err);
should.exist(users);
users.length.should.be.ok;
users.forEach(function (user) {
users.forEach(function(user) {
// The relation should be promoted as the 'owner' property
user.should.have.property('posts');
user.should.have.property('passports');
@ -298,10 +298,10 @@ describe('include', function () {
user.__cachedRelations.should.have.property('posts');
user.__cachedRelations.should.have.property('passports');
user.__cachedRelations.posts.forEach(function (p) {
user.__cachedRelations.posts.forEach(function(p) {
p.userId.should.eql(user.id);
});
user.__cachedRelations.passports.forEach(function (pp) {
user.__cachedRelations.passports.forEach(function(pp) {
pp.ownerId.should.eql(user.id);
});
});
@ -311,12 +311,12 @@ describe('include', function () {
it('should fetch User - Posts AND Passports in relation syntax',
function(done) {
User.find({include: [
{relation: 'posts', scope: {
where: {title: 'Post A'}
User.find({ include: [
{ relation: 'posts', scope: {
where: { title: 'Post A' },
}},
'passports'
]}, function(err, users) {
'passports',
] }, function(err, users) {
should.not.exist(err);
should.exist(users);
users.length.should.be.ok;
@ -348,12 +348,12 @@ describe('include', function () {
});
});
it('should not fetch User - AccessTokens', function (done) {
User.find({include: ['accesstokens']}, function (err, users) {
it('should not fetch User - AccessTokens', function(done) {
User.find({ include: ['accesstokens'] }, function(err, users) {
should.not.exist(err);
should.exist(users);
users.length.should.be.ok;
users.forEach(function (user) {
users.forEach(function(user) {
var userObj = user.toJSON();
userObj.should.not.have.property('accesstokens');
});
@ -361,20 +361,20 @@ describe('include', function () {
});
});
it('should support hasAndBelongsToMany', function (done) {
Assembly.create({name: 'car'}, function (err, assembly) {
Part.create({partNumber: 'engine'}, function (err, part) {
assembly.parts.add(part, function (err, data) {
assembly.parts(function (err, parts) {
it('should support hasAndBelongsToMany', function(done) {
Assembly.create({ name: 'car' }, function(err, assembly) {
Part.create({ partNumber: 'engine' }, function(err, part) {
assembly.parts.add(part, function(err, data) {
assembly.parts(function(err, parts) {
should.not.exist(err);
should.exists(parts);
parts.length.should.equal(1);
parts[0].partNumber.should.equal('engine');
// 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[0].parts().length.should.equal(2);
done();
@ -387,13 +387,13 @@ describe('include', function () {
});
});
it('should fetch User - Profile (HasOne)', function (done) {
User.find({include: ['profile']}, function (err, users) {
it('should fetch User - Profile (HasOne)', function(done) {
User.find({ include: ['profile'] }, function(err, users) {
should.not.exist(err);
should.exist(users);
users.length.should.be.ok;
var usersWithProfile = 0;
users.forEach(function (user) {
users.forEach(function(user) {
// The relation should be promoted as the 'owner' property
user.should.have.property('profile');
var userObj = user.toJSON();
@ -421,10 +421,10 @@ describe('include', function () {
// Not implemented correctly, see: loopback-datasource-juggler/issues/166
// fixed by DB optimization
it('should support include scope on hasAndBelongsToMany', function (done) {
Assembly.find({include: { relation: 'parts', scope: {
where: { partNumber: 'engine' }
}}}, function (err, assemblies) {
it('should support include scope on hasAndBelongsToMany', function(done) {
Assembly.find({ include: { relation: 'parts', scope: {
where: { partNumber: 'engine' },
}}}, function(err, assemblies) {
assemblies.length.should.equal(1);
var parts = assemblies[0].parts();
parts.should.have.length(1);
@ -435,7 +435,7 @@ describe('include', function () {
it('should save related items separately', function(done) {
User.find({
include: 'posts'
include: 'posts',
})
.then(function(users) {
var posts = users[0].posts();
@ -444,7 +444,7 @@ describe('include', function () {
})
.then(function(updatedUser) {
return User.findById(updatedUser.id, {
include: 'posts'
include: 'posts',
});
})
.then(function(user) {
@ -455,7 +455,7 @@ describe('include', function () {
.catch(done);
});
describe('performance', function () {
describe('performance', function() {
var all;
beforeEach(function() {
this.called = 0;
@ -469,11 +469,11 @@ describe('include', function () {
afterEach(function() {
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;
Passport.find({include: 'owner'}, function (err, passports) {
Passport.find({ include: 'owner' }, function(err, passports) {
passports.length.should.be.ok;
passports.forEach(function (p) {
passports.forEach(function(p) {
p.__cachedRelations.should.have.property('owner');
// The relation should be promoted as the 'owner' property
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;
Assembly.create([{name: 'sedan'}, {name: 'hatchback'},
{name: 'SUV'}],
function (err, assemblies) {
Part.create([{partNumber: 'engine'}, {partNumber: 'bootspace'},
{partNumber: 'silencer'}],
function (err, parts) {
async.each(parts, function (part, next) {
async.each(assemblies, function (assembly, next) {
Assembly.create([{ name: 'sedan' }, { name: 'hatchback' },
{ name: 'SUV' }],
function(err, assemblies) {
Part.create([{ partNumber: 'engine' }, { partNumber: 'bootspace' },
{ partNumber: 'silencer' }],
function(err, parts) {
async.each(parts, function(part, next) {
async.each(assemblies, function(assembly, next) {
if (assembly.name === 'SUV') {
return next();
}
@ -509,20 +509,20 @@ describe('include', function () {
part.partNumber === 'bootspace') {
return next();
}
assembly.parts.add(part, function (err, data) {
assembly.parts.add(part, function(err, data) {
next();
});
}, next);
}, function (err) {
}, function(err) {
self.called = 0;
Assembly.find({
where: {
name: {
inq: ['sedan', 'hatchback', 'SUV']
}
inq: ['sedan', 'hatchback', 'SUV'],
},
},
include: 'parts'
}, function (err, result) {
include: 'parts',
}, function(err, result) {
should.not.exist(err);
should.exists(result);
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;
User.find({include: ['posts', 'passports']}, function (err, users) {
User.find({ include: ['posts', 'passports'] }, function(err, users) {
should.not.exist(err);
should.exist(users);
users.length.should.be.ok;
users.forEach(function (user) {
users.forEach(function(user) {
// The relation should be promoted as the 'owner' property
user.should.have.property('posts');
user.should.have.property('passports');
@ -567,10 +567,10 @@ describe('include', function () {
user.__cachedRelations.should.have.property('posts');
user.__cachedRelations.should.have.property('passports');
user.__cachedRelations.posts.forEach(function (p) {
user.__cachedRelations.posts.forEach(function(p) {
p.userId.should.eql(user.id);
});
user.__cachedRelations.passports.forEach(function (pp) {
user.__cachedRelations.passports.forEach(function(pp) {
pp.ownerId.should.eql(user.id);
});
});
@ -581,15 +581,15 @@ describe('include', function () {
it('should not make n+1 db calls in relation syntax',
function (done) {
function(done) {
var self = this;
User.find({include: [{ relation: 'posts', scope: {
where: {title: 'Post A'}
}}, 'passports']}, function (err, users) {
User.find({ include: [{ relation: 'posts', scope: {
where: { title: 'Post A' },
}}, 'passports'] }, function(err, users) {
should.not.exist(err);
should.exist(users);
users.length.should.be.ok;
users.forEach(function (user) {
users.forEach(function(user) {
// The relation should be promoted as the 'owner' property
user.should.have.property('posts');
user.should.have.property('passports');
@ -605,11 +605,11 @@ describe('include', function () {
user.__cachedRelations.should.have.property('posts');
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.title.should.be.equal('Post A');
});
user.__cachedRelations.passports.forEach(function (pp) {
user.__cachedRelations.passports.forEach(function(pp) {
pp.ownerId.should.eql(user.id);
});
});
@ -627,44 +627,44 @@ function setup(done) {
Building = db.define('Building');
User = db.define('User', {
name: String,
age: Number
age: Number,
});
Profile = db.define('Profile', {
profileName: String
profileName: String,
});
AccessToken = db.define('AccessToken', {
token: String
token: String,
});
Passport = db.define('Passport', {
number: String
number: String,
});
Post = db.define('Post', {
title: String
title: String,
});
Passport.belongsTo('owner', {model: User});
User.hasMany('passports', {foreignKey: 'ownerId'});
User.hasMany('posts', {foreignKey: 'userId'});
Passport.belongsTo('owner', { model: User });
User.hasMany('passports', { foreignKey: 'ownerId' });
User.hasMany('posts', { foreignKey: 'userId' });
User.hasMany('accesstokens', {
foreignKey: 'userId',
options: {disableInclude: true}
options: { disableInclude: true },
});
Profile.belongsTo('user', {model: User});
User.hasOne('profile', {foreignKey: 'userId'});
Post.belongsTo('author', {model: User, foreignKey: 'userId'});
Profile.belongsTo('user', { model: User });
User.hasOne('profile', { foreignKey: 'userId' });
Post.belongsTo('author', { model: User, foreignKey: 'userId' });
Assembly = db.define('Assembly', {
name: String
name: String,
});
Part = db.define('Part', {
partNumber: String
partNumber: String,
});
Assembly.hasAndBelongsToMany(Part);
Part.hasAndBelongsToMany(Assembly);
db.automigrate(function () {
db.automigrate(function() {
var createdUsers = [];
var createdPassports = [];
var createdProfiles = [];
@ -674,13 +674,13 @@ function setup(done) {
clearAndCreate(
User,
[
{name: 'User A', age: 21},
{name: 'User B', age: 22},
{name: 'User C', age: 23},
{name: 'User D', age: 24},
{name: 'User E', age: 25}
{ name: 'User A', age: 21 },
{ name: 'User B', age: 22 },
{ name: 'User C', age: 23 },
{ name: 'User D', age: 24 },
{ name: 'User E', age: 25 },
],
function (items) {
function(items) {
createdUsers = items;
createPassports();
createAccessTokens();
@ -692,10 +692,10 @@ function setup(done) {
clearAndCreate(
AccessToken,
[
{token: '1', userId: createdUsers[0].id},
{token: '2', userId: createdUsers[1].id}
{ token: '1', userId: createdUsers[0].id },
{ token: '2', userId: createdUsers[1].id },
],
function (items) {}
function(items) {}
);
}
@ -703,12 +703,12 @@ function setup(done) {
clearAndCreate(
Passport,
[
{number: '1', ownerId: createdUsers[0].id},
{number: '2', ownerId: createdUsers[1].id},
{number: '3'},
{number: '4', ownerId: createdUsers[2].id},
{ number: '1', ownerId: createdUsers[0].id },
{ number: '2', ownerId: createdUsers[1].id },
{ number: '3' },
{ number: '4', ownerId: createdUsers[2].id },
],
function (items) {
function(items) {
createdPassports = items;
createPosts();
}
@ -719,12 +719,12 @@ function setup(done) {
clearAndCreate(
Profile,
[
{profileName: 'Profile A', userId: createdUsers[0].id},
{profileName: 'Profile B', userId: createdUsers[1].id},
{profileName: 'Profile Z'}
{ profileName: 'Profile A', userId: createdUsers[0].id },
{ profileName: 'Profile B', userId: createdUsers[1].id },
{ profileName: 'Profile Z' },
],
function (items) {
createdProfiles = items
function(items) {
createdProfiles = items;
done();
}
);
@ -734,13 +734,13 @@ function setup(done) {
clearAndCreate(
Post,
[
{title: 'Post A', userId: createdUsers[0].id},
{title: 'Post B', userId: createdUsers[0].id},
{title: 'Post C', userId: createdUsers[0].id},
{title: 'Post D', userId: createdUsers[1].id},
{title: 'Post E'}
{ title: 'Post A', userId: createdUsers[0].id },
{ title: 'Post B', userId: createdUsers[0].id },
{ title: 'Post C', userId: createdUsers[0].id },
{ title: 'Post D', userId: createdUsers[1].id },
{ title: 'Post E' },
],
function (items) {
function(items) {
createdPosts = items;
createProfiles();
}
@ -752,7 +752,7 @@ function setup(done) {
function clearAndCreate(model, data, callback) {
var createdItems = [];
model.destroyAll(function () {
model.destroyAll(function() {
nextItem(null, null);
});
@ -775,38 +775,38 @@ describe('Model instance with included relation .toJSON()', function() {
var db, ChallengerModel, GameParticipationModel, ResultModel;
before(function(done) {
db = new DataSource({connector: 'memory'});
db = new DataSource({ connector: 'memory' });
ChallengerModel = db.createModel('Challenger',
{
name: String
name: String,
},
{
relations: {
gameParticipations: {
type: 'hasMany',
model: 'GameParticipation',
foreignKey: ''
}
}
foreignKey: '',
},
},
}
);
GameParticipationModel = db.createModel('GameParticipation',
{
date: Date
date: Date,
},
{
relations: {
challenger: {
type: 'belongsTo',
model: 'Challenger',
foreignKey: ''
foreignKey: '',
},
results: {
type: 'hasMany',
model: 'Result',
foreignKey: ''
}
}
foreignKey: '',
},
},
}
);
ResultModel = db.createModel('Result', {
@ -816,9 +816,9 @@ describe('Model instance with included relation .toJSON()', function() {
gameParticipation: {
type: 'belongsTo',
model: 'GameParticipation',
foreignKey: ''
}
}
foreignKey: '',
},
},
});
async.waterfall([
@ -832,25 +832,25 @@ describe('Model instance with included relation .toJSON()', function() {
});
function createChallengers(callback) {
ChallengerModel.create([{name: 'challenger1'}, {name: 'challenger2'}], callback);
ChallengerModel.create([{ name: 'challenger1' }, { name: 'challenger2' }], callback);
}
function createGameParticipations(challengers, callback) {
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);
}
function createResults(gameParticipations, callback) {
ResultModel.create([
{gameParticipationId: gameParticipations[0].id, points: 10},
{gameParticipationId: gameParticipations[0].id, points: 20}
{ gameParticipationId: gameParticipations[0].id, points: 10 },
{ gameParticipationId: gameParticipations[0].id, points: 20 },
], callback);
}
it('should recursively serialize objects', function(done) {
var filter = {include: {gameParticipations: 'results'}};
var filter = { include: { gameParticipations: 'results' }};
ChallengerModel.find(filter, function(err, challengers) {
var levelOneInclusion = challengers[0].toJSON().gameParticipations[0];

View File

@ -3,44 +3,44 @@
// This file is licensed under the MIT License.
// License text available at https://opensource.org/licenses/MIT
var assert = require("assert");
var should = require("should");
var assert = require('assert');
var should = require('should');
var includeUtils = require("../lib/include_utils");
var includeUtils = require('../lib/include_utils');
describe('include_util', function(){
describe('#buildOneToOneIdentityMapWithOrigKeys', function(){
it('should return an object with keys', function(){
describe('include_util', function() {
describe('#buildOneToOneIdentityMapWithOrigKeys', function() {
it('should return an object with keys', function() {
var objs = [
{id: 11, letter: "A"},
{id: 22, letter: "B"}
{ id: 11, letter: 'A' },
{ id: 22, letter: 'B' },
];
var result = includeUtils.buildOneToOneIdentityMapWithOrigKeys(objs, "id");
var result = includeUtils.buildOneToOneIdentityMapWithOrigKeys(objs, 'id');
result.get(11).should.be.ok;
result.get(22).should.be.ok;
});
it('should overwrite keys in case of collision', function(){
var objs = [
{id: 11, letter: "A"},
{id: 22, letter: "B"},
{id: 33, letter: "C"},
{id: 11, letter: "HA!"}
];
it('should overwrite keys in case of collision', function() {
var objs = [
{ id: 11, letter: 'A' },
{ id: 22, letter: 'B' },
{ id: 33, letter: 'C' },
{ id: 11, letter: 'HA!' },
];
var result = includeUtils.buildOneToOneIdentityMapWithOrigKeys(objs, "id");
result.getKeys().should.containEql(11);
result.getKeys().should.containEql(22);
result.getKeys().should.containEql(33);
result.get(11)["letter"].should.equal("HA!");
result.get(33)["letter"].should.equal("C");
var result = includeUtils.buildOneToOneIdentityMapWithOrigKeys(objs, 'id');
result.getKeys().should.containEql(11);
result.getKeys().should.containEql(22);
result.getKeys().should.containEql(33);
result.get(11)['letter'].should.equal('HA!');
result.get(33)['letter'].should.equal('C');
});
});
describe('#buildOneToOneIdentityMapWithOrigKeys', function(){
it('should return an object with keys', function(){
describe('#buildOneToOneIdentityMapWithOrigKeys', function() {
it('should return an object with keys', function() {
var objs = [
{id: 11, letter: "A"},
{id: 22, letter: "B"}
{ id: 11, letter: 'A' },
{ id: 22, letter: 'B' },
];
var result = includeUtils.buildOneToOneIdentityMapWithOrigKeys(objs, 'id');
result.get(11).should.be.ok;
@ -48,36 +48,36 @@ describe('include_util', function(){
result.getKeys().should.have.lengthOf(2); // no additional properties
});
});
describe('#buildOneToManyIdentityMap', function(){
it('should return an object with keys', function(){
var objs = [
{id: 11, letter: "A"},
{id: 22, letter: "B"}
];
var result = includeUtils.buildOneToManyIdentityMapWithOrigKeys(objs, "id");
result.exist(11).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");
});
describe('#buildOneToManyIdentityMap', function() {
it('should return an object with keys', function() {
var objs = [
{ id: 11, letter: 'A' },
{ id: 22, letter: 'B' },
];
var result = includeUtils.buildOneToManyIdentityMapWithOrigKeys(objs, 'id');
result.exist(11).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');
});
});
});
describe('KVMap', function(){
it('should allow to set and get value with key string', function(){
describe('KVMap', function() {
it('should allow to set and get value with key string', function() {
var map = new includeUtils.KVMap();
map.set('name', 'Alex');
map.set('gender', true);
@ -86,23 +86,23 @@ describe('KVMap', function(){
map.get('gender').should.be.equal(true);
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();
map.set('name', 'Alex');
map.set(true, 'male');
map.set(false, false);
map.set({isTrue: 'yes'}, 25);
map.set({ isTrue: 'yes' }, 25);
map.get('name').should.be.equal('Alex');
map.get(true).should.be.equal('male');
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();
map.set('name', 'Alex');
(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();
map.set('one', 1);
map.set(2, 'two');
@ -112,7 +112,7 @@ describe('KVMap', function(){
map.exist(true).should.be.true;
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();
map.set('one', 1);
map.set(2, 'two');
@ -122,7 +122,7 @@ describe('KVMap', function(){
keys.should.containEql(2);
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();
map.set(1, [1, 2, 3]);
map.set(2, [2, 3, 4]);

View File

@ -21,13 +21,13 @@ var ModelBuilder = require('../').ModelBuilder;
var Schema = require('../').Schema;
if (!('getSchema' in global)) {
global.getSchema = function (connector, settings) {
global.getSchema = function(connector, settings) {
return new Schema(connector || 'memory', settings);
};
}
if (!('getModelBuilder' in global)) {
global.getModelBuilder = function () {
global.getModelBuilder = function() {
return new ModelBuilder();
};
}

View File

@ -19,19 +19,19 @@ var json = {
city: 'San Jose',
state: 'CA',
zipcode: '95131',
country: 'US'
country: 'US',
},
friends: ['John', 'Mary'],
emails: [
{label: 'work', id: 'x@sample.com'},
{label: 'home', id: 'x@home.com'}
{ label: 'work', id: 'x@sample.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(true), 'boolean');
assert.equal(introspectType(false), 'boolean');
@ -39,7 +39,7 @@ describe('Introspection of model definitions from JSON', function () {
assert.equal(introspectType(new Date()), 'date');
});
it('should handle array types', function () {
it('should handle array types', function() {
var type = introspectType(['123']);
assert.deepEqual(type, ['string'], 'type should be ["string"]');
type = introspectType([1]);
@ -54,21 +54,21 @@ describe('Introspection of model definitions from JSON', function () {
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(undefined), ModelBuilder.Any);
});
it('should return a schema for object', function () {
var json = {a: 'str', b: 0, c: true};
it('should return a schema for object', function() {
var json = { a: 'str', b: 0, c: true };
var type = introspectType(json);
assert.equal(type.a, 'string');
assert.equal(type.b, 'number');
assert.equal(type.c, 'boolean');
});
it('should handle nesting objects', function () {
var json = {a: 'str', b: 0, c: true, d: {x: 10, y: 5}};
it('should handle nesting objects', function() {
var json = { a: 'str', b: 0, c: true, d: { x: 10, y: 5 }};
var type = introspectType(json);
assert.equal(type.a, 'string');
assert.equal(type.b, 'number');
@ -77,8 +77,8 @@ describe('Introspection of model definitions from JSON', function () {
assert.equal(type.d.y, 'number');
});
it('should handle nesting arrays', function () {
var json = {a: 'str', b: 0, c: true, d: [1, 2]};
it('should handle nesting arrays', function() {
var json = { a: 'str', b: 0, c: true, d: [1, 2] };
var type = introspectType(json);
assert.equal(type.a, 'string');
assert.equal(type.b, 'number');
@ -86,13 +86,13 @@ describe('Introspection of model definitions from JSON', function () {
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 schema = introspectType(json);
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
var obj = new Model(json);
@ -103,11 +103,11 @@ describe('Introspection of model definitions from JSON', function () {
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 builder = new ModelBuilder();
var Model = builder.buildModelFromInstance('MyModel', copy, {idInjection: false});
var Model = builder.buildModelFromInstance('MyModel', copy, { idInjection: false });
var obj = new Model(json);
obj = obj.toObject();
@ -115,12 +115,12 @@ describe('Introspection of model definitions from JSON', function () {
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 builder = new DataSource('memory');
var Model = builder.buildModelFromInstance('MyModel', copy,
{idInjection: false});
{ idInjection: false });
assert.equal(Model.dataSource, builder);

View File

@ -9,33 +9,33 @@ var should = require('./init.js');
var Schema = require('../').Schema;
var ModelBuilder = require('../').ModelBuilder;
describe('JSON property', function () {
describe('JSON property', function() {
var dataSource, Model;
it('should be defined', function () {
it('should be defined', function() {
dataSource = getSchema();
Model = dataSource.define('Model', {propertyName: ModelBuilder.JSON});
Model = dataSource.define('Model', { propertyName: ModelBuilder.JSON });
var m = new Model;
(new Boolean('propertyName' in m)).should.eql(true);
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({
propertyName: '{"foo": "bar"}'
propertyName: '{"foo": "bar"}',
});
m.propertyName.should.be.an.Object;
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;
m.propertyName = {"foo": "bar"};
m.propertyName = { 'foo': 'bar' };
m.propertyName.should.be.an.Object;
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;
m.propertyName = '{"foo": "bar"}';
m.propertyName.should.be.a.String;

View File

@ -8,8 +8,8 @@ var should = require('./init.js');
var loopbackData = require('../');
describe('loopback-datasource-juggler', function () {
it('should expose version', function () {
describe('loopback-datasource-juggler', function() {
it('should expose version', function() {
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

View File

@ -36,20 +36,20 @@ describe('Memory connector', function() {
function createUserModel() {
var ds = new DataSource({
connector: 'memory',
file: file
file: file,
});
var User = ds.createModel('User', {
id: {
type: Number,
id: true,
generated: true
generated: true,
},
name: String,
bio: String,
approved: Boolean,
joinedAt: Date,
age: Number
age: Number,
});
return User;
}
@ -64,7 +64,7 @@ describe('Memory connector', function() {
it('should persist create', function(done) {
var count = 0;
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);
count++;
readModels(function(err, json) {
@ -92,7 +92,7 @@ describe('Memory connector', function() {
});
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) {
return done(err);
}
@ -110,7 +110,7 @@ describe('Memory connector', function() {
});
it('should persist update', function(done) {
User.update({id: ids[1]}, {name: 'John1'},
User.update({ id: ids[1] }, { name: 'John1' },
function(err, result) {
if (err) {
return done(err);
@ -141,33 +141,33 @@ describe('Memory connector', function() {
describe('Query for memory connector', function() {
var ds = new DataSource({
connector: 'memory'
connector: 'memory',
});
var User = ds.define('User', {
seq: {type: Number, index: true},
name: {type: String, index: true, sort: true},
email: {type: String, index: true},
birthday: {type: Date, index: true},
role: {type: String, index: true},
order: {type: Number, index: true, sort: true},
vip: {type: Boolean},
seq: { type: Number, index: true },
name: { type: String, index: true, sort: true },
email: { type: String, index: true },
birthday: { type: Date, index: true },
role: { type: String, index: true },
order: { type: Number, index: true, sort: true },
vip: { type: Boolean },
address: {
street: String,
city: String,
state: String,
zipCode: String
zipCode: String,
},
friends: [
{
name: String
}
]
name: String,
},
],
});
before(seed);
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);
posts.should.have.property('length', 2);
done();
@ -175,7 +175,7 @@ describe('Memory connector', function() {
});
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);
posts.should.have.property('length', 2);
done();
@ -183,7 +183,7 @@ describe('Memory connector', function() {
});
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);
posts.should.have.property('length', 0);
done();
@ -191,7 +191,7 @@ describe('Memory connector', function() {
});
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);
posts.should.have.property('length', 4);
done();
@ -199,7 +199,7 @@ describe('Memory connector', function() {
});
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);
posts.should.have.property('length', 4);
done();
@ -207,7 +207,7 @@ describe('Memory connector', function() {
});
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);
posts.should.have.property('length', 6);
done();
@ -215,73 +215,73 @@ describe('Memory connector', function() {
});
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);
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);
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);
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);
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);
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);
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);
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) {
should(users.length).be.equal(1);
should(users[0].name).be.equal('John Lennon');
done();
});
should(users.length).be.equal(1);
should(users[0].name).be.equal('John Lennon');
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) {
should(users.length).be.equal(2);
done();
});
should(users.length).be.equal(2);
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[0].name).be.equal('John Lennon');
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) {
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[0].name).be.equal('John Lennon');
done();
@ -298,8 +298,8 @@ describe('Memory connector', function() {
});
it('should successfully extract 2 users using date range', function(done) {
User.find({where: {birthday: {between:
[new Date(1940, 0).toISOString(), new Date(1990, 0).toISOString()]}}},
User.find({ where: { birthday: { between:
[new Date(1940, 0).toISOString(), new Date(1990, 0).toISOString()] }}},
function(err, users) {
should(users.length).be.equal(2);
done();
@ -307,21 +307,21 @@ describe('Memory connector', function() {
});
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) {
should(users.length).be.equal(0);
done();
});
should(users.length).be.equal(0);
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({
where: {
children: {
regexp: /an/
}
}
}, function (err, users) {
regexp: /an/,
},
},
}, function(err, users) {
should.not.exist(err);
users.length.should.be.equal(2);
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({
where: {
children: 'Dhani'
}
}, function (err, users) {
children: 'Dhani',
},
}, function(err, users) {
should.not.exist(err);
users.length.should.be.equal(1);
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({
where: {
'children': {neq: 'Dhani'}
}
}, function (err, users) {
'children': { neq: 'Dhani' },
},
}, function(err, users) {
should.not.exist(err);
users.length.should.be.equal(5);
done();
@ -356,7 +356,7 @@ describe('Memory connector', function() {
});
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) {
should(count).be.equal(2);
done();
@ -364,7 +364,7 @@ describe('Memory connector', function() {
});
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);
posts[0].seq.should.be.eql(4);
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) {
User.find({order: 'vip ASC, order DESC'}, function(err, posts) {
User.find({ order: 'vip ASC, order DESC' }, function(err, posts) {
should.not.exist(err);
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) {
User.find({order: 'seq ABC'}, function(err, posts) {
User.find({ order: 'seq ABC' }, function(err, posts) {
should.exist(err);
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);
users.length.should.be.equal(5);
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) {
User.find({where: {role: {neq: 'lead'}}}, function(err, users) {
User.find({ where: { role: { neq: 'lead' }}}, function(err, users) {
should.not.exist(err);
users.length.should.be.equal(4);
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) {
User.find({where: {role: {neq: null}}}, function(err, users) {
User.find({ where: { role: { neq: null }}}, function(err, users) {
should.not.exist(err);
users.length.should.be.equal(2);
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',
function(done) {
User.find({where: {name: /John.*/i}}, function(err, users) {
should.not.exist(err);
users.length.should.equal(1);
users[0].name.should.equal('John Lennon');
done();
});
});
User.find({ where: { name: /John.*/i }}, function(err, users) {
should.not.exist(err);
users.length.should.equal(1);
users[0].name.should.equal('John Lennon');
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);
users.length.should.equal(1);
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) {
User.find({where: {name: {regexp: /^J/}}}, function(err, users) {
User.find({ where: { name: { regexp: /^J/ }}}, function(err, users) {
should.not.exist(err);
users.length.should.equal(1);
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) {
User.find({where: {name: {regexp: new RegExp(/^J/)}}}, function(err,
User.find({ where: { name: { regexp: new RegExp(/^J/) }}}, function(err,
users) {
should.not.exist(err);
users.length.should.equal(1);
@ -463,7 +463,7 @@ describe('Memory connector', function() {
});
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);
users.length.should.be.equal(1);
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) {
User.find({where: {'friends.name': {regexp: /^Ringo/}}}, function(err, users) {
User.find({ where: { 'friends.name': { regexp: /^Ringo/ }}}, function(err, users) {
should.not.exist(err);
users.length.should.be.equal(2);
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) {
User.find({where: {'address.city': {gt: 'San'}}}, function(err, users) {
should.not.exist(err);
users.length.should.be.equal(2);
for (var i = 0; i < users.length; i++) {
User.find({ where: { 'address.city': { gt: 'San' }}}, function(err, users) {
should.not.exist(err);
users.length.should.be.equal(2);
for (var i = 0; i < users.length; i++) {
users[i].address.state.should.be.eql('CA');
}
done();
});
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) {
should.not.exist(err);
users.length.should.be.equal(2);
@ -506,8 +506,8 @@ describe('Memory connector', function() {
});
it('should deserialize values after saving in upsert', function(done) {
User.findOne({where: {seq: 1}}, function(err, paul) {
User.updateOrCreate({id: paul.id, name: 'Sir Paul McCartney'},
User.findOne({ where: { seq: 1 }}, function(err, paul) {
User.updateOrCreate({ id: paul.id, name: 'Sir Paul McCartney' },
function(err, sirpaul) {
should.not.exist(err);
sirpaul.birthday.should.be.instanceOf(Date);
@ -531,14 +531,14 @@ describe('Memory connector', function() {
street: '123 A St',
city: 'San Jose',
state: 'CA',
zipCode: '95131'
zipCode: '95131',
},
friends: [
{ name: 'Paul McCartney' },
{ name: 'George Harrison' },
{ name: 'Ringo Starr' },
],
children: ['Sean', 'Julian']
children: ['Sean', 'Julian'],
},
{
seq: 1,
@ -552,26 +552,26 @@ describe('Memory connector', function() {
street: '456 B St',
city: 'San Mateo',
state: 'CA',
zipCode: '94065'
zipCode: '94065',
},
friends: [
{ name: 'John Lennon' },
{ name: 'George Harrison' },
{ 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: 3, name: 'Ringo Starr', order: 6, vip: false},
{seq: 4, name: 'Pete Best', order: 4, children: []},
{seq: 5, name: 'Stuart Sutcliffe', order: 3, vip: true}
{ seq: 2, name: 'George Harrison', order: 5, vip: false, children: ['Dhani'] },
{ seq: 3, name: 'Ringo Starr', order: 6, vip: false },
{ seq: 4, name: 'Pete Best', order: 4, children: [] },
{ seq: 5, name: 'Stuart Sutcliffe', order: 3, vip: true },
];
async.series([
User.destroyAll.bind(User),
function(cb) {
async.each(beatles, User.create.bind(User), cb);
}
},
], done);
}
@ -579,20 +579,20 @@ describe('Memory connector', function() {
it('should use collection setting', function(done) {
var ds = new DataSource({
connector: 'memory'
connector: 'memory',
});
var Product = ds.createModel('Product', {
name: String
name: String,
});
var Tool = ds.createModel('Tool', {
name: String
}, {memory: {collection: 'Product'}});
name: String,
}, { memory: { collection: 'Product' }});
var Widget = ds.createModel('Widget', {
name: String
}, {memory: {collection: 'Product'}});
name: String,
}, { memory: { collection: 'Product' }});
ds.connector.getCollection('Tool').should.equal('Product');
ds.connector.getCollection('Widget').should.equal('Product');
@ -606,7 +606,7 @@ describe('Memory connector', function() {
},
function(next) {
Widget.create({ name: 'Widget A' }, next);
}
},
], function(err) {
Product.find(function(err, products) {
should.not.exist(err);
@ -623,11 +623,11 @@ describe('Memory connector', function() {
var ds;
beforeEach(function() {
ds = new DataSource({
connector: 'memory'
connector: 'memory',
});
ds.createModel('m1', {
name: String
name: String,
});
});
@ -642,7 +642,7 @@ describe('Memory connector', function() {
.then(function(result) {
done();
})
.catch(function(err){
.catch(function(err) {
done(err);
});
});
@ -658,7 +658,7 @@ describe('Memory connector', function() {
.then(function(result) {
done();
})
.catch(function(err){
.catch(function(err) {
done(err);
});
});
@ -674,7 +674,7 @@ describe('Memory connector', function() {
.then(function(result) {
done();
})
.catch(function(err){
.catch(function(err) {
done(err);
});
});
@ -688,10 +688,10 @@ describe('Memory connector', function() {
it('automigrate reports errors for models not attached - promise variant', function(done) {
ds.automigrate(['m1', 'm2'])
.then(function(){
.then(function() {
done(new Error('automigrate() should have failed'));
})
.catch(function(err){
.catch(function(err) {
err.should.be.an.instanceOf(Error);
done();
});
@ -702,17 +702,17 @@ describe('Memory connector', function() {
describe('findOrCreate', function() {
var ds, Cars;
before(function() {
ds = new DataSource({connector: 'memory'});
ds = new DataSource({ connector: 'memory' });
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) {
var creationNum = 0;
async.times(100, function(n, next) {
var initialData = {color: 'white'};
var query = {'where': initialData};
var initialData = { color: 'white' };
var query = { 'where': initialData };
Cars.findOrCreate(query, initialData, function(err, car, created) {
if (created) creationNum++;
next(err, car);
@ -735,20 +735,20 @@ describe('Memory connector', function() {
var ds;
beforeEach(function() {
ds = new DataSource({
connector: 'memory'
connector: 'memory',
});
});
it('automigrate does NOT report error when NO models are attached', function(done) {
ds.automigrate(function(err) {
done();
})
});
});
it('automigrate does NOT report error when NO models are attached - promise variant', function(done) {
ds.automigrate()
.then(done)
.catch(function(err){
.catch(function(err) {
done(err);
});
});
@ -758,7 +758,7 @@ describe('Memory connector', function() {
var ds, model;
beforeEach(function() {
ds = new DataSource({
connector: 'memory'
connector: 'memory',
});
ds.connector.autoupdate = function(models, cb) {
@ -766,19 +766,19 @@ describe('Memory connector', function() {
};
model = ds.createModel('m1', {
name: String
name: String,
});
ds.automigrate();
ds.createModel('m1', {
name: String,
address: String
address: String,
});
});
it('autoupdates all models', function(done) {
ds.autoupdate(function(err, result){
ds.autoupdate(function(err, result) {
done(err);
});
});
@ -786,9 +786,9 @@ describe('Memory connector', function() {
it('autoupdates all models - promise variant', function(done) {
ds.autoupdate()
.then(function(result) {
done();
})
.catch(function(err){
done();
})
.catch(function(err) {
done(err);
});
});
@ -804,7 +804,7 @@ describe('Memory connector', function() {
.then(function(result) {
done();
})
.catch(function(err){
.catch(function(err) {
done(err);
});
});
@ -820,7 +820,7 @@ describe('Memory connector', function() {
.then(function(result) {
done();
})
.catch(function(err){
.catch(function(err) {
done(err);
});
});
@ -834,10 +834,10 @@ describe('Memory connector', function() {
it('autoupdate reports errors for models not attached - promise variant', function(done) {
ds.autoupdate(['m1', 'm2'])
.then(function(){
.then(function() {
done(new Error('automigrate() should have failed'));
})
.catch(function(err){
.catch(function(err) {
err.should.be.an.instanceOf(Error);
done();
});
@ -849,16 +849,16 @@ describe('Optimized connector', function() {
var ds = new DataSource({ connector: Memory });
// optimized methods
ds.connector.findOrCreate = function (model, query, data, callback) {
this.all(model, query, {}, function (err, list) {
ds.connector.findOrCreate = function(model, query, data, callback) {
this.all(model, query, {}, function(err, list) {
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);
});
}.bind(this));
};
require('./persistence-hooks.suite')(ds, should, {replaceOrCreateReportsNewInstance: true});
require('./persistence-hooks.suite')(ds, should, { replaceOrCreateReportsNewInstance: true });
});
describe('Unoptimized connector', function() {
@ -867,14 +867,14 @@ describe('Unoptimized connector', function() {
ds.connector.updateOrCreate = 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() {
var ds, savedOptions = {}, Post;
before(function() {
ds = new DataSource({connector: 'memory'});
ds = new DataSource({ connector: 'memory' });
ds.connector.create = function(model, data, options, cb) {
savedOptions.create = options;
process.nextTick(function() {
@ -885,33 +885,33 @@ describe('Memory connector with options', function() {
ds.connector.update = function(model, where, data, options, cb) {
savedOptions.update = options;
process.nextTick(function() {
cb(null, {count: 1});
cb(null, { count: 1 });
});
};
ds.connector.all = function(model, filter, options, cb) {
savedOptions.find = options;
process.nextTick(function() {
cb(null, [{title: 't1', content: 'c1'}]);
cb(null, [{ title: 't1', content: 'c1' }]);
});
};
Post = ds.define('Post', {
title: String,
content: String
content: String,
});
});
it('should receive options from the find method', function(done) {
var opts = {transaction: 'tx1'};
Post.find({where: {title: 't1'}}, opts, function(err, p) {
var opts = { transaction: 'tx1' };
Post.find({ where: { title: 't1' }}, opts, function(err, p) {
savedOptions.find.should.be.eql(opts);
done(err);
});
});
it('should receive options from the find method', function(done) {
var opts = {transaction: 'tx2'};
var opts = { transaction: 'tx2' };
Post.find({}, opts, function(err, p) {
savedOptions.find.should.be.eql(opts);
done(err);
@ -919,7 +919,7 @@ describe('Memory connector with options', function() {
});
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) {
savedOptions.find.should.be.eql({});
done(err);
@ -927,16 +927,16 @@ describe('Memory connector with options', function() {
});
it('should receive options from the create method', function(done) {
var opts = {transaction: 'tx3'};
Post.create({title: 't1', content: 'c1'}, opts, function(err, p) {
var opts = { transaction: 'tx3' };
Post.create({ title: 't1', content: 'c1' }, opts, function(err, p) {
savedOptions.create.should.be.eql(opts);
done(err);
});
});
it('should receive options from the update method', function(done) {
var opts = {transaction: 'tx4'};
Post.update({title: 't1'}, {content: 'c1 --> c2'},
var opts = { transaction: 'tx4' };
Post.update({ title: 't1' }, { content: 'c1 --> c2' },
opts, function(err, p) {
savedOptions.update.should.be.eql(opts);
done(err);
@ -947,7 +947,7 @@ describe('Memory connector with options', function() {
describe('Memory connector with observers', function() {
var ds = new DataSource({
connector: 'memory'
connector: 'memory',
});
it('should have observer mixed into the connector', function() {
@ -959,7 +959,7 @@ describe('Memory connector with observers', function() {
var events = [];
ds.connector.execute = function(command, params, options, cb) {
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) {
process.nextTick(function() {
if (err) return cb(err);
@ -981,7 +981,7 @@ describe('Memory connector with observers', function() {
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);
events.should.eql(['before execute', 'execute', 'after execute']);
done();

View File

@ -45,7 +45,7 @@ function timestamps(Model, options) {
mixins.define('TimeStamp', timestamps);
describe('Model class', function () {
describe('Model class', function() {
it('should define mixins', function() {
mixins.define('Example', function(Model, options) {
@ -65,12 +65,12 @@ describe('Model class', function () {
it('should apply a mixin class', function() {
var Address = modelBuilder.define('Address', {
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' }, {
mixins: { Address: true }
mixins: { Address: true },
});
var properties = Item.definition.properties;
@ -80,15 +80,15 @@ describe('Model class', function () {
});
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' }, {
mixins: {
TimeStamp: true, Demo: { value: true },
Multi: [
{ key: 'foo', value: 'bar' },
{ key: 'fox', value: 'baz' }
]
}
{ key: 'fox', value: 'baz' },
],
},
});
Item.mixin('Example', { foo: 'bar' });
@ -110,31 +110,31 @@ describe('Model class', function () {
});
});
describe('#mixin()', function () {
describe('#mixin()', function() {
var Person, Author, Address;
beforeEach(function () {
beforeEach(function() {
Address = modelBuilder.define('Address', {
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' });
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._mixins.should.containEql(Address);
});
it('should NOT share mixins registry', function () {
it('should NOT share mixins registry', function() {
Person.mixin(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);
Author.mixin(Address);
Author._mixins.should.containEql(Address);

View File

@ -14,21 +14,21 @@ var Memory = require('../lib/connectors/memory');
var ModelDefinition = require('../lib/model-definition');
describe('ModelDefinition class', function () {
describe('ModelDefinition class', function() {
var memory;
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 User = new ModelDefinition(modelBuilder, 'User', {
name: "string",
name: 'string',
bio: ModelBuilder.Text,
approved: Boolean,
joinedAt: Date,
age: "number"
age: 'number',
});
User.build();
@ -39,12 +39,12 @@ describe('ModelDefinition class', function () {
assert.equal(User.properties.age.type, Number);
var json = User.toJSON();
assert.equal(json.name, "User");
assert.equal(json.properties.name.type, "String");
assert.equal(json.properties.bio.type, "Text");
assert.equal(json.properties.approved.type, "Boolean");
assert.equal(json.properties.joinedAt.type, "Date");
assert.equal(json.properties.age.type, "Number");
assert.equal(json.name, 'User');
assert.equal(json.properties.name.type, 'String');
assert.equal(json.properties.bio.type, 'Text');
assert.equal(json.properties.approved.type, 'Boolean');
assert.equal(json.properties.joinedAt.type, 'Date');
assert.equal(json.properties.age.type, 'Number');
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 User = new ModelDefinition(modelBuilder, 'User', {
name: "string",
name: 'string',
bio: ModelBuilder.Text,
approved: Boolean,
joinedAt: Date,
age: "number"
age: 'number',
});
User.build();
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.bio.type, ModelBuilder.Text);
assert.equal(User.properties.approved.type, Boolean);
@ -77,13 +77,13 @@ describe('ModelDefinition class', function () {
assert.equal(User.properties.id.type, Number);
json = User.toJSON();
assert.deepEqual(json.properties.id, {type: 'Number', id: true});
assert.deepEqual(json.properties.id, { type: 'Number', id: true });
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 User = new ModelDefinition(modelBuilder, 'User', {
@ -96,8 +96,8 @@ describe('ModelDefinition class', function () {
street: String,
city: String,
zipCode: String,
state: String
}
state: String,
},
});
User.build();
@ -109,30 +109,30 @@ describe('ModelDefinition class', function () {
assert.equal(typeof User.properties.address.type, 'function');
var json = User.toJSON();
assert.equal(json.name, "User");
assert.equal(json.properties.name.type, "String");
assert.equal(json.properties.bio.type, "Text");
assert.equal(json.properties.approved.type, "Boolean");
assert.equal(json.properties.joinedAt.type, "Date");
assert.equal(json.properties.age.type, "Number");
assert.equal(json.name, 'User');
assert.equal(json.properties.name.type, 'String');
assert.equal(json.properties.bio.type, 'Text');
assert.equal(json.properties.approved.type, 'Boolean');
assert.equal(json.properties.joinedAt.type, 'Date');
assert.equal(json.properties.age.type, 'Number');
assert.deepEqual(json.properties.address.type, { street: { type: 'String' },
city: { type: 'String' },
zipCode: { type: 'String' },
state: { type: 'String' } });
state: { type: 'String' }});
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 Address = modelBuilder.define('Address', {
street: String,
city: String,
zipCode: String,
state: String
state: String,
});
var User = new ModelDefinition(modelBuilder, 'User', {
name: String,
@ -140,7 +140,7 @@ describe('ModelDefinition class', function () {
approved: Boolean,
joinedAt: Date,
age: Number,
address: Address
address: Address,
});
@ -153,12 +153,12 @@ describe('ModelDefinition class', function () {
assert.equal(User.properties.address.type, Address);
var json = User.toJSON();
assert.equal(json.name, "User");
assert.equal(json.properties.name.type, "String");
assert.equal(json.properties.bio.type, "Text");
assert.equal(json.properties.approved.type, "Boolean");
assert.equal(json.properties.joinedAt.type, "Date");
assert.equal(json.properties.age.type, "Number");
assert.equal(json.name, 'User');
assert.equal(json.properties.name.type, 'String');
assert.equal(json.properties.bio.type, 'Text');
assert.equal(json.properties.approved.type, 'Boolean');
assert.equal(json.properties.joinedAt.type, 'Date');
assert.equal(json.properties.age.type, 'Number');
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 Address = modelBuilder.define('Address', {
street: String,
city: String,
zipCode: String,
state: String
state: String,
});
var User = new ModelDefinition(modelBuilder, 'User', {
name: String,
@ -181,7 +181,7 @@ describe('ModelDefinition class', function () {
approved: Boolean,
joinedAt: Date,
age: Number,
address: 'Address'
address: 'Address',
});
@ -194,12 +194,12 @@ describe('ModelDefinition class', function () {
assert.equal(User.properties.address.type, Address);
var json = User.toJSON();
assert.equal(json.name, "User");
assert.equal(json.properties.name.type, "String");
assert.equal(json.properties.bio.type, "Text");
assert.equal(json.properties.approved.type, "Boolean");
assert.equal(json.properties.joinedAt.type, "Date");
assert.equal(json.properties.age.type, "Number");
assert.equal(json.name, 'User');
assert.equal(json.properties.name.type, 'String');
assert.equal(json.properties.bio.type, 'Text');
assert.equal(json.properties.approved.type, 'Boolean');
assert.equal(json.properties.joinedAt.type, 'Date');
assert.equal(json.properties.age.type, 'Number');
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 User = new ModelDefinition(modelBuilder, 'User', {
userId: {type: String, id: true},
name: "string",
userId: { type: String, id: true },
name: 'string',
bio: ModelBuilder.Text,
approved: Boolean,
joinedAt: Date,
age: "number"
age: 'number',
});
assert.equal(User.idName(), 'userId');
@ -224,17 +224,17 @@ describe('ModelDefinition class', function () {
done();
});
it('should sort id properties by its index', function () {
it('should sort id properties by its index', function() {
var modelBuilder = new ModelBuilder();
var User = new ModelDefinition(modelBuilder, 'User', {
userId: {type: String, id: 2},
userType: {type: String, id: 1},
name: "string",
userId: { type: String, id: 2 },
userType: { type: String, id: 1 },
name: 'string',
bio: ModelBuilder.Text,
approved: Boolean,
joinedAt: Date,
age: "number"
age: 'number',
});
var ids = User.ids();
@ -246,13 +246,13 @@ describe('ModelDefinition class', function () {
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 User = new ModelDefinition(modelBuilder, 'User', {
userId: {type: String, id: true, oracle: {column: 'ID'}},
name: "string"
}, {oracle: {table: 'USER'}});
userId: { type: String, id: true, oracle: { column: 'ID' }},
name: 'string',
}, { oracle: { table: 'USER' }});
assert.equal(User.tableName('oracle'), 'USER');
assert.equal(User.tableName('mysql'), 'User');
@ -261,15 +261,15 @@ describe('ModelDefinition class', function () {
done();
});
it('should inherit prototype using option.base', function () {
it('should inherit prototype using option.base', function() {
var modelBuilder = memory.modelBuilder;
var parent = memory.createModel('parent', {}, {
relations: {
children: {
type: 'hasMany',
model: 'anotherChild'
}
}
model: 'anotherChild',
},
},
});
var baseChild = modelBuilder.define('baseChild');
baseChild.attachTo(memory);
@ -301,30 +301,30 @@ describe('ModelDefinition class', function () {
it('should serialize protected properties into JSON', function() {
var modelBuilder = memory.modelBuilder;
var ProtectedModel = memory.createModel('protected', {}, {
protected: ['protectedProperty']
protected: ['protectedProperty'],
});
var pm = new ProtectedModel({
id: 1, foo: 'bar', protectedProperty: 'protected'
id: 1, foo: 'bar', protectedProperty: 'protected',
});
var serialized = pm.toJSON();
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 Parent = memory.createModel('parent');
var Child = memory.createModel('child', {}, {protected: ['protectedProperty']});
var Child = memory.createModel('child', {}, { protected: ['protectedProperty'] });
Parent.hasMany(Child);
Parent.create({
name: 'parent'
name: 'parent',
}, function(err, parent) {
parent.children.create({
name: 'child',
protectedProperty: 'protectedValue'
protectedProperty: 'protectedValue',
}, function(err, child) {
Parent.find({include: 'children'}, function(err, parents) {
Parent.find({ include: 'children' }, function(err, parents) {
var serialized = parents[0].toJSON();
var child = serialized.children[0];
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 HiddenModel = memory.createModel('hidden', {}, {
hidden: ['secret']
hidden: ['secret'],
});
var hm = new HiddenModel({
id: 1,
foo: 'bar',
secret: 'secret'
secret: 'secret',
});
var serialized = hm.toJSON();
assert.deepEqual(serialized, {
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 Parent = memory.createModel('parent');
var Child = memory.createModel('child', {}, {hidden: ['secret']});
var Child = memory.createModel('child', {}, { hidden: ['secret'] });
Parent.hasMany(Child);
Parent.create({
name: 'parent'
name: 'parent',
}, function(err, parent) {
parent.children.create({
name: 'child',
secret: 'secret'
secret: 'secret',
}, function(err, child) {
Parent.find({include: 'children'}, function(err, parents) {
Parent.find({ include: 'children' }, function(err, parents) {
var serialized = parents[0].toJSON();
var child = serialized.children[0];
assert.equal(child.name, 'child');
@ -399,7 +399,7 @@ describe('ModelDefinition class', function () {
it('should support "array" type shortcut', function() {
var Model = memory.createModel('TwoArrays', {
regular: Array,
sugar: 'array'
sugar: 'array',
});
var props = Model.definition.properties;
@ -411,11 +411,11 @@ describe('ModelDefinition class', function () {
var Todo;
before(function prepModel() {
Todo = new ModelDefinition(new ModelBuilder(), 'Todo', {
content: 'string'
content: 'string',
});
Todo.defineProperty('id', {
type: 'number',
id: true
id: true,
});
Todo.build();
});
@ -429,7 +429,7 @@ describe('ModelDefinition class', function () {
var Todo;
before(function prepModel() {
Todo = new ModelDefinition(new ModelBuilder(), 'Todo', {
content: 'string'
content: 'string',
});
Todo.build();
});

View File

@ -12,31 +12,31 @@ var ValidationError = j.ValidationError;
var INITIAL_NAME = 'Bert';
var NEW_NAME = 'Ernie';
var INVALID_DATA = {name: null};
var VALID_DATA = {name: INITIAL_NAME};
var INVALID_DATA = { name: null };
var VALID_DATA = { name: INITIAL_NAME };
describe('optional-validation', function () {
describe('optional-validation', function() {
before(function (done) {
before(function(done) {
db = getSchema();
ModelWithForceId = db.createModel(
'ModelWithForceId',
{ name: String },
{ forceId: true });
User = db.define('User', {
seq: {type: Number, index: true},
name: {type: String, index: true, sort: true},
email: {type: String, index: true},
birthday: {type: Date, index: true},
role: {type: String, index: true},
order: {type: Number, index: true, sort: true},
vip: {type: Boolean}
seq: { type: Number, index: true },
name: { type: String, index: true, sort: true },
email: { type: String, index: true },
birthday: { type: Date, index: true },
role: { type: String, index: true },
order: { type: Number, index: true, sort: true },
vip: { type: Boolean },
}, { forceId: true, strict: true });
db.automigrate(['ModelWithForceId', 'User'], done);
});
beforeEach(function (done) {
User.destroyAll(function () {
beforeEach(function(done) {
User.destroyAll(function() {
delete User.validations;
User.validatesPresenceOf('name');
done();
@ -44,7 +44,7 @@ describe('optional-validation', function () {
});
function expectValidationError(done) {
return function (err, result) {
return function(err, result) {
should.exist(err);
err.should.be.instanceOf(Error);
err.should.be.instanceOf(ValidationError);
@ -87,27 +87,27 @@ describe('optional-validation', function () {
}
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;
cb(err, d);
});
}
function createUser(cb) {
User.create(VALID_DATA, {validate: true}, cb);
User.create(VALID_DATA, { validate: true }, cb);
}
function callUpdateOrCreateWithExistingUserId(name, options, cb){
User.create({'name': 'Groover'}, function(err, user){
function callUpdateOrCreateWithExistingUserId(name, options, cb) {
User.create({ 'name': 'Groover' }, function(err, user) {
if (err) return cb(err);
var data = {name: name};
var data = { name: name };
data.id = user.id;
User.updateOrCreate(data, options, cb);
});
}
function getNewWhere() {
return {name: 'DoesNotExist' + (whereCount++)};
return { name: 'DoesNotExist' + (whereCount++) };
}
describe('forceId', function() {
@ -136,284 +136,283 @@ describe('optional-validation', function () {
});
});
describe('no model setting', function() {
describe('method create', function() {
it('should throw on create with validate:true with invalid data', function (done) {
User.create(INVALID_DATA, {validate: true}, expectValidationError(done));
it('should throw on create with validate:true with invalid data', function(done) {
User.create(INVALID_DATA, { validate: true }, expectValidationError(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));
it('should NOT throw on create with validate:false with invalid data', function(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) {
User.create(VALID_DATA, {validate: true}, expectCreateSuccess(done));
it('should NOT throw on create with validate:true with valid data', function(done) {
User.create(VALID_DATA, { validate: true }, expectCreateSuccess(done));
});
it('should NOT throw on create with validate:false with valid data', function (done) {
User.create(VALID_DATA, {validate: false}, expectCreateSuccess(done));
it('should NOT throw on create with validate:false with valid data', function(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));
});
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));
});
});
describe('method findOrCreate', function() {
it('should throw on findOrCreate with validate:true with invalid data', function (done) {
User.findOrCreate(getNewWhere(), INVALID_DATA, {validate: true}, expectValidationError(done));
it('should throw on findOrCreate with validate:true with invalid data', function(done) {
User.findOrCreate(getNewWhere(), INVALID_DATA, { validate: true }, expectValidationError(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));
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));
});
it('should NOT throw on findOrCreate with validate:true with valid data', function (done) {
User.findOrCreate(getNewWhere(), VALID_DATA, {validate: true}, expectCreateSuccess(done));
it('should NOT throw on findOrCreate with validate:true with valid data', function(done) {
User.findOrCreate(getNewWhere(), VALID_DATA, { validate: true }, expectCreateSuccess(done));
});
it('should NOT throw on findOrCreate with validate:false with valid data', function (done) {
User.findOrCreate(getNewWhere(), VALID_DATA, {validate: false}, expectCreateSuccess(done));
it('should NOT throw on findOrCreate with validate:false with valid data', function(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));
});
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));
});
});
describe('method updateOrCreate on existing data', function() {
it('should throw on updateOrCreate(id) with validate:true with invalid data', function (done) {
callUpdateOrCreateWithExistingUserId(null, {validate: true}, expectValidationError(done));
it('should throw on updateOrCreate(id) with validate:true with invalid data', function(done) {
callUpdateOrCreateWithExistingUserId(null, { validate: true }, expectValidationError(done));
});
it('should NOT throw on updateOrCreate(id) with validate:false with invalid data', function (done) {
callUpdateOrCreateWithExistingUserId(null, {validate: false}, expectChangeSuccess(INVALID_DATA, done));
it('should NOT throw on updateOrCreate(id) with validate:false with invalid data', function(done) {
callUpdateOrCreateWithExistingUserId(null, { validate: false }, expectChangeSuccess(INVALID_DATA, done));
});
it('should NOT throw on updateOrCreate(id) with validate:true with valid data', function (done) {
callUpdateOrCreateWithExistingUserId(NEW_NAME, {validate: true}, expectChangeSuccess(done));
it('should NOT throw on updateOrCreate(id) with validate:true with valid data', function(done) {
callUpdateOrCreateWithExistingUserId(NEW_NAME, { validate: true }, expectChangeSuccess(done));
});
it('should NOT throw on updateOrCreate(id) with validate:false with valid data', function (done) {
callUpdateOrCreateWithExistingUserId(NEW_NAME, {validate: false}, expectChangeSuccess(done));
it('should NOT throw on updateOrCreate(id) with validate:false with valid data', function(done) {
callUpdateOrCreateWithExistingUserId(NEW_NAME, { validate: false }, expectChangeSuccess(done));
});
// 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));
});
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));
});
});
describe('method save', function() {
it('should throw on save with {validate:true} with invalid data', function (done) {
createUserAndChangeName(null, function (err, d) {
d.save({validate: true}, expectValidationError(done));
it('should throw on save with {validate:true} with invalid data', function(done) {
createUserAndChangeName(null, function(err, d) {
d.save({ validate: true }, expectValidationError(done));
});
});
it('should NOT throw on save with {validate:false} with invalid data', function (done) {
createUserAndChangeName(null, function (err, d) {
d.save({validate: false}, expectChangeSuccess(INVALID_DATA, done));
it('should NOT throw on save with {validate:false} with invalid data', function(done) {
createUserAndChangeName(null, function(err, d) {
d.save({ validate: false }, expectChangeSuccess(INVALID_DATA, done));
});
});
it('should NOT throw on save with {validate:true} with valid data', function (done) {
createUserAndChangeName(NEW_NAME, function (err, d) {
d.save({validate: true}, expectChangeSuccess(done));
it('should NOT throw on save with {validate:true} with valid data', function(done) {
createUserAndChangeName(NEW_NAME, function(err, d) {
d.save({ validate: true }, expectChangeSuccess(done));
});
});
it('should NOT throw on save with {validate:false} with valid data', function (done) {
createUserAndChangeName(NEW_NAME, function (err, d) {
d.save({validate: false}, expectChangeSuccess(done));
it('should NOT throw on save with {validate:false} with valid data', function(done) {
createUserAndChangeName(NEW_NAME, function(err, d) {
d.save({ validate: false }, expectChangeSuccess(done));
});
});
it('should throw on save(cb) with invalid data', function (done) {
createUserAndChangeName(null, function (err, d) {
it('should throw on save(cb) with invalid data', function(done) {
createUserAndChangeName(null, function(err, d) {
d.save(expectValidationError(done));
});
});
it('should NOT throw on save(cb) with valid data', function (done) {
createUserAndChangeName(NEW_NAME, function (err, d) {
it('should NOT throw on save(cb) with valid data', function(done) {
createUserAndChangeName(NEW_NAME, function(err, d) {
d.save(expectChangeSuccess(done));
});
});
});
describe('method updateAttributes', function() {
it('should throw on updateAttributes with {validate:true} with invalid data', function (done) {
createUser(function (err, d) {
d.updateAttributes(INVALID_DATA, {validate: true}, expectValidationError(done));
it('should throw on updateAttributes with {validate:true} with invalid data', function(done) {
createUser(function(err, d) {
d.updateAttributes(INVALID_DATA, { validate: true }, expectValidationError(done));
});
});
it('should NOT throw on updateAttributes with {validate:false} with invalid data', function (done) {
createUser(function (err, d) {
d.updateAttributes(INVALID_DATA, {validate: false}, expectChangeSuccess(INVALID_DATA, done));
it('should NOT throw on updateAttributes with {validate:false} with invalid data', function(done) {
createUser(function(err, d) {
d.updateAttributes(INVALID_DATA, { validate: false }, expectChangeSuccess(INVALID_DATA, done));
});
});
it('should NOT throw on updateAttributes with {validate:true} with valid data', function (done) {
createUser(function (err, d) {
d.updateAttributes({'name': NEW_NAME}, {validate: true}, expectChangeSuccess(done));
it('should NOT throw on updateAttributes with {validate:true} with valid data', function(done) {
createUser(function(err, d) {
d.updateAttributes({ 'name': NEW_NAME }, { validate: true }, expectChangeSuccess(done));
});
});
it('should NOT throw on updateAttributes with {validate:false} with valid data', function (done) {
createUser(function (err, d) {
d.updateAttributes({'name': NEW_NAME}, {validate: false}, expectChangeSuccess(done));
it('should NOT throw on updateAttributes with {validate:false} with valid data', function(done) {
createUser(function(err, d) {
d.updateAttributes({ 'name': NEW_NAME }, { validate: false }, expectChangeSuccess(done));
});
});
it('should throw on updateAttributes(cb) with invalid data', function (done) {
createUser(function (err, d) {
it('should throw on updateAttributes(cb) with invalid data', function(done) {
createUser(function(err, d) {
d.updateAttributes(INVALID_DATA, expectValidationError(done));
});
});
it('should NOT throw on updateAttributes(cb) with valid data', function (done) {
createUser(function (err, d) {
d.updateAttributes({'name': NEW_NAME}, expectChangeSuccess(done));
it('should NOT throw on updateAttributes(cb) with valid data', function(done) {
createUser(function(err, d) {
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;
done();
});
describe('method create', function() {
it('should throw on create with validate:true with invalid data', function (done) {
User.create(INVALID_DATA, {validate: true}, expectValidationError(done));
it('should throw on create with validate:true with invalid data', function(done) {
User.create(INVALID_DATA, { validate: true }, expectValidationError(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));
it('should NOT throw on create with validate:false with invalid data', function(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) {
User.create(VALID_DATA, {validate: true}, expectCreateSuccess(done));
it('should NOT throw on create with validate:true with valid data', function(done) {
User.create(VALID_DATA, { validate: true }, expectCreateSuccess(done));
});
it('should NOT throw on create with validate:false with valid data', function (done) {
User.create(VALID_DATA, {validate: false}, expectCreateSuccess(done));
it('should NOT throw on create with validate:false with valid data', function(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));
});
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));
});
});
describe('method findOrCreate', function() {
it('should throw on findOrCreate with validate:true with invalid data', function (done) {
User.findOrCreate(getNewWhere(), INVALID_DATA, {validate: true}, expectValidationError(done));
it('should throw on findOrCreate with validate:true with invalid data', function(done) {
User.findOrCreate(getNewWhere(), INVALID_DATA, { validate: true }, expectValidationError(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));
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));
});
it('should NOT throw on findOrCreate with validate:true with valid data', function (done) {
User.findOrCreate(getNewWhere(), VALID_DATA, {validate: true}, expectCreateSuccess(done));
it('should NOT throw on findOrCreate with validate:true with valid data', function(done) {
User.findOrCreate(getNewWhere(), VALID_DATA, { validate: true }, expectCreateSuccess(done));
});
it('should NOT throw on findOrCreate with validate:false with valid data', function (done) {
User.findOrCreate(getNewWhere(), VALID_DATA, {validate: false}, expectCreateSuccess(done));
it('should NOT throw on findOrCreate with validate:false with valid data', function(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));
});
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));
});
});
describe('method updateOrCreate on existing data', function() {
it('should throw on updateOrCreate(id) with validate:true with invalid data', function (done) {
callUpdateOrCreateWithExistingUserId(null, {validate: true}, expectValidationError(done));
it('should throw on updateOrCreate(id) with validate:true with invalid data', function(done) {
callUpdateOrCreateWithExistingUserId(null, { validate: true }, expectValidationError(done));
});
it('should NOT throw on updateOrCreate(id) with validate:false with invalid data', function (done) {
callUpdateOrCreateWithExistingUserId(null, {validate: false}, expectChangeSuccess(INVALID_DATA, done));
it('should NOT throw on updateOrCreate(id) with validate:false with invalid data', function(done) {
callUpdateOrCreateWithExistingUserId(null, { validate: false }, expectChangeSuccess(INVALID_DATA, done));
});
it('should NOT throw on updateOrCreate(id) with validate:true with valid data', function (done) {
callUpdateOrCreateWithExistingUserId(NEW_NAME, {validate: true}, expectChangeSuccess(done));
it('should NOT throw on updateOrCreate(id) with validate:true with valid data', function(done) {
callUpdateOrCreateWithExistingUserId(NEW_NAME, { validate: true }, expectChangeSuccess(done));
});
it('should NOT throw on updateOrCreate(id) with validate:false with valid data', function (done) {
callUpdateOrCreateWithExistingUserId(NEW_NAME, {validate: false}, expectChangeSuccess(done));
it('should NOT throw on updateOrCreate(id) with validate:false with valid data', function(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));
});
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));
});
});
describe('method save', function() {
it('should throw on save with {validate:true} with invalid data', function (done) {
createUserAndChangeName(null, function (err, d) {
d.save({validate: true}, expectValidationError(done));
it('should throw on save with {validate:true} with invalid data', function(done) {
createUserAndChangeName(null, function(err, d) {
d.save({ validate: true }, expectValidationError(done));
});
});
it('should NOT throw on save with {validate:false} with invalid data', function (done) {
createUserAndChangeName(null, function (err, d) {
d.save({validate: false}, expectChangeSuccess(INVALID_DATA, done));
it('should NOT throw on save with {validate:false} with invalid data', function(done) {
createUserAndChangeName(null, function(err, d) {
d.save({ validate: false }, expectChangeSuccess(INVALID_DATA, done));
});
});
it('should NOT throw on save with {validate:true} with valid data', function (done) {
createUserAndChangeName(NEW_NAME, function (err, d) {
d.save({validate: true}, expectChangeSuccess(done));
it('should NOT throw on save with {validate:true} with valid data', function(done) {
createUserAndChangeName(NEW_NAME, function(err, d) {
d.save({ validate: true }, expectChangeSuccess(done));
});
});
it('should NOT throw on save with {validate:false} with valid data', function (done) {
createUserAndChangeName(NEW_NAME, function (err, d) {
d.save({validate: false}, expectChangeSuccess(done));
it('should NOT throw on save with {validate:false} with valid data', function(done) {
createUserAndChangeName(NEW_NAME, function(err, d) {
d.save({ validate: false }, expectChangeSuccess(done));
});
});
it('should NOT throw on save(cb) with invalid data', function (done) {
createUserAndChangeName(null, function (err, d) {
it('should NOT throw on save(cb) with invalid data', function(done) {
createUserAndChangeName(null, function(err, d) {
d.save(expectChangeSuccess(INVALID_DATA, done));
});
});
it('should NOT throw on save(cb) with valid data', function (done) {
createUserAndChangeName(NEW_NAME, function (err, d) {
it('should NOT throw on save(cb) with valid data', function(done) {
createUserAndChangeName(NEW_NAME, function(err, d) {
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;
done();
});
describe('method create', function() {
it('should throw on create with validate:true with invalid data', function (done) {
User.create(INVALID_DATA, {validate: true}, expectValidationError(done));
it('should throw on create with validate:true with invalid data', function(done) {
User.create(INVALID_DATA, { validate: true }, expectValidationError(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));
it('should NOT throw on create with validate:false with invalid data', function(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) {
User.create(VALID_DATA, {validate: true}, expectCreateSuccess(done));
it('should NOT throw on create with validate:true with valid data', function(done) {
User.create(VALID_DATA, { validate: true }, expectCreateSuccess(done));
});
it('should NOT throw on create with validate:false with valid data', function (done) {
User.create(VALID_DATA, {validate: false}, expectCreateSuccess(done));
it('should NOT throw on create with validate:false with valid data', function(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));
});
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));
});
});
describe('method findOrCreate', function() {
it('should throw on findOrCreate with validate:true with invalid data', function (done) {
User.findOrCreate(getNewWhere(), INVALID_DATA, {validate: true}, expectValidationError(done));
it('should throw on findOrCreate with validate:true with invalid data', function(done) {
User.findOrCreate(getNewWhere(), INVALID_DATA, { validate: true }, expectValidationError(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));
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));
});
it('should NOT throw on findOrCreate with validate:true with valid data', function (done) {
User.findOrCreate(getNewWhere(), VALID_DATA, {validate: true}, expectCreateSuccess(done));
it('should NOT throw on findOrCreate with validate:true with valid data', function(done) {
User.findOrCreate(getNewWhere(), VALID_DATA, { validate: true }, expectCreateSuccess(done));
});
it('should NOT throw on findOrCreate with validate:false with valid data', function (done) {
User.findOrCreate(getNewWhere(), VALID_DATA, {validate: false}, expectCreateSuccess(done));
it('should NOT throw on findOrCreate with validate:false with valid data', function(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));
});
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));
});
});
describe('method updateOrCreate on existing data', function() {
it('should throw on updateOrCreate(id) with validate:true with invalid data', function (done) {
callUpdateOrCreateWithExistingUserId(null, {validate: true}, expectValidationError(done));
it('should throw on updateOrCreate(id) with validate:true with invalid data', function(done) {
callUpdateOrCreateWithExistingUserId(null, { validate: true }, expectValidationError(done));
});
it('should NOT throw on updateOrCreate(id) with validate:false with invalid data', function (done) {
callUpdateOrCreateWithExistingUserId(null, {validate: false}, expectChangeSuccess(INVALID_DATA, done));
it('should NOT throw on updateOrCreate(id) with validate:false with invalid data', function(done) {
callUpdateOrCreateWithExistingUserId(null, { validate: false }, expectChangeSuccess(INVALID_DATA, done));
});
it('should NOT throw on updateOrCreate(id) with validate:true with valid data', function (done) {
callUpdateOrCreateWithExistingUserId(NEW_NAME, {validate: true}, expectChangeSuccess(done));
it('should NOT throw on updateOrCreate(id) with validate:true with valid data', function(done) {
callUpdateOrCreateWithExistingUserId(NEW_NAME, { validate: true }, expectChangeSuccess(done));
});
it('should NOT throw on updateOrCreate(id) with validate:false with valid data', function (done) {
callUpdateOrCreateWithExistingUserId(NEW_NAME, {validate: false}, expectChangeSuccess(done));
it('should NOT throw on updateOrCreate(id) with validate:false with valid data', function(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));
});
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));
});
});
describe('method save', function() {
it('should throw on save with {validate:true} with invalid data', function (done) {
createUserAndChangeName(null, function (err, d) {
it('should throw on save with {validate:true} with invalid data', function(done) {
createUserAndChangeName(null, function(err, d) {
d.save(options, expectValidationError(done));
});
});
it('should NOT throw on save with {validate:false} with invalid data', function (done) {
createUserAndChangeName(null, function (err, d) {
d.save({validate: false}, expectChangeSuccess(INVALID_DATA, done));
it('should NOT throw on save with {validate:false} with invalid data', function(done) {
createUserAndChangeName(null, function(err, d) {
d.save({ validate: false }, expectChangeSuccess(INVALID_DATA, done));
});
});
it('should NOT throw on save with {validate:true} with valid data', function (done) {
createUserAndChangeName(NEW_NAME, function (err, d) {
d.save({validate: true}, expectChangeSuccess(done));
it('should NOT throw on save with {validate:true} with valid data', function(done) {
createUserAndChangeName(NEW_NAME, function(err, d) {
d.save({ validate: true }, expectChangeSuccess(done));
});
});
it('should NOT throw on save with {validate:false} with valid data', function (done) {
createUserAndChangeName(NEW_NAME, function (err, d) {
d.save({validate: false}, expectChangeSuccess(done));
it('should NOT throw on save with {validate:false} with valid data', function(done) {
createUserAndChangeName(NEW_NAME, function(err, d) {
d.save({ validate: false }, expectChangeSuccess(done));
});
});
it('should throw on save(cb) with invalid data', function (done) {
createUserAndChangeName(null, function (err, d) {
it('should throw on save(cb) with invalid data', function(done) {
createUserAndChangeName(null, function(err, d) {
d.save(expectValidationError(done));
});
});
it('should NOT throw on save(cb) with valid data', function (done) {
createUserAndChangeName(NEW_NAME, function (err, d) {
it('should NOT throw on save(cb) with valid data', function(done) {
createUserAndChangeName(NEW_NAME, function(err, d) {
d.save(expectChangeSuccess(done));
});
});

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@ -8,16 +8,16 @@ var should = require('./init.js');
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.dataSource.should.eql(db);
var m = new Model;
m.getDataSource().should.eql(db);
});
it('should clone existing model', function () {
it('should clone existing model', function() {
SlaveModel = slave.copyModel(Model);
SlaveModel.dataSource.should.equal(slave);
slave.should.not.equal(db);
@ -27,30 +27,30 @@ describe('dataSource', function () {
sm.getDataSource().should.equal(slave);
});
it('should automigrate', function (done) {
it('should automigrate', function(done) {
db.automigrate(done);
});
it('should create transaction', function (done) {
it('should create transaction', function(done) {
var tr = db.transaction();
tr.connected.should.be.false;
tr.connecting.should.be.false;
var called = false;
tr.models.Model.create(Array(3), function () {
tr.models.Model.create(Array(3), function() {
called = true;
});
tr.connected.should.be.false;
tr.connecting.should.be.true;
db.models.Model.count(function (err, c) {
db.models.Model.count(function(err, c) {
should.not.exist(err);
should.exist(c);
c.should.equal(0);
called.should.be.false;
tr.exec(function () {
setTimeout(function () {
tr.exec(function() {
setTimeout(function() {
called.should.be.true;
db.models.Model.count(function (err, c) {
db.models.Model.count(function(err, c) {
c.should.equal(3);
done();
});

View File

@ -8,45 +8,45 @@ var should = require('./init.js');
var db, Railway, Station;
describe('scope', function () {
describe('scope', function() {
before(function () {
before(function() {
db = getSchema();
Railway = db.define('Railway', {
URID: {type: String, index: true}
URID: { type: String, index: true },
}, {
scopes: {
highSpeed: {
where: {
highSpeed: true
}
}
}
highSpeed: true,
},
},
},
});
Station = db.define('Station', {
USID: {type: String, index: true},
capacity: {type: Number, index: true},
thoughput: {type: Number, index: true},
isActive: {type: Boolean, index: true},
isUndeground: {type: Boolean, index: true}
USID: { type: String, index: true },
capacity: { type: Number, index: true },
thoughput: { type: Number, index: true },
isActive: { type: Boolean, index: true },
isUndeground: { type: Boolean, index: true },
});
});
beforeEach(function (done) {
Railway.destroyAll(function () {
beforeEach(function(done) {
Railway.destroyAll(function() {
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.highSpeed.should.be.function;
});
it('should define scope with query', function (done) {
Station.scope('active', {where: {isActive: true}});
it('should define scope with query', function(done) {
Station.scope('active', { where: { isActive: true }});
Station.scopes.should.have.property('active');
Station.active.create(function (err, station) {
Station.active.create(function(err, station) {
should.not.exist(err);
should.exist(station);
should.exist(station.isActive);
@ -55,35 +55,35 @@ describe('scope', function () {
});
});
it('should allow scope chaining', function (done) {
Station.scope('active', {where: {isActive: true}});
Station.scope('subway', {where: {isUndeground: true}});
Station.active.subway.create(function (err, station) {
it('should allow scope chaining', function(done) {
Station.scope('active', { where: { isActive: true }});
Station.scope('subway', { where: { isUndeground: true }});
Station.active.subway.create(function(err, station) {
should.not.exist(err);
should.exist(station);
station.isActive.should.be.true;
station.isUndeground.should.be.true;
done();
})
});
});
it('should query all', function (done) {
Station.scope('active', {where: {isActive: true}});
Station.scope('inactive', {where: {isActive: false}});
Station.scope('ground', {where: {isUndeground: true}});
Station.active.ground.create(function () {
Station.inactive.ground.create(function () {
Station.ground.inactive(function (err, ss) {
it('should query all', function(done) {
Station.scope('active', { where: { isActive: true }});
Station.scope('inactive', { where: { isActive: false }});
Station.scope('ground', { where: { isUndeground: true }});
Station.active.ground.create(function() {
Station.inactive.ground.create(function() {
Station.ground.inactive(function(err, ss) {
ss.should.have.lengthOf(1);
done();
});
});
});
});
it('should not cache any results', function (done) {
Station.scope('active', {where: {isActive: true}});
Station.active.create(function (err, s) {
it('should not cache any results', function(done) {
Station.scope('active', { where: { isActive: true }});
Station.active.create(function(err, s) {
if (err) return done(err);
s.isActive.should.be.true;
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();
Station = db.define('Station', {
name: {type: String, index: true},
order: {type: Number, index: true}
name: { type: String, 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);
});
beforeEach(function (done) {
beforeEach(function(done) {
Station.create({ name: 'a', order: 1 }, done);
});
beforeEach(function (done) {
beforeEach(function(done) {
Station.create({ name: 'b', order: 2 }, done);
});
beforeEach(function (done) {
beforeEach(function(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) {
stations[0].name.should.equal('c');
stations[0].order.should.equal(3);
@ -144,8 +144,8 @@ describe('scope - order', function () {
});
});
it('should override default scope order', function (done) {
Station.reverse({order: 'order ASC'}, function(err, stations) {
it('should override default scope order', function(done) {
Station.reverse({ order: 'order ASC' }, function(err, stations) {
stations[0].name.should.equal('a');
stations[0].order.should.equal(1);
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;
before(function () {
before(function() {
db = getSchema();
Station = db.define('Station', {
name: {type: String, index: true},
order: {type: Number, index: true},
active: {type: Boolean, index: true, default: true},
flagged: {type: Boolean, index: true, default: false}
name: { type: String, index: true },
order: { type: Number, index: true },
active: { type: Boolean, index: true, default: true },
flagged: { type: Boolean, index: true, default: false },
});
Station.scope('ordered', {order: 'order'});
Station.scope('active', {where: { active: true}});
Station.scope('inactive', {where: { active: false}});
Station.scope('flagged', {where: { flagged: true}});
Station.scope('ordered', { order: 'order' });
Station.scope('active', { where: { active: true }});
Station.scope('inactive', { where: { active: false }});
Station.scope('flagged', { where: { flagged: true }});
});
beforeEach(function (done) {
beforeEach(function(done) {
Station.destroyAll(done);
});
beforeEach(function (done) {
beforeEach(function(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) {
stationA = inst;
done();
});
});
beforeEach(function (done) {
beforeEach(function(done) {
Station.create({ name: 'd', order: 4, active: false }, done);
});
beforeEach(function (done) {
beforeEach(function(done) {
Station.create({ name: 'c', order: 3 }, done);
});
it('should find all - verify', function(done) {
Station.ordered(function(err, stations) {
should.not.exist(err);
stations.should.have.length(4);
stations[0].name.should.equal('a');
stations[1].name.should.equal('b');
stations[2].name.should.equal('c');
stations[3].name.should.equal('d');
done();
should.not.exist(err);
stations.should.have.length(4);
stations[0].name.should.equal('a');
stations[1].name.should.equal('b');
stations[2].name.should.equal('c');
stations[3].name.should.equal('d');
done();
});
});
it('should find one', function(done) {
Station.active.findOne(function(err, station) {
should.not.exist(err);
station.name.should.equal('a');
done();
should.not.exist(err);
station.name.should.equal('a');
done();
});
});
it('should find one - with filter', function(done) {
Station.active.findOne({ where: { name: 'c' } }, function(err, station) {
should.not.exist(err);
station.name.should.equal('c');
done();
Station.active.findOne({ where: { name: 'c' }}, function(err, station) {
should.not.exist(err);
station.name.should.equal('c');
done();
});
});
it('should find by id - match', function(done) {
Station.active.findById(stationA.id, function(err, station) {
should.not.exist(err);
station.name.should.equal('a');
done();
should.not.exist(err);
station.name.should.equal('a');
done();
});
});
it('should find by id - no match', function(done) {
Station.inactive.findById(stationA.id, function(err, station) {
should.not.exist(err);
should.not.exist(station);
done();
should.not.exist(err);
should.not.exist(station);
done();
});
});
it('should count all in scope - active', function(done) {
Station.active.count(function(err, count) {
should.not.exist(err);
count.should.equal(2);
done();
should.not.exist(err);
count.should.equal(2);
done();
});
});
it('should count all in scope - inactive', function(done) {
Station.inactive.count(function(err, count) {
should.not.exist(err);
count.should.equal(2);
done();
should.not.exist(err);
count.should.equal(2);
done();
});
});
it('should count filtered - active', function(done) {
Station.active.count({ order: { gt: 1 } }, function(err, count) {
should.not.exist(err);
count.should.equal(1);
done();
Station.active.count({ order: { gt: 1 }}, function(err, count) {
should.not.exist(err);
count.should.equal(1);
done();
});
});
it('should count filtered - inactive', function(done) {
Station.inactive.count({ order: 2 }, function(err, count) {
should.not.exist(err);
count.should.equal(1);
done();
should.not.exist(err);
count.should.equal(1);
done();
});
});
it('should allow updateAll', function(done) {
Station.inactive.updateAll({ flagged: true }, function(err, result) {
should.not.exist(err);
result.count.should.equal(2);
verify();
should.not.exist(err);
result.count.should.equal(2);
verify();
});
var verify = function() {
@ -293,9 +293,9 @@ describe('scope - filtered count, updateAll and destroyAll', function () {
it('should allow filtered updateAll', function(done) {
Station.ordered.updateAll({ active: true }, { flagged: true }, function(err, result) {
should.not.exist(err);
result.count.should.equal(2);
verify();
should.not.exist(err);
result.count.should.equal(2);
verify();
});
var verify = function() {
@ -309,8 +309,8 @@ describe('scope - filtered count, updateAll and destroyAll', function () {
it('should allow filtered destroyAll', function(done) {
Station.ordered.destroyAll({ active: false }, function(err) {
should.not.exist(err);
verify();
should.not.exist(err);
verify();
});
var verify = function() {
@ -318,9 +318,9 @@ describe('scope - filtered count, updateAll and destroyAll', function () {
should.not.exist(err);
count.should.equal(2);
Station.inactive.count(function(err, count) {
should.not.exist(err);
count.should.equal(0);
done();
should.not.exist(err);
count.should.equal(0);
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;
before(function () {
before(function() {
db = getSchema();
Image = db.define('Image', {name: String});
Video = db.define('Video', {name: String});
Image = db.define('Image', { 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() {
return {}; // could return a scope based on `this` (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() {
Image.destroyAll(function() {
Video.destroyAll(done);
})
});
});
});
beforeEach(function (done) {
beforeEach(function(done) {
Collection.create({ name: 'Images', modelName: 'Image' }, done);
});
beforeEach(function (done) {
beforeEach(function(done) {
Collection.create({ name: 'Videos', modelName: 'Video' }, done);
});
beforeEach(function (done) {
beforeEach(function(done) {
Collection.create({ name: 'Things', modelName: 'Unknown' }, done);
});
beforeEach(function (done) {
beforeEach(function(done) {
Image.create({ name: 'Image A' }, done);
});
beforeEach(function (done) {
beforeEach(function(done) {
Video.create({ name: 'Video A' }, 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);
coll.name.should.equal('Images');
coll.items(function(err, items) {
@ -389,7 +389,7 @@ describe('scope - dynamic target class', function () {
});
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);
coll.name.should.equal('Videos');
coll.items(function(err, items) {
@ -403,10 +403,10 @@ describe('scope - dynamic target class', function () {
});
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);
coll.modelName.should.equal('Unknown');
(function () {
(function() {
coll.items(function(err, items) {});
}).should.throw();
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();
Item = db.define('Item', {title: Number,creator:Number});
Item.scope('dynamicQuery', function () {
Item = db.define('Item', { title: Number, creator:Number });
Item.scope('dynamicQuery', function() {
seed++;
return {where:{creator:seed}};
})
return { where:{ creator:seed }};
});
});
beforeEach(function (done) {
Item.create({ title:1,creator:1 }, function () {
Item.create({ title:2,creator:2 },done)
})
beforeEach(function(done) {
Item.create({ title:1, creator:1 }, function() {
Item.create({ title:2, creator:2 }, done);
});
});
it('should deduce item by runtime creator', function (done) {
Item.dynamicQuery.findOne(function (err,firstQuery) {
it('should deduce item by runtime creator', function(done) {
Item.dynamicQuery.findOne(function(err, firstQuery) {
should.not.exist(err);
firstQuery.title.should.equal(1);
Item.dynamicQuery.findOne(function (err,secondQuery) {
Item.dynamicQuery.findOne(function(err, secondQuery) {
should.not.exist(err);
secondQuery.title.should.equal(2);
done();
})
})
})
});
});
});
});

View File

@ -28,12 +28,12 @@ function context(name, tests) {
EXT_EXP[name] = {};
group_name = name;
tests({
before: function (f) {
before: function(f) {
it('setUp', f);
},
after: function (f) {
after: function(f) {
it('tearDown', f);
}
},
});
group_name = false;
}

View File

@ -12,32 +12,32 @@ var should = require('./init.js');
var db, TransientModel, Person, Widget, Item;
var getTransientDataSource = function(settings) {
return new DataSource('transient', settings);
return new DataSource('transient', settings);
};
describe('Transient connector', function () {
before(function () {
describe('Transient connector', function() {
before(function() {
db = getTransientDataSource();
TransientModel = db.define('TransientModel', {}, { idInjection: false });
Person = TransientModel.extend('Person', {name: String});
Person = TransientModel.extend('Person', { name: String });
Person.attachTo(db);
Widget = db.define('Widget', {name: String});
Widget = db.define('Widget', { name: String });
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) {
should.not.exist(Person.definition.properties.id);
should.exist(Person.definition.properties.name);
Person.create({ name: 'Wilma' }, function(err, inst) {
should.not.exist(err);
inst.toObject().should.eql({ name: 'Wilma' });
Person.count(function(err, count) {
should.not.exist(err);
count.should.equal(0);
@ -45,18 +45,18 @@ describe('Transient connector', function () {
});
});
});
it('should generate a random string id', function(done) {
should.exist(Widget.definition.properties.id);
should.exist(Widget.definition.properties.name);
Widget.definition.properties.id.type.should.equal(String);
Widget.create({ name: 'Thing' }, function(err, inst) {
should.not.exist(err);
inst.id.should.match(/^[0-9a-fA-F]{24}$/);
inst.name.should.equal('Thing');
Widget.findById(inst.id, function(err, widget) {
should.not.exist(err);
should.not.exist(widget);
@ -64,17 +64,17 @@ describe('Transient connector', function () {
});
});
});
it('should generate a random number id', function(done) {
should.exist(Item.definition.properties.id);
should.exist(Item.definition.properties.name);
Item.definition.properties.id.type.should.equal(Number);
Item.create({ name: 'Example' }, function(err, inst) {
should.not.exist(err);
inst.name.should.equal('Example');
Item.count(function(err, count) {
should.not.exist(err);
count.should.equal(0);
@ -82,5 +82,5 @@ describe('Transient connector', function () {
});
});
});
});

View File

@ -12,54 +12,54 @@ var mergeIncludes = utils.mergeIncludes;
var sortObjectsByIds = utils.sortObjectsByIds;
var uniq = utils.uniq;
describe('util.fieldsToArray', function () {
describe('util.fieldsToArray', function() {
function sample(fields, excludeUnknown) {
var properties = ['foo', 'bar', 'bat', 'baz'];
return {
expect: function (arr) {
expect: function(arr) {
should.deepEqual(fieldsToArray(fields, properties, excludeUnknown), arr);
}
},
};
}
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(null).expect(undefined);
sample({}).expect(undefined);
sample('foo').expect(['foo']);
sample(['foo']).expect(['foo']);
sample({'foo': 1}).expect(['foo']);
sample({'bat': true}).expect(['bat']);
sample({'bat': 0}).expect(['foo', 'bar', 'baz']);
sample({'bat': false}).expect(['foo', 'bar', 'baz']);
sample({ 'foo': 1 }).expect(['foo']);
sample({ 'bat': true }).expect(['bat']);
sample({ 'bat': 0 }).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(null, true).expect(undefined);
sample({}, true).expect(undefined);
sample('foo', true).expect(['foo']);
sample(['foo', 'unknown'], true).expect(['foo']);
sample({'foo': 1, unknown: 1}, true).expect(['foo']);
sample({'bat': true, unknown: true}, true).expect(['bat']);
sample({'bat': 0}, true).expect(['foo', 'bar', 'baz']);
sample({'bat': false}, true).expect(['foo', 'bar', 'baz']);
sample({ 'foo': 1, unknown: 1 }, true).expect(['foo']);
sample({ 'bat': true, unknown: true }, true).expect(['bat']);
sample({ 'bat': 0 }, true).expect(['foo', 'bar', 'baz']);
sample({ 'bat': false }, true).expect(['foo', 'bar', 'baz']);
});
});
describe('util.removeUndefined', function () {
it('Remove undefined values from the query object', function () {
var q1 = {where: {x: 1, y: undefined}};
should.deepEqual(removeUndefined(q1), {where: {x: 1}});
describe('util.removeUndefined', function() {
it('Remove undefined values from the query object', function() {
var q1 = { where: { x: 1, y: undefined }};
should.deepEqual(removeUndefined(q1), { where: { x: 1 }});
var q2 = {where: {x: 1, y: 2}};
should.deepEqual(removeUndefined(q2), {where: {x: 1, y: 2}});
var q2 = { where: { x: 1, y: 2 }};
should.deepEqual(removeUndefined(q2), { where: { x: 1, y: 2 }});
var q3 = {where: {x: 1, y: {in: [2, undefined]}}};
should.deepEqual(removeUndefined(q3), {where: {x: 1, y: {in: [2]}}});
var q3 = { where: { x: 1, y: { in: [2, undefined] }}};
should.deepEqual(removeUndefined(q3), { where: { x: 1, y: { in: [2] }}});
should.equal(removeUndefined(null), null);
@ -68,21 +68,21 @@ describe('util.removeUndefined', function () {
should.equal(removeUndefined('x'), 'x');
var date = new Date();
var q4 = {where: {x: 1, y: date}};
should.deepEqual(removeUndefined(q4), {where: {x: 1, y: date}});
var q4 = { where: { x: 1, y: date }};
should.deepEqual(removeUndefined(q4), { where: { x: 1, y: date }});
// test handling of undefined
var q5 = {where: {x: 1, y: undefined}};
should.deepEqual(removeUndefined(q5, 'nullify'), {where: {x: 1, y: null}});
var q5 = { where: { x: 1, y: undefined }};
should.deepEqual(removeUndefined(q5, 'nullify'), { where: { x: 1, y: null }});
var q6 = {where: {x: 1, y: undefined}};
(function(){ removeUndefined(q6, 'throw') }).should.throw(/`undefined` in query/);
var q6 = { where: { x: 1, y: undefined }};
(function() { removeUndefined(q6, 'throw'); }).should.throw(/`undefined` in query/);
});
});
describe('util.parseSettings', function () {
it('Parse a full url into a settings object', function () {
describe('util.parseSettings', function() {
it('Parse a full url into a settings object', function() {
var url = 'mongodb://x:y@localhost:27017/mydb?w=2';
var settings = utils.parseSettings(url);
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 settings = utils.parseSettings(url);
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 settings = utils.parseSettings(url);
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 settings = utils.parseSettings(url);
should.equal(settings.hostname, '');
@ -144,12 +144,12 @@ describe('util.parseSettings', function () {
});
describe('mergeSettings', function () {
it('should merge settings correctly', function () {
describe('mergeSettings', function() {
it('should merge settings correctly', function() {
var src = { base: 'User',
relations: { accessTokens: { model: 'accessToken', type: 'hasMany',
foreignKey: 'userId' },
account: { model: 'account', type: 'belongsTo' } },
account: { model: 'account', type: 'belongsTo' }},
acls: [
{ accessType: '*',
permission: 'DENY',
@ -163,7 +163,7 @@ describe('mergeSettings', function () {
{ permission: 'ALLOW',
property: 'findById',
principalType: 'ROLE',
principalId: '$owner' }
principalId: '$owner' },
] };
var tgt = { strict: false,
acls: [
@ -174,7 +174,7 @@ describe('mergeSettings', function () {
{ principalType: 'ROLE',
principalId: '$owner',
permission: 'ALLOW',
property: 'removeById' }
property: 'removeById' },
],
maxTTL: 31556926,
ttl: 1209600 };
@ -203,20 +203,20 @@ describe('mergeSettings', function () {
{ permission: 'ALLOW',
property: 'findById',
principalType: 'ROLE',
principalId: '$owner' }
principalId: '$owner' },
],
maxTTL: 31556926,
ttl: 1209600,
base: 'User',
relations: { accessTokens: { model: 'accessToken', type: 'hasMany',
foreignKey: 'userId' },
account: { model: 'account', type: 'belongsTo' } } };
account: { model: 'account', type: 'belongsTo' }}};
should.deepEqual(dst.acls, expected.acls, 'Merged settings should match the expectation');
});
});
describe('sortObjectsByIds', function () {
describe('sortObjectsByIds', function() {
var items = [
{ id: 1, name: 'a' },
@ -224,7 +224,7 @@ describe('sortObjectsByIds', function () {
{ id: 3, name: 'c' },
{ id: 4, name: 'd' },
{ id: 5, name: 'e' },
{ id: 6, name: 'f' }
{ id: 6, name: 'f' },
];
it('should sort', function() {
@ -247,7 +247,7 @@ describe('sortObjectsByIds', function () {
});
describe('util.mergeIncludes', function () {
describe('util.mergeIncludes', function() {
function checkInputOutput(baseInclude, updateInclude, expectedInclude) {
var mergedInclude = mergeIncludes(baseInclude, updateInclude);
@ -259,8 +259,8 @@ describe('util.mergeIncludes', function () {
var baseInclude = 'relation1';
var updateInclude = 'relation2';
var expectedInclude = [
{relation2: true},
{relation1: true}
{ relation2: true },
{ relation1: true },
];
checkInputOutput(baseInclude, updateInclude, expectedInclude);
});
@ -269,18 +269,18 @@ describe('util.mergeIncludes', function () {
var baseInclude = 'relation1';
var updateInclude = ['relation2'];
var expectedInclude = [
{relation2: true},
{relation1: true}
{ relation2: true },
{ relation1: true },
];
checkInputOutput(baseInclude, updateInclude, expectedInclude);
});
it('Merge string & object values to object', function() {
var baseInclude = ['relation1'];
var updateInclude = {relation2: 'relation2Include'};
var updateInclude = { relation2: 'relation2Include' };
var expectedInclude = [
{relation2: 'relation2Include'},
{relation1: true}
{ relation2: 'relation2Include' },
{ relation1: true },
];
checkInputOutput(baseInclude, updateInclude, expectedInclude);
});
@ -289,37 +289,37 @@ describe('util.mergeIncludes', function () {
var baseInclude = ['relation1'];
var updateInclude = ['relation2'];
var expectedInclude = [
{relation2: true},
{relation1: true}
{ relation2: true },
{ relation1: true },
];
checkInputOutput(baseInclude, updateInclude, expectedInclude);
});
it('Merge array & object values to object', function() {
var baseInclude = ['relation1'];
var updateInclude = {relation2: 'relation2Include'};
var updateInclude = { relation2: 'relation2Include' };
var expectedInclude = [
{relation2: 'relation2Include'},
{relation1: true}
{ relation2: 'relation2Include' },
{ relation1: true },
];
checkInputOutput(baseInclude, updateInclude, expectedInclude);
});
it('Merge object & object values to object', function() {
var baseInclude = {relation1: 'relation1Include'};
var updateInclude = {relation2: 'relation2Include'};
var baseInclude = { relation1: 'relation1Include' };
var updateInclude = { relation2: 'relation2Include' };
var expectedInclude = [
{relation2: 'relation2Include'},
{relation1: 'relation1Include'}
{ relation2: 'relation2Include' },
{ relation1: 'relation1Include' },
];
checkInputOutput(baseInclude, updateInclude, expectedInclude);
});
it('Override property collision with update value', function() {
var baseInclude = {relation1: 'baseValue'};
var updateInclude = {relation1: 'updateValue'};
var baseInclude = { relation1: 'baseValue' };
var updateInclude = { relation1: 'updateValue' };
var expectedInclude = [
{relation1: 'updateValue'}
{ relation1: 'updateValue' },
];
checkInputOutput(baseInclude, updateInclude, expectedInclude);
});
@ -327,9 +327,9 @@ describe('util.mergeIncludes', function () {
it('Merge string includes & include with relation syntax properly',
function() {
var baseInclude = 'relation1';
var updateInclude = {relation: 'relation1'};
var updateInclude = { relation: 'relation1' };
var expectedInclude = [
{relation: 'relation1'}
{ relation: 'relation1' },
];
checkInputOutput(baseInclude, updateInclude, expectedInclude);
});
@ -338,10 +338,10 @@ describe('util.mergeIncludes', function () {
var baseInclude = 'relation1';
var updateInclude = {
relation: 'relation1',
scope: {include: 'relation2'}
scope: { include: 'relation2' },
};
var expectedInclude = [
{relation: 'relation1', scope: {include: 'relation2'}}
{ relation: 'relation1', scope: { include: 'relation2' }},
];
checkInputOutput(baseInclude, updateInclude, expectedInclude);
});
@ -352,39 +352,39 @@ describe('util.mergeIncludes', function () {
var baseInclude = ['relation2'];
var updateInclude = {
relation: 'relation1',
scope: {include: 'relation2'}
scope: { include: 'relation2' },
};
var expectedInclude = [{
relation: 'relation1',
scope: {include: 'relation2'}
}, {relation2: true}];
scope: { include: 'relation2' },
}, { relation2: true }];
checkInputOutput(baseInclude, updateInclude, expectedInclude);
//w & w/o relation syntax - collision
baseInclude = ['relation1'];
updateInclude = {relation: 'relation1', scope: {include: 'relation2'}};
updateInclude = { relation: 'relation1', scope: { include: 'relation2' }};
expectedInclude =
[{relation: 'relation1', scope: {include: 'relation2'}}];
[{ relation: 'relation1', scope: { include: 'relation2' }}];
checkInputOutput(baseInclude, updateInclude, expectedInclude);
//w & w/o relation syntax - collision
baseInclude = {relation: 'relation1', scope: {include: 'relation2'}};
baseInclude = { relation: 'relation1', scope: { include: 'relation2' }};
updateInclude = ['relation1'];
expectedInclude = [{relation1: true}];
expectedInclude = [{ relation1: true }];
checkInputOutput(baseInclude, updateInclude, expectedInclude);
});
it('Merge includes with mixture of strings, arrays & objects properly', function() {
var baseInclude = ['relation1', {relation2: true},
{relation: 'relation3', scope: {where: {id: 'some id'}}},
{relation: 'relation5', scope: {where: {id: 'some id'}}}
var baseInclude = ['relation1', { relation2: true },
{ relation: 'relation3', scope: { where: { id: 'some id' }}},
{ relation: 'relation5', scope: { where: { id: 'some id' }}},
];
var updateInclude = ['relation4', {relation3: true},
{relation: 'relation2', scope: {where: {id: 'some id'}}}];
var expectedInclude = [{relation4: true}, {relation3: true},
{relation: 'relation2', scope: {where: {id: 'some id'}}},
{relation1: true},
{relation: 'relation5', scope: {where: {id: 'some id'}}}];
var updateInclude = ['relation4', { relation3: true },
{ relation: 'relation2', scope: { where: { id: 'some id' }}}];
var expectedInclude = [{ relation4: true }, { relation3: true },
{ relation: 'relation2', scope: { where: { id: 'some id' }}},
{ relation1: true },
{ relation: 'relation5', scope: { where: { id: 'some id' }}}];
checkInputOutput(baseInclude, updateInclude, expectedInclude);
});
});
@ -457,18 +457,18 @@ describe('util.toRegExp', function() {
context('with a regex string', function() {
it('should return a RegExp object when no regex flags are provided',
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',
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',
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() {

View File

@ -18,15 +18,15 @@ function getValidAttributes() {
age: 26,
gender: 'male',
createdByAdmin: false,
createdByScript: true
createdByScript: true,
};
}
describe('validations', function () {
describe('validations', function() {
var User, Entry;
before(function (done) {
before(function(done) {
db = getSchema();
User = db.define('User', {
email: String,
@ -39,33 +39,33 @@ describe('validations', function () {
pendingPeriod: Number,
createdByAdmin: Boolean,
createdByScript: Boolean,
updatedAt: Date
updatedAt: Date,
});
Entry = db.define('Entry', {
id: { type: 'string', id: true, generated: false },
name: { type: 'string' }
name: { type: 'string' },
});
Entry.validatesUniquenessOf('id');
db.automigrate(done);
});
beforeEach(function (done) {
User.destroyAll(function () {
beforeEach(function(done) {
User.destroyAll(function() {
delete User.validations;
done();
});
});
after(function () {
after(function() {
// db.disconnect();
});
describe('commons', function () {
describe('commons', function() {
describe('skipping', function () {
describe('skipping', function() {
it('should NOT skip when `if` is fulfilled', function () {
User.validatesPresenceOf('pendingPeriod', {if: 'createdByAdmin'});
it('should NOT skip when `if` is fulfilled', function() {
User.validatesPresenceOf('pendingPeriod', { if: 'createdByAdmin' });
var user = new User;
user.createdByAdmin = true;
user.isValid().should.be.false;
@ -74,8 +74,8 @@ describe('validations', function () {
user.isValid().should.be.true;
});
it('should skip when `if` is NOT fulfilled', function () {
User.validatesPresenceOf('pendingPeriod', {if: 'createdByAdmin'});
it('should skip when `if` is NOT fulfilled', function() {
User.validatesPresenceOf('pendingPeriod', { if: 'createdByAdmin' });
var user = new User;
user.createdByAdmin = false;
user.isValid().should.be.true;
@ -84,8 +84,8 @@ describe('validations', function () {
user.isValid().should.be.true;
});
it('should NOT skip when `unless` is fulfilled', function () {
User.validatesPresenceOf('pendingPeriod', {unless: 'createdByAdmin'});
it('should NOT skip when `unless` is fulfilled', function() {
User.validatesPresenceOf('pendingPeriod', { unless: 'createdByAdmin' });
var user = new User;
user.createdByAdmin = false;
user.isValid().should.be.false;
@ -94,8 +94,8 @@ describe('validations', function () {
user.isValid().should.be.true;
});
it('should skip when `unless` is NOT fulfilled', function () {
User.validatesPresenceOf('pendingPeriod', {unless: 'createdByAdmin'});
it('should skip when `unless` is NOT fulfilled', function() {
User.validatesPresenceOf('pendingPeriod', { unless: 'createdByAdmin' });
var user = new User;
user.createdByAdmin = 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) {
User.validateAsync('pendingPeriod', function (err, done) {
it('should skip when `if` is NOT fulfilled', function(done) {
User.validateAsync('pendingPeriod', function(err, done) {
if (!this.pendingPeriod) err();
done();
}, {if: 'createdByAdmin', code: 'presence', message: 'can\'t be blank'});
}, { if: 'createdByAdmin', code: 'presence', message: 'can\'t be blank' });
var user = new User;
user.createdByAdmin = false;
user.isValid(function (valid) {
user.isValid(function(valid) {
valid.should.be.true;
user.errors.should.be.false;
done();
});
});
it('should NOT skip when `if` is fulfilled', function (done) {
User.validateAsync('pendingPeriod', function (err, done) {
it('should NOT skip when `if` is fulfilled', function(done) {
User.validateAsync('pendingPeriod', function(err, done) {
if (!this.pendingPeriod) err();
done();
}, {if: 'createdByAdmin', code: 'presence', message: 'can\'t be blank'});
}, { if: 'createdByAdmin', code: 'presence', message: 'can\'t be blank' });
var user = new User;
user.createdByAdmin = true;
user.isValid(function (valid) {
user.isValid(function(valid) {
valid.should.be.false;
user.errors.pendingPeriod.should.eql(['can\'t be blank']);
done();
});
});
it('should skip when `unless` is NOT fulfilled', function (done) {
User.validateAsync('pendingPeriod', function (err, done) {
it('should skip when `unless` is NOT fulfilled', function(done) {
User.validateAsync('pendingPeriod', function(err, done) {
if (!this.pendingPeriod) err();
done();
}, {unless: 'createdByAdmin', code: 'presence', message: 'can\'t be blank'});
}, { unless: 'createdByAdmin', code: 'presence', message: 'can\'t be blank' });
var user = new User;
user.createdByAdmin = true;
user.isValid(function (valid) {
user.isValid(function(valid) {
valid.should.be.true;
user.errors.should.be.false;
done();
});
});
it('should NOT skip when `unless` is fulfilled', function (done) {
User.validateAsync('pendingPeriod', function (err, done) {
it('should NOT skip when `unless` is fulfilled', function(done) {
User.validateAsync('pendingPeriod', function(err, done) {
if (!this.pendingPeriod) err();
done();
}, {unless: 'createdByAdmin', code: 'presence', message: 'can\'t be blank'});
}, { unless: 'createdByAdmin', code: 'presence', message: 'can\'t be blank' });
var user = new User;
user.createdByAdmin = false;
user.isValid(function (valid) {
user.isValid(function(valid) {
valid.should.be.false;
user.errors.pendingPeriod.should.eql(['can\'t be blank']);
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;
User.validatesPresenceOf('name');
User.create(function (e, u) {
User.create(function(e, u) {
should.exist(e);
User.create({name: 'Valid'}, function (e, d) {
User.create({ name: 'Valid' }, function(e, d) {
should.not.exist(e);
done();
});
});
});
it('should work on update', function (done) {
it('should work on update', function(done) {
delete User.validations;
User.validatesPresenceOf('name');
User.create({name: 'Valid'}, function (e, d) {
d.updateAttribute('name', null, function (e) {
User.create({ name: 'Valid' }, function(e, d) {
d.updateAttribute('name', null, function(e) {
should.exist(e);
e.should.be.instanceOf(Error);
e.should.be.instanceOf(ValidationError);
d.updateAttribute('name', 'Vasiliy', function (e) {
d.updateAttribute('name', 'Vasiliy', function(e) {
should.not.exist(e);
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;
User.validatesPresenceOf('name');
User.create(function (e, u) {
User.create(function(e, u) {
should.exist(e);
e.details.codes.name.should.eql(['presence']);
done();
});
});
it('should allow to modify error after validation', function (done) {
User.afterValidate = function (next) {
it('should allow to modify error after validation', function(done) {
User.afterValidate = function(next) {
next();
};
done();
@ -252,7 +252,7 @@ describe('validations', function () {
it('should include validation messages in err.message', function(done) {
delete User.validations;
User.validatesPresenceOf('name');
User.create(function (e, u) {
User.create(function(e, u) {
should.exist(e);
e.message.should.match(/`name` can't be blank/);
done();
@ -262,7 +262,7 @@ describe('validations', function () {
it('should include property value in err.message', function(done) {
delete User.validations;
User.validatesPresenceOf('name');
User.create(function (e, u) {
User.create(function(e, u) {
should.exist(e);
e.message.should.match(/`name` can't be blank \(value: undefined\)/);
done();
@ -272,7 +272,7 @@ describe('validations', function () {
it('should include model name in err.message', function(done) {
delete User.validations;
User.validatesPresenceOf('name');
User.create(function (e, u) {
User.create(function(e, u) {
should.exist(e);
e.message.should.match(/`User` instance/i);
done();
@ -280,7 +280,7 @@ describe('validations', function () {
});
it('should return validation metadata', function() {
var expected = {name:[{validation: 'presence', options: {}}]};
var expected = { name:[{ validation: 'presence', options: {}}] };
delete User.validations;
User.validatesPresenceOf('name');
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');
var validations = User.validations;
validations.name.should.eql([{validation: 'presence', options: {}}]);
validations.email.should.eql([{validation: 'presence', options: {}}]);
validations.name.should.eql([{ validation: 'presence', options: {}}]);
validations.email.should.eql([{ validation: 'presence', options: {}}]);
var u = new User;
u.isValid().should.not.be.true;
@ -324,10 +324,10 @@ describe('validations', function () {
u.isValid().should.be.true;
});
it('should skip validation by property (if/unless)', function () {
User.validatesPresenceOf('domain', {unless: 'createdByScript'});
it('should skip validation by property (if/unless)', function() {
User.validatesPresenceOf('domain', { unless: 'createdByScript' });
var user = new User(getValidAttributes())
var user = new User(getValidAttributes());
user.isValid().should.be.true;
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' });
var u = new User({reserved: 'foo', locked: true});
var u = new User({ reserved: 'foo', locked: true });
u.isValid().should.not.be.true;
u.reserved = null;
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;
});
});
describe('uniqueness', function () {
it('should validate uniqueness', function (done) {
describe('uniqueness', function() {
it('should validate uniqueness', function(done) {
User.validatesUniquenessOf('email');
var u = new User({email: 'hey'});
Boolean(u.isValid(function (valid) {
var u = new User({ email: 'hey' });
Boolean(u.isValid(function(valid) {
valid.should.be.true;
u.save(function () {
var u2 = new User({email: 'hey'});
u2.isValid(function (valid) {
u.save(function() {
var u2 = new User({ email: 'hey' });
u2.isValid(function(valid) {
valid.should.be.false;
done();
});
@ -370,14 +370,14 @@ describe('validations', function () {
})).should.be.false;
});
it('should handle same object modification', function (done) {
it('should handle same object modification', function(done) {
User.validatesUniquenessOf('email');
var u = new User({email: 'hey'});
Boolean(u.isValid(function (valid) {
var u = new User({ email: 'hey' });
Boolean(u.isValid(function(valid) {
valid.should.be.true;
u.save(function () {
u.save(function() {
u.name = 'Goghi';
u.isValid(function (valid) {
u.isValid(function(valid) {
valid.should.be.true;
u.save(done);
});
@ -390,7 +390,7 @@ describe('validations', function () {
var EMAIL = 'user@xample.com';
var SiteUser = db.define('SiteUser', {
siteId: String,
email: String
email: String,
});
SiteUser.validatesUniquenessOf('email', { scopedTo: ['siteId'] });
async.waterfall([
@ -413,7 +413,7 @@ describe('validations', function () {
valid.should.be.false;
next();
});
}
},
], function(err) {
if (err && err.name == 'ValidationError') {
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');
var u = new User({email: ' '});
Boolean(u.isValid(function (valid) {
var u = new User({ email: ' ' });
Boolean(u.isValid(function(valid) {
valid.should.be.true;
u.save(function () {
var u2 = new User({email: null});
u2.isValid(function (valid) {
u.save(function() {
var u2 = new User({ email: null });
u2.isValid(function(valid) {
valid.should.be.true;
done();
});
@ -437,31 +437,31 @@ describe('validations', function () {
})).should.be.false;
});
it('should work with if/unless', function (done) {
it('should work with if/unless', function(done) {
User.validatesUniquenessOf('email', {
if: function() { return true; },
unless: function() { return false; }
unless: function() { return false; },
});
var u = new User({email: 'hello'});
Boolean(u.isValid(function (valid) {
var u = new User({ email: 'hello' });
Boolean(u.isValid(function(valid) {
valid.should.be.true;
done();
})).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) {
var e = new Entry({ id: 'entry' });
Boolean(e.isValid(function (valid) {
Boolean(e.isValid(function(valid) {
valid.should.be.false;
done();
})).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) {
Boolean(e.isValid(function (valid) {
Boolean(e.isValid(function(valid) {
valid.should.be.true;
done();
})).should.be.false;
@ -469,83 +469,83 @@ describe('validations', function () {
});
});
describe('format', function () {
describe('format', function() {
it('should validate format');
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 });
var u = new User({});
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 });
var u = new User({ email: null });
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+$/ });
var u = new User({});
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+$/ });
var u = new User({ email: null });
u.isValid().should.be.false;
});
});
describe('numericality', function () {
describe('numericality', function() {
it('should validate numericality');
});
describe('inclusion', function () {
describe('inclusion', function() {
it('should validate inclusion');
});
describe('exclusion', function () {
describe('exclusion', function() {
it('should validate exclusion');
});
describe('length', function () {
describe('length', function() {
it('should validate length');
});
describe('custom', function () {
describe('custom', function() {
it('should validate using custom sync validation', function() {
User.validate('email', function (err) {
User.validate('email', function(err) {
if (this.email === 'hello') err();
}, { code: 'invalid-email' });
var u = new User({email: 'hello'});
var u = new User({ email: 'hello' });
Boolean(u.isValid()).should.be.false;
u.errors.codes.should.eql({ email: ['invalid-email'] });
});
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') {
this.errors.add('email', 'Cannot be `' + this.email + '`', 'invalid-email');
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;
u.errors.should.eql({ email: ['Cannot be `hello`'] });
u.errors.codes.should.eql({ email: ['invalid-email'] });
});
it('should validate using custom async validation', function(done) {
User.validateAsync('email', function (err, next) {
User.validateAsync('email', function(err, next) {
process.nextTick(next);
}, {
if: function() { return true; },
unless: function() { return false; }
unless: function() { return false; },
});
var u = new User({email: 'hello'});
Boolean(u.isValid(function (valid) {
var u = new User({ email: 'hello' });
Boolean(u.isValid(function(valid) {
valid.should.be.true;
done();
})).should.be.false;
@ -578,7 +578,7 @@ describe('validations', function () {
it('should truncate long arrays', function() {
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)
.should.equal('`prop` is invalid (value: [ { a...} ]).');
});
@ -611,7 +611,7 @@ describe('validations', function () {
var obj = {
errors: errorVal,
toJSON: function() { return jsonVal; }
toJSON: function() { return jsonVal; },
};
return new ValidationError(obj);
}