Merge pull request #1146 from strongloop/2.x_eslint

2.x eslint
This commit is contained in:
Amirali Jafarian 2016-10-19 21:24:56 -04:00 committed by GitHub
commit c96f471efd
83 changed files with 2463 additions and 2370 deletions

View File

@ -6,8 +6,9 @@
"ignoreUrls": true,
"ignorePattern": "^\\s*var\\s.+=\\s*(require\\s*\\()|(/)"
}],
// NOTE(bajtos) we should eventuall remove this override
// NOTE we should eventually remove this override
// and fix all of those 100+ violations
"one-var": "off"
"one-var": "off",
"no-unused-expressions": "off"
}
}
}

View File

@ -2,6 +2,7 @@
// Node module: loopback-datasource-juggler
// This file is licensed under the MIT License.
// License text available at https://opensource.org/licenses/MIT
'use strict';
var DataSource = require('../../loopback-datasource-juggler').DataSource;
var ModelBuilder = require('../../loopback-datasource-juggler').ModelBuilder;
@ -10,14 +11,14 @@ 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',
{'platform': 'apns',
'apns': {
'pushOptions': {
'gateway': 'gateway.sandbox.push.apple.com',
@ -33,7 +34,7 @@ var application = {
'interval': 300,
},
}},
] };
]};
console.log(new Application(application).toObject());
@ -59,8 +60,8 @@ var user = {
},
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: [],
};
@ -69,7 +70,7 @@ var user = {
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);

View File

@ -2,18 +2,19 @@
// Node module: loopback-datasource-juggler
// This file is licensed under the MIT License.
// License text available at https://opensource.org/licenses/MIT
'use strict';
var ModelBuilder = require('../../loopback-datasource-juggler').ModelBuilder;
var modelBuilder = new ModelBuilder();
// define models
var Post = modelBuilder.define('Post', {
title: { type: String, length: 255 },
content: { type: ModelBuilder.Text },
date: { type: Date, default: function() {
title: {type: String, length: 255},
content: {type: ModelBuilder.Text},
date: {type: Date, default: function() {
return new Date();
} },
timestamp: { type: Number, default: Date.now },
published: { type: Boolean, default: false, index: true },
}},
timestamp: {type: Number, default: Date.now},
published: {type: Boolean, default: false, index: true},
});
// simpler way to describe model
@ -25,19 +26,19 @@ var User = modelBuilder.define('User', {
age: Number,
});
var Group = modelBuilder.define('Group', { group: String });
var Group = modelBuilder.define('Group', {group: String});
// define any custom method
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

@ -2,6 +2,7 @@
// Node module: loopback-datasource-juggler
// This file is licensed under the MIT License.
// License text available at https://opensource.org/licenses/MIT
'use strict';
var DataSource = require('../../loopback-datasource-juggler').DataSource;
var ModelBuilder = require('../../loopback-datasource-juggler').ModelBuilder;
@ -9,13 +10,13 @@ var ds = new DataSource('memory');
// define models
var Post = ds.define('Post', {
title: { type: String, length: 255 },
content: { type: DataSource.Text },
date: { type: Date, default: function() {
title: {type: String, length: 255},
content: {type: DataSource.Text},
date: {type: Date, default: function() {
return new Date;
} },
timestamp: { type: Number, default: Date.now },
published: { type: Boolean, default: false, index: true },
}},
timestamp: {type: Number, default: Date.now},
published: {type: Boolean, default: false, index: true},
});
// simplier way to describe model
@ -27,28 +28,28 @@ var User = ds.define('User', {
age: Number,
});
var Group = ds.define('Group', { name: String });
var Group = ds.define('Group', {name: String});
// define any custom method
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,44 +57,44 @@ Post.belongsTo(User, { as: 'author', foreignKey: 'userId' });
User.hasAndBelongsToMany('groups');
var user2 = new User({ name: 'Smith', age: 14 });
var user2 = new User({name: 'Smith', age: 14});
user2.save(function(err) {
console.log(user2);
var post = user2.posts.build({ title: 'Hello world' });
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.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.tags.create({name: 'popular'}, function(err, data) {
Article.findOne(function(e, article) {
article.tags(function(e, tags) {
console.log(tags);
@ -112,9 +113,9 @@ Color = modelBuilder.define('Color', {
// 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) {
console.log(colors);

View File

@ -2,6 +2,7 @@
// Node module: loopback-datasource-juggler
// This file is licensed under the MIT License.
// License text available at https://opensource.org/licenses/MIT
'use strict';
var jdb = require('../index');
@ -9,31 +10,31 @@ var User, Post, Passport, City, Street, Building;
var nbSchemaRequests = 0;
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' }},
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');
@ -48,10 +49,10 @@ function setup(done) {
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() {
var createdUsers = [];
@ -62,11 +63,11 @@ 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) {
createdUsers = items;
@ -79,9 +80,9 @@ 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) {
createdPassports = items;
@ -94,11 +95,11 @@ 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) {
createdPosts = items;

View File

@ -2,6 +2,7 @@
// Node module: loopback-datasource-juggler
// This file is licensed under the MIT License.
// License text available at https://opensource.org/licenses/MIT
'use strict';
var path = require('path'),
fs = require('fs'),

View File

@ -2,6 +2,7 @@
// Node module: loopback-datasource-juggler
// This file is licensed under the MIT License.
// License text available at https://opensource.org/licenses/MIT
'use strict';
var ModelBuilder = require('../../loopback-datasource-juggler').ModelBuilder;
var modelBuilder = new ModelBuilder();
@ -38,8 +39,8 @@ var user = new User({
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

@ -2,6 +2,7 @@
// Node module: loopback-datasource-juggler
// This file is licensed under the MIT License.
// License text available at https://opensource.org/licenses/MIT
'use strict';
var DataSource = require('../index').DataSource;
var ds = new DataSource('memory');
@ -20,43 +21,43 @@ 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.customer.create({ name: 'Smith' }, function(err, customer2) {
Order.create({orderDate: new Date(), items: ['Phone']}, function(err, order) {
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) {
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);
@ -82,13 +83,13 @@ var Appointment = ds.createModel('Appointment', {
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) {
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,
@ -100,11 +101,11 @@ Physician.create({ name: 'Dr John' }, function(err, physician1) {
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,
@ -113,7 +114,7 @@ Physician.create({ name: 'Dr John' }, function(err, physician1) {
// Create a physician?
patient1.physicians.create(
{ name: 'Dr X' },
{name: 'Dr X'},
function(err, patient4) {
console.log(
'Physician 4: ',
@ -140,22 +141,22 @@ var Part = ds.createModel('Part', {
Assembly.hasAndBelongsToMany(Part);
Part.hasAndBelongsToMany(Assembly);
Assembly.create({ name: 'car' }, function(err, assembly) {
Part.create({ partNumber: 'engine' }, function(err, part) {
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

@ -2,6 +2,7 @@
// Node module: loopback-datasource-juggler
// This file is licensed under the MIT License.
// License text available at https://opensource.org/licenses/MIT
'use strict';
var SG = require('strong-globalize');
SG.SetRootDir(__dirname);

View File

@ -2,6 +2,7 @@
// Node module: loopback-datasource-juggler
// This file is licensed under the MIT License.
// License text available at https://opensource.org/licenses/MIT
'use strict';
// A lightweight alternative to "depd" that works in the browser
module.exports = function depd(namespace) {

View File

@ -2,6 +2,7 @@
// Node module: loopback-datasource-juggler
// This file is licensed under the MIT License.
// License text available at https://opensource.org/licenses/MIT
'use strict';
var g = require('strong-globalize')();
var util = require('util');
@ -107,7 +108,7 @@ 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 {
@ -241,12 +242,12 @@ Memory.prototype.updateOrCreate = function(model, data, options, callback) {
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 });
callback(err, data, {isNewInstance: false});
});
} else {
self.create(model, data, options, function(err, id) {
self.setIdValue(model, data, id);
callback(err, data, { isNewInstance: true });
callback(err, data, {isNewInstance: true});
});
}
});
@ -256,21 +257,21 @@ Memory.prototype.patchOrCreateWithWhere =
Memory.prototype.upsertWithWhere = function(model, where, data, options, callback) {
var self = this;
var primaryKey = this.idName(model);
var filter = { where: where };
var filter = {where: where};
var nodes = self._findAllSkippingIncludes(model, filter);
if (nodes.length === 0) {
return self._createSync(model, data, function(err, id) {
if (err) return process.nextTick(function() { callback(err); });
self.saveToFile(id, function(err, id) {
self.setIdValue(model, data, id);
callback(err, self.fromDb(model, data), { isNewInstance: true });
callback(err, self.fromDb(model, data), {isNewInstance: true});
});
});
}
if (nodes.length === 1) {
var primaryKeyValue = nodes[0][primaryKey];
self.updateAttributes(model, primaryKeyValue, data, options, function(err, data) {
callback(err, data, { isNewInstance: false });
callback(err, data, {isNewInstance: false});
});
} else {
process.nextTick(function() {
@ -323,7 +324,7 @@ Memory.prototype.save = function save(model, data, options, callback) {
}
this.collection(model)[id] = serialize(data);
this.saveToFile(data, function(err) {
callback(err, self.fromDb(model, data), { isNewInstance: !modelData });
callback(err, self.fromDb(model, data), {isNewInstance: !modelData});
});
};
@ -342,7 +343,7 @@ Memory.prototype.find = function find(model, id, options, callback) {
Memory.prototype.destroy = function destroy(model, id, options, callback) {
var exists = this.collection(model)[id];
delete this.collection(model)[id];
this.saveToFile({ count: exists ? 1 : 0 }, callback);
this.saveToFile({count: exists ? 1 : 0}, callback);
};
Memory.prototype.fromDb = function(model, data) {
@ -412,7 +413,7 @@ Memory.prototype._findAllSkippingIncludes = function(model, filter) {
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));
}
@ -485,12 +486,12 @@ function applyFilter(filter) {
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') {
return where[key].some(function(cond) {
return applyFilter({ where: cond })(obj);
return applyFilter({where: cond})(obj);
});
}
}
@ -507,7 +508,7 @@ function applyFilter(filter) {
return true;
}
return value.some(function(v, i) {
var filter = { where: {}};
var filter = {where: {}};
filter.where[i] = matcher;
return applyFilter(filter)(value);
});
@ -522,7 +523,7 @@ function applyFilter(filter) {
var dotIndex = key.indexOf('.');
var subValue = obj[key.substring(0, dotIndex)];
if (dotIndex !== -1) {
var subFilter = { where: {}};
var subFilter = {where: {}};
var subKey = key.substring(dotIndex + 1);
subFilter.where[subKey] = where[key];
if (Array.isArray(subValue)) {
@ -601,8 +602,8 @@ function applyFilter(filter) {
}
if ('between' in example) {
return (testInEquality({ gte: example.between[0] }, value) &&
testInEquality({ lte: example.between[1] }, value));
return (testInEquality({gte: example.between[0]}, value) &&
testInEquality({lte: example.between[1]}, value));
}
if (example.like || example.nlike || example.ilike || example.nilike) {
@ -687,7 +688,7 @@ Memory.prototype.destroyAll = function destroyAll(model, where, options, callbac
var filter = null;
var count = 0;
if (where) {
filter = applyFilter({ where: where });
filter = applyFilter({where: where});
Object.keys(cache).forEach(function(id) {
if (!filter || filter(this.fromDb(model, cache[id]))) {
count++;
@ -698,14 +699,14 @@ Memory.prototype.destroyAll = function destroyAll(model, where, options, callbac
count = Object.keys(cache).length;
this.collection(model, {});
}
this.saveToFile({ count: count }, callback);
this.saveToFile({count: count}, callback);
};
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 };
var filter = {where: where};
data = data.map(function(id) {
return this.fromDb(model, cache[id]);
}.bind(this));
@ -722,7 +723,7 @@ 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;
@ -739,7 +740,7 @@ Memory.prototype.update =
}
}, function(err) {
if (err) return cb(err);
self.saveToFile({ count: count }, cb);
self.saveToFile({count: count}, cb);
});
};
@ -803,7 +804,7 @@ 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];
@ -815,14 +816,14 @@ Memory.prototype.replaceOrCreate = function(model, data, options, callback) {
if (err) return process.nextTick(function() { cb(err); });
self.saveToFile(id, function(err, id) {
self.setIdValue(model, data, id);
callback(err, self.fromDb(model, data), { isNewInstance: true });
callback(err, self.fromDb(model, data), {isNewInstance: true});
});
});
}
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});
});
};

View File

@ -2,6 +2,7 @@
// Node module: loopback-datasource-juggler
// This file is licensed under the MIT License.
// License text available at https://opensource.org/licenses/MIT
'use strict';
var g = require('strong-globalize')();
var util = require('util');
@ -104,7 +105,7 @@ 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) {

View File

@ -3,6 +3,10 @@
// This file is licensed under the MIT License.
// License text available at https://opensource.org/licenses/MIT
// Turning on strict for this file breaks lots of test cases;
// disabling strict for this file
/* eslint-disable strict */
/*!
* Module exports class Model
*/
@ -107,7 +111,7 @@ function setIdValue(m, data, value) {
function byIdQuery(m, id) {
var pk = idName(m);
var query = { where: {}};
var query = {where: {}};
query.where[pk] = id;
return query;
}
@ -252,7 +256,7 @@ DataAccessObject.create = function(data, options, cb) {
async.map(data, function(item, done) {
self.create(item, options, function(err, result) {
// Collect all errors and results
done(null, { err: err, result: result || item });
done(null, {err: err, result: result || item});
});
}, function(err, results) {
if (err) {
@ -507,7 +511,7 @@ DataAccessObject.upsert = function(data, options, cb) {
var update = data;
var inst = data;
if (!(data instanceof Model)) {
inst = new Model(data, { applyDefaultValues: false });
inst = new Model(data, {applyDefaultValues: false});
}
update = inst.toObject(false);
@ -580,7 +584,7 @@ DataAccessObject.upsert = function(data, options, cb) {
var obj;
if (data && !(data instanceof Model)) {
inst._initProperties(data, { persisted: true });
inst._initProperties(data, {persisted: true});
obj = inst;
} else {
obj = data;
@ -610,11 +614,11 @@ DataAccessObject.upsert = function(data, options, cb) {
}
});
} else {
var opts = { notify: false };
var opts = {notify: false};
if (ctx.options && ctx.options.transaction) {
opts.transaction = ctx.options.transaction;
}
Model.findOne({ where: ctx.query.where }, opts, function(err, inst) {
Model.findOne({where: ctx.query.where}, opts, function(err, inst) {
if (err) {
return cb(err);
}
@ -679,7 +683,7 @@ DataAccessObject.upsertWithWhere = function(where, data, options, cb) {
var Model = this;
var connector = Model.getConnector();
var modelName = Model.modelName;
var query = { where: where };
var query = {where: where};
var context = {
Model: Model,
query: query,
@ -704,7 +708,7 @@ DataAccessObject.upsertWithWhere = function(where, data, options, cb) {
var update = data;
var inst = data;
if (!(data instanceof Model)) {
inst = new Model(data, { applyDefaultValues: false });
inst = new Model(data, {applyDefaultValues: false});
}
update = inst.toObject(false);
Model.applyScope(query);
@ -758,7 +762,7 @@ DataAccessObject.upsertWithWhere = function(where, data, options, cb) {
if (err) return cb(err);
var obj;
if (contxt.data && !(contxt.data instanceof Model)) {
inst._initProperties(contxt.data, { persisted: true });
inst._initProperties(contxt.data, {persisted: true});
obj = inst;
} else {
obj = contxt.data;
@ -777,11 +781,11 @@ DataAccessObject.upsertWithWhere = function(where, data, options, cb) {
}
});
} else {
var opts = { notify: false };
var opts = {notify: false};
if (ctx.options && ctx.options.transaction) {
opts.transaction = ctx.options.transaction;
}
self.find({ where: ctx.query.where }, opts, function(err, instances) {
self.find({where: ctx.query.where}, opts, function(err, instances) {
if (err) return cb(err);
var modelsLength = instances.length;
if (modelsLength === 0) {
@ -931,7 +935,7 @@ DataAccessObject.replaceOrCreate = function replaceOrCreate(data, options, cb) {
var obj;
if (data && !(data instanceof Model)) {
inst._initProperties(data, { persisted: true });
inst._initProperties(data, {persisted: true});
obj = inst;
} else {
obj = data;
@ -958,11 +962,11 @@ DataAccessObject.replaceOrCreate = function replaceOrCreate(data, options, cb) {
}
});
} else {
var opts = { notify: false };
var opts = {notify: false};
if (ctx.options && ctx.options.transaction) {
opts.transaction = ctx.options.transaction;
}
Model.findOne({ where: ctx.query.where }, opts, function(err, found) {
Model.findOne({where: ctx.query.where}, opts, function(err, found) {
if (err) return cb(err);
if (!isOriginalQuery) {
// The custom query returned from a hook may hide the fact that
@ -1007,14 +1011,14 @@ DataAccessObject.findOrCreate = function findOrCreate(query, data, options, cb)
// findOrCreate(data);
// query will be built from data, and method will return Promise
data = query;
query = { where: data };
query = {where: data};
} else if (options === undefined && cb === undefined) {
if (typeof data === 'function') {
// findOrCreate(data, cb);
// query will be built from data
cb = data;
data = query;
query = { where: data };
query = {where: data};
}
} else if (cb === undefined) {
if (typeof options === 'function') {
@ -1025,7 +1029,7 @@ DataAccessObject.findOrCreate = function findOrCreate(query, data, options, cb)
}
cb = cb || utils.createPromiseCallback();
query = query || { where: {}};
query = query || {where: {}};
data = data || {};
options = options || {};
@ -1056,8 +1060,8 @@ DataAccessObject.findOrCreate = function findOrCreate(query, data, options, cb)
var obj, Model = self.lookupModel(data);
if (data) {
obj = new Model(data, { fields: query.fields, applySetters: false,
persisted: true });
obj = new Model(data, {fields: query.fields, applySetters: false,
persisted: true});
}
if (created) {
@ -1344,9 +1348,9 @@ DataAccessObject.findByIds = function(ids, query, options, cb) {
return cb.promise;
}
var filter = { where: {}};
var filter = {where: {}};
var pk = idName(this);
filter.where[pk] = { inq: [].concat(ids) };
filter.where[pk] = {inq: [].concat(ids)};
mergeQuery(filter, query || {});
// to know if the result need to be sorted by ids or not
@ -1866,7 +1870,7 @@ DataAccessObject.find = function find(query, options, cb) {
if (!err && Array.isArray(data)) {
async.map(data, function(item, next) {
var Model = self.lookupModel(item);
var obj = new Model(item, { fields: query.fields, applySetters: false, persisted: true });
var obj = new Model(item, {fields: query.fields, applySetters: false, persisted: true});
if (query && query.include) {
if (query.collect) {
@ -2064,7 +2068,7 @@ DataAccessObject.destroyAll = function destroyAll(where, options, cb) {
var hookState = {};
var query = { where: where };
var query = {where: where};
this.applyScope(query);
where = query.where;
@ -2078,7 +2082,7 @@ DataAccessObject.destroyAll = function destroyAll(where, options, cb) {
if (options.notify === false) {
doDelete(where);
} else {
query = { where: whereIsEmpty(where) ? {} : where };
query = {where: whereIsEmpty(where) ? {} : where};
var context = {
Model: Model,
query: query,
@ -2268,7 +2272,7 @@ DataAccessObject.count = function(where, options, cb) {
var hookState = {};
var query = { where: where };
var query = {where: where};
this.applyScope(query);
where = query.where;
@ -2284,7 +2288,7 @@ DataAccessObject.count = function(where, options, cb) {
var context = {
Model: Model,
query: { where: where },
query: {where: where},
hookState: hookState,
options: options,
};
@ -2406,7 +2410,7 @@ DataAccessObject.prototype.save = function(options, cb) {
Model.notifyObserversOf('loaded', context, function(err) {
if (err) return cb(err);
inst._initProperties(data, { persisted: true });
inst._initProperties(data, {persisted: true});
var context = {
Model: Model,
@ -2517,7 +2521,7 @@ DataAccessObject.updateAll = function(where, data, options, cb) {
var hookState = {};
var query = { where: where };
var query = {where: where};
this.applyScope(query);
this.applyProperties(data);
@ -2525,7 +2529,7 @@ DataAccessObject.updateAll = function(where, data, options, cb) {
var context = {
Model: Model,
query: { where: where },
query: {where: where},
hookState: hookState,
options: options,
};
@ -2668,7 +2672,7 @@ DataAccessObject.prototype.remove =
// A hook modified the query, it is no longer
// a simple 'delete model with the given id'.
// We must switch to full query-based delete.
Model.deleteAll(where, { notify: false }, function(err, info) {
Model.deleteAll(where, {notify: false}, function(err, info) {
if (err) return cb(err, false);
var deleted = info && info.count > 0;
if (Model.settings.strictDelete && !deleted) {
@ -2834,7 +2838,7 @@ DataAccessObject.replaceById = function(id, data, options, cb) {
if (!data[pkName]) data[pkName] = id;
var Model = this;
var inst = new Model(data, { persisted: true });
var inst = new Model(data, {persisted: true});
var enforced = {};
this.applyProperties(enforced, inst);
inst.setAttributes(enforced);

View File

@ -3,6 +3,10 @@
// This file is licensed under the MIT License.
// License text available at https://opensource.org/licenses/MIT
// Turning on strict for this file breaks lots of test cases;
// disabling strict for this file
/* eslint-disable strict */
/*!
* Module dependencies
*/
@ -515,7 +519,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) {
@ -648,7 +652,7 @@ DataSource.prototype.mixin = function(ModelCtor) {
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) {
@ -1416,7 +1420,7 @@ DataSource.prototype.discoverSchemas = function(modelName, options, cb) {
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};
}
});
}
@ -1567,7 +1571,7 @@ DataSource.prototype.discoverSchemasSync = function(modelName, options) {
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};
}
});
}
@ -1825,7 +1829,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] = {};

View File

@ -2,6 +2,7 @@
// Node module: loopback-datasource-juggler
// This file is licensed under the MIT License.
// License text available at https://opensource.org/licenses/MIT
'use strict';
var assert = require('assert');
@ -57,7 +58,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

View File

@ -2,6 +2,7 @@
// Node module: loopback-datasource-juggler
// This file is licensed under the MIT License.
// License text available at https://opensource.org/licenses/MIT
'use strict';
var deprecated = require('depd')('loopback-datasource-juggler');
var g = require('strong-globalize')();

View File

@ -2,6 +2,7 @@
// Node module: loopback-datasource-juggler
// This file is licensed under the MIT License.
// License text available at https://opensource.org/licenses/MIT
'use strict';
var async = require('async');
var g = require('strong-globalize')();
@ -242,7 +243,7 @@ Inclusion.include = function(objects, include, options, cb) {
}
});
}
utils.mergeQuery(filter, includeScope, { fields: false });
utils.mergeQuery(filter, includeScope, {fields: false});
}
//Let's add a placeholder where query
filter.where = filter.where || {};
@ -639,7 +640,7 @@ 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] = {
@ -906,7 +907,7 @@ 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 {

View File

@ -2,6 +2,7 @@
// Node module: loopback-datasource-juggler
// This file is licensed under the MIT License.
// License text available at https://opensource.org/licenses/MIT
'use strict';
module.exports.buildOneToOneIdentityMapWithOrigKeys = buildOneToOneIdentityMapWithOrigKeys;
module.exports.buildOneToManyIdentityMapWithOrigKeys = buildOneToManyIdentityMapWithOrigKeys;

View File

@ -2,6 +2,7 @@
// Node module: loopback-datasource-juggler
// This file is licensed under the MIT License.
// License text available at https://opensource.org/licenses/MIT
'use strict';
module.exports = function getIntrospector(ModelBuilder) {
function introspectType(value) {

View File

@ -2,6 +2,7 @@
// Node module: loopback-datasource-juggler
// This file is licensed under the MIT License.
// License text available at https://opensource.org/licenses/MIT
'use strict';
var util = require('util');

View File

@ -23,7 +23,7 @@ module.exports = function keyValueSet(key, value, options, callback) {
callback = options;
options = {};
} else if (typeof options === 'number') {
options = { ttl: options };
options = {ttl: options};
} else if (!options) {
options = {};
}

View File

@ -2,6 +2,7 @@
// Node module: loopback-datasource-juggler
// This file is licensed under the MIT License.
// License text available at https://opensource.org/licenses/MIT
'use strict';
var g = require('strong-globalize')();
var util = require('util');

View File

@ -2,6 +2,7 @@
// Node module: loopback-datasource-juggler
// This file is licensed under the MIT License.
// License text available at https://opensource.org/licenses/MIT
'use strict';
var debug = require('debug')('loopback:mixin');
var assert = require('assert');

View File

@ -2,6 +2,7 @@
// Node module: loopback-datasource-juggler
// This file is licensed under the MIT License.
// License text available at https://opensource.org/licenses/MIT
'use strict';
/*!
* Module dependencies
@ -73,7 +74,7 @@ function isModelClass(cls) {
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;
};
@ -216,7 +217,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;
}
@ -229,7 +230,7 @@ ModelBuilder.prototype.define = function defineClass(className, properties, sett
// Support both flavors path: 'x' and path: '/x'
pathName = '/' + pathName;
}
hiddenProperty(ModelClass, 'http', { path: pathName });
hiddenProperty(ModelClass, 'http', {path: pathName});
hiddenProperty(ModelClass, 'base', ModelBaseClass);
hiddenProperty(ModelClass, '_observers', {});
hiddenProperty(ModelClass, '_warned', {});
@ -291,7 +292,7 @@ ModelBuilder.prototype.define = function defineClass(className, properties, sett
// Add the id property
if (idInjection) {
// Set up the id property
ModelClass.definition.defineProperty('id', { type: Number, id: 1, generated: true });
ModelClass.definition.defineProperty('id', {type: Number, id: 1, generated: true});
}
idNames = modelDefinition.idNames(); // Reload it after rebuild
@ -697,7 +698,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') {
@ -744,7 +745,7 @@ ModelBuilder.prototype.buildModels = function(schemas, createModel) {
{
name: this.getSchemaName(),
properties: schemas,
options: { anonymous: true },
options: {anonymous: true},
},
];
}
@ -771,7 +772,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});
}
}
}

View File

@ -2,6 +2,7 @@
// Node module: loopback-datasource-juggler
// This file is licensed under the MIT License.
// License text available at https://opensource.org/licenses/MIT
'use strict';
var assert = require('assert');
var util = require('util');
@ -143,7 +144,7 @@ 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) {
return a.id - b.id;

View File

@ -3,6 +3,10 @@
// This file is licensed under the MIT License.
// License text available at https://opensource.org/licenses/MIT
// Turning on strict for this file breaks lots of test cases;
// disabling strict for this file
/* eslint-disable strict */
/*!
* Module exports class Model
*/
@ -198,7 +202,7 @@ ModelBaseClass.prototype._initProperties = function(data, options) {
var multiple = ctor.relations[p].multiple;
var typeName = multiple ? 'Array' : modelTo.modelName;
var propType = multiple ? [modelTo] : modelTo;
properties[p] = { name: typeName, type: propType };
properties[p] = {name: typeName, type: propType};
this.setStrict(false);
}

View File

@ -2,6 +2,7 @@
// Node module: loopback-datasource-juggler
// This file is licensed under the MIT License.
// License text available at https://opensource.org/licenses/MIT
'use strict';
var async = require('async');
var utils = require('./utils');

View File

@ -3,6 +3,10 @@
// This file is licensed under the MIT License.
// License text available at https://opensource.org/licenses/MIT
// Turning on strict for this file breaks lots of test cases;
// disabling strict for this file
/* eslint-disable strict */
/*!
* Dependencies
*/
@ -556,7 +560,7 @@ function lookupModelTo(modelFrom, modelTo, params, singularize) {
* @returns {Object} The normalized parameters
*/
function polymorphicParams(params, as) {
if (typeof params === 'string') params = { as: params };
if (typeof params === 'string') params = {as: params};
if (typeof params.as !== 'string') params.as = as || 'reference'; // default
params.foreignKey = params.foreignKey || i8n.camelize(params.as + '_id', true);
params.discriminator = params.discriminator || i8n.camelize(params.as + '_type', true);
@ -608,7 +612,7 @@ RelationDefinition.hasMany = function hasMany(modelFrom, modelTo, params) {
fk = polymorphic.foreignKey;
}
if (!params.through) {
modelTo.dataSource.defineProperty(modelTo.modelName, discriminator, { type: 'string', index: true });
modelTo.dataSource.defineProperty(modelTo.modelName, discriminator, {type: 'string', index: true});
}
}
@ -1025,7 +1029,7 @@ HasManyThrough.prototype.create = function create(data, options, cb) {
var fk2 = keys[1];
function createRelation(to, next) {
var d = {}, q = {}, filter = { where: q };
var d = {}, q = {}, filter = {where: q};
d[fk1] = q[fk1] = modelInstance[definition.keyFrom];
d[fk2] = q[fk2] = to[pk2];
definition.applyProperties(modelInstance, d);
@ -1090,7 +1094,7 @@ HasManyThrough.prototype.add = function(acInst, data, options, cb) {
query[fk1] = this.modelInstance[pk1];
query[fk2] = (acInst instanceof definition.modelTo) ? acInst[pk2] : acInst;
var filter = { where: query };
var filter = {where: query};
definition.applyScope(this.modelInstance, filter);
@ -1136,7 +1140,7 @@ HasManyThrough.prototype.exists = function(acInst, options, cb) {
query[fk1] = this.modelInstance[pk1];
query[fk2] = (acInst instanceof definition.modelTo) ? acInst[pk2] : acInst;
var filter = { where: query };
var filter = {where: query};
definition.applyScope(this.modelInstance, filter);
@ -1174,7 +1178,7 @@ HasManyThrough.prototype.remove = function(acInst, options, cb) {
query[fk1] = this.modelInstance[pk1];
query[fk2] = (acInst instanceof definition.modelTo) ? acInst[pk2] : acInst;
var filter = { where: query };
var filter = {where: query};
definition.applyScope(this.modelInstance, filter);
@ -1239,12 +1243,12 @@ RelationDefinition.belongsTo = function(modelFrom, modelTo, params) {
discriminator = polymorphic.discriminator;
if (polymorphic.idType) { // explicit key type
modelFrom.dataSource.defineProperty(modelFrom.modelName, fk, { type: polymorphic.idType, index: true });
modelFrom.dataSource.defineProperty(modelFrom.modelName, fk, {type: polymorphic.idType, index: true});
} else { // try to use the same foreign key type as modelFrom
modelFrom.dataSource.defineForeignKey(modelFrom.modelName, fk, modelFrom.modelName, pkName);
}
modelFrom.dataSource.defineProperty(modelFrom.modelName, discriminator, { type: 'string', index: true });
modelFrom.dataSource.defineProperty(modelFrom.modelName, discriminator, {type: 'string', index: true});
} else {
pkName = params.primaryKey || modelTo.dataSource.idName(modelTo.modelName) || 'id';
relationName = params.as || i8n.camelize(modelTo.modelName, true);
@ -1461,7 +1465,7 @@ BelongsTo.prototype.related = function(condOrRefresh, options, cb) {
}
if (cachedValue === undefined || !(cachedValue instanceof ModelBaseClass)) {
var query = { where: {}};
var query = {where: {}};
query.where[pk] = modelInstance[fk];
if (query.where[pk] === undefined || query.where[pk] === null) {
@ -1560,7 +1564,7 @@ RelationDefinition.hasAndBelongsToMany = function hasAndBelongsToMany(modelFrom,
modelFrom.dataSource.define(name1);
}
var options = { as: params.as, through: params.through };
var options = {as: params.as, through: params.through};
options.properties = params.properties;
options.scope = params.scope;
// Forward relation options like "disableInclude"
@ -1572,7 +1576,7 @@ RelationDefinition.hasAndBelongsToMany = function hasAndBelongsToMany(modelFrom,
var accessor = params.through.prototype[polymorphic.as];
if (typeof accessor !== 'function') { // declare once
// use the name of the polymorphic rel, not modelTo
params.through.belongsTo(polymorphic.as, { polymorphic: true });
params.through.belongsTo(polymorphic.as, {polymorphic: true});
}
} else {
params.through.belongsTo(modelFrom);
@ -1613,7 +1617,7 @@ RelationDefinition.hasOne = function(modelFrom, modelTo, params) {
fk = polymorphic.foreignKey;
discriminator = polymorphic.discriminator;
if (!params.through) {
modelTo.dataSource.defineProperty(modelTo.modelName, discriminator, { type: 'string', index: true });
modelTo.dataSource.defineProperty(modelTo.modelName, discriminator, {type: 'string', index: true});
}
}
@ -1705,7 +1709,7 @@ HasOne.prototype.create = function(targetModelData, options, cb) {
cb = cb || utils.createPromiseCallback();
targetModelData[fk] = modelInstance[pk];
var query = { where: {}};
var query = {where: {}};
query.where[fk] = targetModelData[fk];
this.definition.applyScope(modelInstance, query);
@ -1882,7 +1886,7 @@ HasOne.prototype.related = function(condOrRefresh, options, cb) {
self.resetCache(newValue);
} else if (typeof cb === 'function') { // acts as async getter
if (cachedValue === undefined) {
var query = { where: {}};
var query = {where: {}};
query.where[fk] = modelInstance[pk];
definition.applyScope(modelInstance, query);
modelTo.findOne(query, options, function(err, inst) {
@ -1967,7 +1971,7 @@ RelationDefinition.embedsOne = function(modelFrom, modelTo, params) {
methods: params.methods,
});
var opts = { type: modelTo };
var opts = {type: modelTo};
if (params.default === true) {
opts.default = function() { return new modelTo(); };
@ -2394,7 +2398,7 @@ RelationDefinition.embedsMany = function embedsMany(modelFrom, modelTo, params)
this.errors.add(propertyName, 'contains duplicate `' + idName + '`', 'uniqueness');
err(false);
}
}, { code: 'uniqueness' });
}, {code: 'uniqueness'});
}
// validate all embedded items
@ -2753,7 +2757,7 @@ EmbedsMany.prototype.destroyAll = function(where, options, cb) {
var embeddedList = this.embeddedList();
if (where && Object.keys(where).length > 0) {
var filter = applyFilter({ where: where });
var filter = applyFilter({where: where});
var reject = function(v) { return !filter(v); };
embeddedList = embeddedList ? embeddedList.filter(reject) : embeddedList;
} else {
@ -2944,7 +2948,7 @@ EmbedsMany.prototype.add = function(acInst, data, options, cb) {
query[fk2] = (acInst instanceof belongsTo.modelTo) ? acInst[pk2] : acInst;
var filter = { where: query };
var filter = {where: query};
belongsTo.applyScope(modelInstance, filter);
@ -2991,7 +2995,7 @@ EmbedsMany.prototype.remove = function(acInst, options, cb) {
query[fk2] = (acInst instanceof belongsTo.modelTo) ? acInst[pk2] : acInst;
var filter = { where: query };
var filter = {where: query};
belongsTo.applyScope(modelInstance, filter);
@ -3048,7 +3052,7 @@ RelationDefinition.referencesMany = function referencesMany(modelFrom, modelTo,
this.errors.add(relationName, msg, 'uniqueness');
err(false);
}
}, { code: 'uniqueness' });
}, {code: 'uniqueness'});
var scopeMethods = {
findById: scopeMethod(definition, 'findById'),
@ -3352,7 +3356,7 @@ ReferencesMany.prototype.add = function(acInst, options, cb) {
if (acInst instanceof modelTo) {
insert(acInst, cb);
} else {
var filter = { where: {}};
var filter = {where: {}};
filter.where[pk] = acInst;
definition.applyScope(modelInstance, filter);

View File

@ -2,6 +2,7 @@
// Node module: loopback-datasource-juggler
// This file is licensed under the MIT License.
// License text available at https://opensource.org/licenses/MIT
'use strict';
/*!
* Dependencies

View File

@ -2,6 +2,7 @@
// Node module: loopback-datasource-juggler
// This file is licensed under the MIT License.
// License text available at https://opensource.org/licenses/MIT
'use strict';
/*eslint-disable camelcase*/
@ -85,7 +86,7 @@ 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) {
if (!err && saveOnCache) {
@ -371,7 +372,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);
}
@ -391,7 +392,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);
}
@ -419,7 +420,7 @@ function defineScope(cls, targetClass, name, params, methods, 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);
@ -439,7 +440,7 @@ function defineScope(cls, targetClass, name, params, methods, options) {
options = options || {};
var targetModel = definition.targetModel(this._receiver);
var scoped = (this._scope && this._scope.where) || {};
filter = mergeQuery({ where: scoped }, filter || {});
filter = mergeQuery({where: scoped}, filter || {});
return targetModel.findOne(filter, options, cb);
}
@ -457,7 +458,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

@ -2,6 +2,7 @@
// Node module: loopback-datasource-juggler
// This file is licensed under the MIT License.
// License text available at https://opensource.org/licenses/MIT
'use strict';
var g = require('strong-globalize')();
var debug = require('debug')('loopback:connector:transaction');

View File

@ -2,6 +2,7 @@
// Node module: loopback-datasource-juggler
// This file is licensed under the MIT License.
// License text available at https://opensource.org/licenses/MIT
'use strict';
var Types = {};
/**

View File

@ -2,6 +2,7 @@
// Node module: loopback-datasource-juggler
// This file is licensed under the MIT License.
// License text available at https://opensource.org/licenses/MIT
'use strict';
exports.safeRequire = safeRequire;
exports.fieldsToArray = fieldsToArray;
@ -162,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;
}
@ -483,8 +484,8 @@ function createPromiseCallback() {
if (!global.Promise) {
cb = function() {};
cb.promise = {};
Object.defineProperty(cb.promise, 'then', { get: throwPromiseNotDefined });
Object.defineProperty(cb.promise, 'catch', { get: throwPromiseNotDefined });
Object.defineProperty(cb.promise, 'then', {get: throwPromiseNotDefined});
Object.defineProperty(cb.promise, 'catch', {get: throwPromiseNotDefined});
return cb;
}

View File

@ -2,6 +2,7 @@
// Node module: loopback-datasource-juggler
// This file is licensed under the MIT License.
// License text available at https://opensource.org/licenses/MIT
'use strict';
var g = require('strong-globalize')();
var util = require('util');
@ -214,7 +215,7 @@ Validatable.validate = getConfigurator('custom');
* @property {String} message Optional error message if property is not valid. Default error message: " is invalid".
* @property {Boolean} allowNull Whether null values are allowed.
*/
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.
@ -239,7 +240,7 @@ Validatable.validateAsync = getConfigurator('custom', { async: true });
* @property {String} message Optional error message if property is not valid. Default error message: "is not unique".
* @property {Boolean} allowNull Whether null values are allowed.
*/
Validatable.validatesUniquenessOf = getConfigurator('uniqueness', { async: true });
Validatable.validatesUniquenessOf = getConfigurator('uniqueness', {async: true});
// implementation of validators
@ -352,7 +353,7 @@ function validateUniqueness(attr, conf, err, options, done) {
if (blank(this[attr])) {
return process.nextTick(done);
}
var cond = { where: {}};
var cond = {where: {}};
cond.where[attr] = this[attr];
if (conf && conf.scopedTo) {

View File

@ -33,8 +33,8 @@
"devDependencies": {
"async-iterators": "^0.2.2",
"bluebird": "^2.9.9",
"eslint": "^2.9.0",
"eslint-config-loopback": "^2.0.0",
"eslint": "^2.13.1",
"eslint-config-loopback": "^4.0.0",
"mocha": "^2.1.0",
"should": "^8.0.2"
},

View File

@ -2,6 +2,7 @@
// Node module: loopback-datasource-juggler
// This file is licensed under the MIT License.
// License text available at https://opensource.org/licenses/MIT
'use strict';
var should = require('./init.js');

View File

@ -2,6 +2,7 @@
// Node module: loopback-datasource-juggler
// This file is licensed under the MIT License.
// License text available at https://opensource.org/licenses/MIT
'use strict';
var ModelBuilder = require('../').ModelBuilder;
var should = require('./init');
@ -10,7 +11,7 @@ describe('async observer', function() {
var TestModel;
beforeEach(function defineTestModel() {
var modelBuilder = new ModelBuilder();
TestModel = modelBuilder.define('TestModel', { name: String });
TestModel = modelBuilder.define('TestModel', {name: String});
});
it('calls registered async observers', function(done) {
@ -302,7 +303,7 @@ describe('async observer', function() {
});
it('returns a promise when no callback is provided', function() {
var context = { value: 'a-test-context' };
var context = {value: 'a-test-context'};
var p = TestModel.notifyObserversOf('event', context);
(p !== undefined).should.be.true;
return p.then(function(result) {

View File

@ -2,6 +2,7 @@
// Node module: loopback-datasource-juggler
// This file is licensed under the MIT License.
// License text available at https://opensource.org/licenses/MIT
'use strict';
// This test written in mocha+should.js
var should = require('./init.js');
@ -12,13 +13,13 @@ describe('basic-querying', function() {
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);
@ -64,12 +65,12 @@ describe('basic-querying', function() {
var createdUsers;
before(function(done) {
var people = [
{ name: 'a', vip: true },
{ name: 'b' },
{ name: 'c' },
{ name: 'd', vip: true },
{ name: 'e' },
{ name: 'f' },
{name: 'a', vip: true},
{name: 'b'},
{name: 'c'},
{name: 'd', vip: true},
{name: 'e'},
{name: 'f'},
];
db.automigrate(['User'], function(err) {
User.create(people, function(err, users) {
@ -103,7 +104,7 @@ describe('basic-querying', function() {
createdUsers[1].id,
createdUsers[2].id,
createdUsers[3].id],
{ where: { vip: true }}, function(err, users) {
{where: {vip: true}}, function(err, users) {
should.exist(users);
should.not.exist(err);
var names = users.map(function(u) {
@ -141,7 +142,7 @@ describe('basic-querying', function() {
});
it('should query limited collection', function(done) {
User.find({ limit: 3 }, function(err, users) {
User.find({limit: 3}, function(err, users) {
should.exists(users);
should.not.exists(err);
users.should.have.lengthOf(3);
@ -150,7 +151,7 @@ describe('basic-querying', function() {
});
it('should query collection with skip & limit', function(done) {
User.find({ skip: 1, limit: 4, order: 'seq' }, function(err, users) {
User.find({skip: 1, limit: 4, order: 'seq'}, function(err, users) {
should.exists(users);
should.not.exists(err);
users[0].seq.should.be.eql(1);
@ -160,7 +161,7 @@ describe('basic-querying', function() {
});
it('should query collection with offset & limit', function(done) {
User.find({ offset: 2, limit: 3, order: 'seq' }, function(err, users) {
User.find({offset: 2, limit: 3, order: 'seq'}, function(err, users) {
should.exists(users);
should.not.exists(err);
users[0].seq.should.be.eql(2);
@ -170,7 +171,7 @@ describe('basic-querying', function() {
});
it('should query filtered collection', function(done) {
User.find({ where: { role: 'lead' }}, function(err, users) {
User.find({where: {role: 'lead'}}, function(err, users) {
should.exists(users);
should.not.exists(err);
users.should.have.lengthOf(2);
@ -179,7 +180,7 @@ describe('basic-querying', function() {
});
it('should query collection sorted by numeric field', function(done) {
User.find({ order: 'order' }, function(err, users) {
User.find({order: 'order'}, function(err, users) {
should.exists(users);
should.not.exists(err);
users.forEach(function(u, i) {
@ -190,7 +191,7 @@ describe('basic-querying', function() {
});
it('should query collection desc sorted by numeric field', function(done) {
User.find({ order: 'order DESC' }, function(err, users) {
User.find({order: 'order DESC'}, function(err, users) {
should.exists(users);
should.not.exists(err);
users.forEach(function(u, i) {
@ -201,7 +202,7 @@ describe('basic-querying', function() {
});
it('should query collection sorted by string field', function(done) {
User.find({ order: 'name' }, function(err, users) {
User.find({order: 'name'}, function(err, users) {
should.exists(users);
should.not.exists(err);
users.shift().name.should.equal('George Harrison');
@ -212,7 +213,7 @@ describe('basic-querying', function() {
});
it('should query collection desc sorted by string field', function(done) {
User.find({ order: 'name DESC' }, function(err, users) {
User.find({order: 'name DESC'}, function(err, users) {
should.exists(users);
should.not.exists(err);
users.pop().name.should.equal('George Harrison');
@ -224,7 +225,7 @@ describe('basic-querying', function() {
it('should query sorted desc by order integer field even though there' +
'is an async model loaded hook', function(done) {
User.find({ order: 'order DESC' }, function(err, users) {
User.find({order: 'order DESC'}, function(err, users) {
if (err) return done(err);
should.exists(users);
@ -235,10 +236,10 @@ 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) {
User.find({where: {and: [
{name: 'John Lennon'},
{role: 'lead'},
]}}, function(err, users) {
should.not.exist(err);
users.should.have.property('length', 1);
done();
@ -246,10 +247,10 @@ describe('basic-querying', function() {
});
it('should support "and" operator that is not satisfied', function(done) {
User.find({ where: { and: [
{ name: 'John Lennon' },
{ role: 'member' },
] }}, function(err, users) {
User.find({where: {and: [
{name: 'John Lennon'},
{role: 'member'},
]}}, function(err, users) {
should.not.exist(err);
users.should.have.property('length', 0);
done();
@ -257,10 +258,10 @@ describe('basic-querying', function() {
});
it('should support "or" that is satisfied', function(done) {
User.find({ where: { or: [
{ name: 'John Lennon' },
{ role: 'lead' },
] }}, function(err, users) {
User.find({where: {or: [
{name: 'John Lennon'},
{role: 'lead'},
]}}, function(err, users) {
should.not.exist(err);
users.should.have.property('length', 2);
done();
@ -268,10 +269,10 @@ describe('basic-querying', function() {
});
it('should support "or" operator that is not satisfied', function(done) {
User.find({ where: { or: [
{ name: 'XYZ' },
{ role: 'Hello1' },
] }}, function(err, users) {
User.find({where: {or: [
{name: 'XYZ'},
{role: 'Hello1'},
]}}, function(err, users) {
should.not.exist(err);
users.should.have.property('length', 0);
done();
@ -279,7 +280,7 @@ describe('basic-querying', function() {
});
it('should support date "gte" that is satisfied', function(done) {
User.find({ order: 'seq', where: { birthday: { 'gte': new Date('1980-12-08') },
User.find({order: 'seq', where: {birthday: {'gte': new Date('1980-12-08')},
}}, function(err, users) {
should.not.exist(err);
users.should.have.property('length', 1);
@ -289,7 +290,7 @@ 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') },
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);
@ -298,7 +299,7 @@ describe('basic-querying', function() {
});
it('should support date "gt" that is satisfied', function(done) {
User.find({ order: 'seq', where: { birthday: { 'gt': new Date('1980-12-07') },
User.find({order: 'seq', where: {birthday: {'gt': new Date('1980-12-07')},
}}, function(err, users) {
should.not.exist(err);
users.should.have.property('length', 1);
@ -308,7 +309,7 @@ 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') },
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);
@ -318,7 +319,7 @@ describe('basic-querying', function() {
});
it('should support number "gte" that is satisfied', function(done) {
User.find({ order: 'seq', where: { order: { 'gte': 3 },
User.find({order: 'seq', where: {order: {'gte': 3},
}}, function(err, users) {
should.not.exist(err);
users.should.have.property('length', 4);
@ -328,7 +329,7 @@ describe('basic-querying', function() {
});
it('should support number "gt" that is not satisfied', function(done) {
User.find({ order: 'seq', where: { order: { 'gt': 6 },
User.find({order: 'seq', where: {order: {'gt': 6},
}}, function(err, users) {
should.not.exist(err);
users.should.have.property('length', 0);
@ -337,7 +338,7 @@ describe('basic-querying', function() {
});
it('should support number "gt" that is satisfied', function(done) {
User.find({ order: 'seq', where: { order: { 'gt': 5 },
User.find({order: 'seq', where: {order: {'gt': 5},
}}, function(err, users) {
should.not.exist(err);
users.should.have.property('length', 1);
@ -347,7 +348,7 @@ describe('basic-querying', function() {
});
it('should support number "lt" that is satisfied', function(done) {
User.find({ order: 'seq', where: { order: { 'lt': 2 },
User.find({order: 'seq', where: {order: {'lt': 2},
}}, function(err, users) {
should.not.exist(err);
users.should.have.property('length', 1);
@ -357,7 +358,7 @@ 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 },
User.find({order: 'seq', where: {order: {'gt': null},
}}, function(err, users) {
should.not.exist(err);
users.should.have.property('length', 0);
@ -366,7 +367,7 @@ describe('basic-querying', function() {
});
it('should support number "lt" that is not satisfied by null value', function(done) {
User.find({ order: 'seq', where: { order: { 'lt': null },
User.find({order: 'seq', where: {order: {'lt': null},
}}, function(err, users) {
should.not.exist(err);
users.should.have.property('length', 0);
@ -375,7 +376,7 @@ describe('basic-querying', function() {
});
it('should support string "gte" that is satisfied by null value', function(done) {
User.find({ order: 'seq', where: { name: { 'gte': null },
User.find({order: 'seq', where: {name: {'gte': null},
}}, function(err, users) {
should.not.exist(err);
users.should.have.property('length', 0);
@ -384,7 +385,7 @@ describe('basic-querying', function() {
});
it('should support string "gte" that is satisfied', function(done) {
User.find({ order: 'seq', where: { name: { 'gte': 'Paul McCartney' },
User.find({order: 'seq', where: {name: {'gte': 'Paul McCartney'},
}}, function(err, users) {
should.not.exist(err);
users.should.have.property('length', 4);
@ -394,7 +395,7 @@ describe('basic-querying', function() {
});
it('should support string "gt" that is not satisfied', function(done) {
User.find({ order: 'seq', where: { name: { 'gt': 'xyz' },
User.find({order: 'seq', where: {name: {'gt': 'xyz'},
}}, function(err, users) {
should.not.exist(err);
users.should.have.property('length', 0);
@ -403,7 +404,7 @@ describe('basic-querying', function() {
});
it('should support string "gt" that is satisfied', function(done) {
User.find({ order: 'seq', where: { name: { 'gt': 'Paul McCartney' },
User.find({order: 'seq', where: {name: {'gt': 'Paul McCartney'},
}}, function(err, users) {
should.not.exist(err);
users.should.have.property('length', 3);
@ -413,7 +414,7 @@ describe('basic-querying', function() {
});
it('should support string "lt" that is satisfied', function(done) {
User.find({ order: 'seq', where: { name: { 'lt': 'Paul McCartney' },
User.find({order: 'seq', where: {name: {'lt': 'Paul McCartney'},
}}, function(err, users) {
should.not.exist(err);
users.should.have.property('length', 2);
@ -423,7 +424,7 @@ describe('basic-querying', function() {
});
it('should support boolean "gte" that is satisfied', function(done) {
User.find({ order: 'seq', where: { vip: { 'gte': true },
User.find({order: 'seq', where: {vip: {'gte': true},
}}, function(err, users) {
should.not.exist(err);
users.should.have.property('length', 3);
@ -433,7 +434,7 @@ describe('basic-querying', function() {
});
it('should support boolean "gt" that is not satisfied', function(done) {
User.find({ order: 'seq', where: { vip: { 'gt': true },
User.find({order: 'seq', where: {vip: {'gt': true},
}}, function(err, users) {
should.not.exist(err);
users.should.have.property('length', 0);
@ -442,7 +443,7 @@ describe('basic-querying', function() {
});
it('should support boolean "gt" that is satisfied', function(done) {
User.find({ order: 'seq', where: { vip: { 'gt': false },
User.find({order: 'seq', where: {vip: {'gt': false},
}}, function(err, users) {
should.not.exist(err);
users.should.have.property('length', 3);
@ -452,7 +453,7 @@ describe('basic-querying', function() {
});
it('should support boolean "lt" that is satisfied', function(done) {
User.find({ order: 'seq', where: { vip: { 'lt': true },
User.find({order: 'seq', where: {vip: {'lt': true},
}}, function(err, users) {
should.not.exist(err);
users.should.have.property('length', 2);
@ -464,7 +465,7 @@ describe('basic-querying', function() {
var itWhenIlikeSupported = connectorCapabilities.ilike ? it : it.skip.bind(it);
itWhenIlikeSupported('should support "like" that is satisfied', function(done) {
User.find({ where: { name: { like: 'John' }}}, function(err, users) {
User.find({where: {name: {like: 'John'}}}, function(err, users) {
if (err) return done(err);
users.length.should.equal(1);
users[0].name.should.equal('John Lennon');
@ -473,7 +474,7 @@ describe('basic-querying', function() {
});
itWhenIlikeSupported('should support "like" that is not satisfied', function(done) {
User.find({ where: { name: { like: 'Bob' }}}, function(err, users) {
User.find({where: {name: {like: 'Bob'}}}, function(err, users) {
if (err) return done(err);
users.length.should.equal(0);
done();
@ -483,7 +484,7 @@ describe('basic-querying', function() {
var itWhenNilikeSupported = connectorCapabilities.nilike ? it : it.skip.bind(it);
itWhenNilikeSupported('should support "nlike" that is satisfied', function(done) {
User.find({ where: { name: { nlike: 'John' }}}, function(err, users) {
User.find({where: {name: {nlike: 'John'}}}, function(err, users) {
if (err) return done(err);
users.length.should.equal(5);
users[0].name.should.equal('Paul McCartney');
@ -492,7 +493,7 @@ describe('basic-querying', function() {
});
itWhenIlikeSupported('should support "ilike" that is satisfied', function(done) {
User.find({ where: { name: { ilike: 'john' }}}, function(err, users) {
User.find({where: {name: {ilike: 'john'}}}, function(err, users) {
if (err) return done(err);
users.length.should.equal(1);
users[0].name.should.equal('John Lennon');
@ -501,7 +502,7 @@ describe('basic-querying', function() {
});
itWhenIlikeSupported('should support "ilike" that is not satisfied', function(done) {
User.find({ where: { name: { ilike: 'bob' }}}, function(err, users) {
User.find({where: {name: {ilike: 'bob'}}}, function(err, users) {
if (err) return done(err);
users.length.should.equal(0);
done();
@ -509,7 +510,7 @@ describe('basic-querying', function() {
});
itWhenNilikeSupported('should support "nilike" that is satisfied', function(done) {
User.find({ where: { name: { nilike: 'john' }}}, function(err, users) {
User.find({where: {name: {nilike: 'john'}}}, function(err, users) {
if (err) return done(err);
users.length.should.equal(5);
users[0].name.should.equal('Paul McCartney');
@ -524,7 +525,7 @@ describe('basic-querying', function() {
return {
expect: function(arr) {
remaining++;
User.find({ fields: fields }, function(err, users) {
User.find({fields: fields}, function(err, users) {
remaining--;
if (err) return done(err);
@ -553,10 +554,10 @@ 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']);
@ -576,7 +577,7 @@ describe('basic-querying', function() {
});
it('should query filtered count', function(done) {
User.count({ role: 'lead' }, function(err, n) {
User.count({role: 'lead'}, function(err, n) {
should.not.exist(err);
should.exist(n);
n.should.equal(2);
@ -589,7 +590,7 @@ describe('basic-querying', function() {
before(seed);
it('should find first record (default sort by id)', function(done) {
User.all({ order: 'id' }, function(err, users) {
User.all({order: 'id'}, function(err, users) {
User.findOne(function(e, u) {
should.not.exist(e);
should.exist(u);
@ -600,7 +601,7 @@ describe('basic-querying', function() {
});
it('should find first record', function(done) {
User.findOne({ order: 'order' }, function(e, u) {
User.findOne({order: 'order'}, function(e, u) {
should.not.exist(e);
should.exist(u);
u.order.should.equal(1);
@ -610,7 +611,7 @@ describe('basic-querying', function() {
});
it('should find last record', function(done) {
User.findOne({ order: 'order DESC' }, function(e, u) {
User.findOne({order: 'order DESC'}, function(e, u) {
should.not.exist(e);
should.exist(u);
u.order.should.equal(6);
@ -621,7 +622,7 @@ describe('basic-querying', function() {
it('should find last record in filtered set', function(done) {
User.findOne({
where: { role: 'lead' },
where: {role: 'lead'},
order: 'order DESC',
}, function(e, u) {
should.not.exist(e);
@ -634,7 +635,7 @@ 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) {
User.findOne({where: {id: u.id}}, function(err, user) {
should.not.exist(err);
should.exist(user);
done();
@ -677,7 +678,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);
});
@ -694,7 +695,7 @@ describe.skip('queries', function() {
var db = getSchema();
Todo = db.define('Todo', {
id: false,
content: { type: 'string' },
content: {type: 'string'},
}, {
idInjection: false,
});
@ -703,16 +704,16 @@ describe.skip('queries', function() {
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();
});
@ -721,7 +722,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();
});
@ -729,14 +730,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();
});
@ -769,14 +770,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();
});
@ -846,7 +847,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();
@ -876,10 +877,10 @@ function seed(done) {
order: 1,
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([

View File

@ -2,6 +2,7 @@
// Node module: loopback-datasource-juggler
// This file is licensed under the MIT License.
// License text available at https://opensource.org/licenses/MIT
'use strict';
require('./datatype.test.js');
require('./basic-querying.test.js');

View File

@ -2,6 +2,7 @@
// Node module: loopback-datasource-juggler
// This file is licensed under the MIT License.
// License text available at https://opensource.org/licenses/MIT
'use strict';
var Schema = require('../index').Schema;
var Text = Schema.Text;
@ -95,45 +96,45 @@ function testOrm(dataSource) {
it('should define class', function(test) {
User = dataSource.define('User', {
name: { type: String, index: true },
email: { type: String, index: true },
name: {type: String, index: true},
email: {type: String, index: true},
bio: Text,
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 },
ownerId: {type: Number, allowNull: true},
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 },
settings: {type: Schema.JSON},
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() {
title: {type: String, length: 255, index: true},
subject: {type: String},
content: {type: Text},
date: {type: Date, default: function() {
return new Date;
}, index: true },
published: { type: Boolean, default: false, index: true },
}, index: true},
published: {type: Boolean, default: false, index: true},
likes: [],
related: [RelatedPost],
}, { table: 'posts' });
}, {table: 'posts'});
function RelatedPost() {
}
@ -146,7 +147,7 @@ function testOrm(dataSource) {
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});
@ -161,7 +162,7 @@ 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
@ -171,8 +172,8 @@ function testOrm(dataSource) {
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;
@ -198,8 +199,8 @@ function testOrm(dataSource) {
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');
@ -231,7 +232,7 @@ function testOrm(dataSource) {
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) {
test.ok(!p.propertyChanged('title'));
@ -268,7 +269,7 @@ function testOrm(dataSource) {
});
it('should save only dataSource-defined field in database', function(test) {
Post.create({ title: '1602', nonSchemaField: 'some value' }, function(err, post) {
Post.create({title: '1602', nonSchemaField: 'some value'}, function(err, post) {
test.ok(!post.nonSchemaField);
post.a = 1;
post.save(function() {
@ -299,7 +300,7 @@ function testOrm(dataSource) {
it('should not re-instantiate object on saving', function(test) {
var title = 'Initial title';
var post = new Post({ title: title });
var post = new Post({title: title});
post.save(function(err, savedPost) {
test.strictEqual(post, savedPost);
test.done();
@ -359,7 +360,7 @@ function testOrm(dataSource) {
// });
it('should update single attribute', function(test) {
Post.create({ title: 'title', content: 'content', published: true }, function(err, post) {
Post.create({title: 'title', content: 'content', published: true}, function(err, post) {
post.content = 'New content';
post.updateAttribute('title', 'New title', function() {
test.equal(post.title, 'New title');
@ -392,8 +393,8 @@ function testOrm(dataSource) {
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();
});
@ -440,9 +441,9 @@ function testOrm(dataSource) {
});
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) {
test.ok(!err, 'Should not have an error.'); // Before cba174b this would be 'Error: Permission denied'
@ -466,7 +467,7 @@ function testOrm(dataSource) {
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) {
u.posts({where: {id: p.id}}, function(e, posts) {
test.equal(posts.length, 1, 'There should be only 1 post.');
test.done();
});
@ -550,7 +551,7 @@ function testOrm(dataSource) {
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();
@ -588,12 +589,12 @@ function testOrm(dataSource) {
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] : [
@ -605,7 +606,7 @@ function testOrm(dataSource) {
new Date(1000 * 9),
];
titles.forEach(function(t, i) {
Post.create({ title: t.title, subject: t.subject, date: dates[i] }, done);
Post.create({title: t.title, subject: t.subject, date: dates[i]}, done);
});
var i = 0, tests = 0;
@ -634,7 +635,7 @@ 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) {
@ -646,7 +647,7 @@ 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) {
@ -659,7 +660,7 @@ 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');
@ -674,7 +675,7 @@ 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) {
@ -688,7 +689,7 @@ 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');
@ -702,7 +703,7 @@ function testOrm(dataSource) {
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');
@ -881,7 +882,7 @@ function testOrm(dataSource) {
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;
@ -896,7 +897,7 @@ 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) {
test.equal(_emails[i], user.email, 'ASC sorting');
@ -906,7 +907,7 @@ 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) {
test.equal(_emails[i], user.email, 'DESC sorting');
@ -924,7 +925,7 @@ function testOrm(dataSource) {
Post.create(function(err, post) {
var id = post.id;
test.ok(post.published === false);
post.updateAttributes({ title: 'hey', published: true }, function() {
post.updateAttributes({title: 'hey', published: true}, function() {
Post.find(id, function(err, post) {
test.ok(!!post.published, 'Update boolean field');
test.ok(post.id);
@ -935,7 +936,7 @@ function testOrm(dataSource) {
});
it('should handle belongsTo correctly', function(test) {
var passport = new Passport({ ownerId: 16 });
var passport = new Passport({ownerId: 16});
// sync getter
test.equal(passport.owner(), 16);
// sync setter
@ -948,14 +949,14 @@ function testOrm(dataSource) {
test.expect(4);
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();
});
@ -1038,7 +1039,7 @@ 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) {
@ -1055,18 +1056,18 @@ function testOrm(dataSource) {
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) {
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) {
test.equal(user.passwd, 'heymansalt');
@ -1081,14 +1082,14 @@ function testOrm(dataSource) {
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) {
test.equal(p.likes.nextid, 2);
p.likes.push({ second: 2 });
p.likes.push({ third: 3 });
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);
@ -1117,11 +1118,11 @@ function testOrm(dataSource) {
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

@ -2,6 +2,7 @@
// Node module: loopback-datasource-juggler
// This file is licensed under the MIT License.
// License text available at https://opensource.org/licenses/MIT
'use strict';
// This test written in mocha+should.js
var should = require('./init.js');
@ -12,16 +13,16 @@ describe('crud-with-options', function() {
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);
});
@ -92,7 +93,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) {
@ -108,7 +109,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) {
@ -124,7 +125,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) {
@ -140,7 +141,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);
@ -188,12 +189,12 @@ describe('crud-with-options', function() {
describe('findByIds', function() {
before(function(done) {
var people = [
{ id: 1, name: 'a', vip: true },
{ id: 2, name: 'b' },
{ id: 3, name: 'c' },
{ id: 4, name: 'd', vip: true },
{ id: 5, name: 'e' },
{ id: 6, name: 'f' },
{id: 1, name: 'a', vip: true},
{id: 2, name: 'b'},
{id: 3, name: 'c'},
{id: 4, name: 'd', vip: true},
{id: 5, name: 'e'},
{id: 6, name: 'f'},
];
// Use automigrate so that serial keys are 1-6
db.automigrate(['User'], function(err) {
@ -216,7 +217,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) {
@ -241,7 +242,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);
@ -259,15 +260,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);
@ -285,7 +286,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');
@ -293,7 +294,7 @@ 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');
});
});
@ -311,7 +312,7 @@ describe('crud-with-options', function() {
});
it('should allow count(where, cb)', function(done) {
User.count({ role: 'lead' }, function(err, n) {
User.count({role: 'lead'}, function(err, n) {
should.not.exist(err);
should.exist(n);
n.should.equal(2);
@ -320,7 +321,7 @@ describe('crud-with-options', function() {
});
it('should allow count(where, options, cb)', function(done) {
User.count({ role: 'lead' }, options, function(err, n) {
User.count({role: 'lead'}, options, function(err, n) {
should.not.exist(err);
should.exist(n);
n.should.equal(2);
@ -333,7 +334,7 @@ describe('crud-with-options', function() {
before(seed);
it('should allow findOne(cb)', function(done) {
User.find({ order: 'id' }, function(err, users) {
User.find({order: 'id'}, function(err, users) {
User.findOne(function(e, u) {
should.not.exist(e);
should.exist(u);
@ -344,7 +345,7 @@ describe('crud-with-options', function() {
});
it('should allow findOne(filter, options, cb)', function(done) {
User.findOne({ order: 'order' }, options, function(e, u) {
User.findOne({order: 'order'}, options, function(e, u) {
should.not.exist(e);
should.exist(u);
u.order.should.equal(1);
@ -354,7 +355,7 @@ describe('crud-with-options', function() {
});
it('should allow findOne(filter, cb)', function(done) {
User.findOne({ order: 'order' }, function(e, u) {
User.findOne({order: 'order'}, function(e, u) {
should.not.exist(e);
should.exist(u);
u.order.should.equal(1);
@ -364,7 +365,7 @@ describe('crud-with-options', function() {
});
it('should allow trailing undefined args', function(done) {
User.findOne({ order: 'order' }, function(e, u) {
User.findOne({order: 'order'}, function(e, u) {
should.not.exist(e);
should.exist(u);
u.order.should.equal(1);
@ -401,7 +402,7 @@ describe('crud-with-options', function() {
describe('save', function() {
it('should allow save(options, cb)', function(done) {
var options = { foo: 'bar' };
var options = {foo: 'bar'};
var opts;
User.observe('after save', function(ctx, next) {
@ -422,12 +423,12 @@ describe('crud-with-options', function() {
beforeEach(seed);
it('should allow destroyAll(where, options, cb)', function(done) {
User.destroyAll({ name: 'John Lennon' }, options, function(err) {
User.destroyAll({name: 'John Lennon'}, options, function(err) {
should.not.exist(err);
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();
@ -437,12 +438,12 @@ describe('crud-with-options', function() {
});
it('should allow destroyAll(where, cb)', function(done) {
User.destroyAll({ name: 'John Lennon' }, function(err) {
User.destroyAll({name: 'John Lennon'}, function(err) {
should.not.exist(err);
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();
@ -454,10 +455,10 @@ describe('crud-with-options', function() {
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();
@ -471,12 +472,12 @@ describe('crud-with-options', function() {
beforeEach(seed);
it('should allow updateAll(where, data, cb)', function(done) {
User.update({ name: 'John Lennon' }, { name: 'John Smith' }, function(err) {
User.update({name: 'John Lennon'}, {name: 'John Smith'}, function(err) {
should.not.exist(err);
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();
@ -486,13 +487,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();
@ -502,11 +503,11 @@ 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) {
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();
@ -542,12 +543,12 @@ describe('upsertWithWhere', function() {
});
it('allows upsertWithWhere by accepting where,data and cb as arguments', function(done) {
User.upsertWithWhere({ name: 'John Lennon' }, { name: 'John Smith' }, function(err) {
User.upsertWithWhere({name: 'John Lennon'}, {name: 'John Smith'}, function(err) {
if (err) return done(err);
User.find({ where: { name: 'John Lennon' }}, function(err, data) {
User.find({where: {name: 'John Lennon'}}, function(err, data) {
if (err) return done(err);
data.length.should.equal(0);
User.find({ where: { name: 'John Smith' }}, function(err, data) {
User.find({where: {name: 'John Smith'}}, function(err, data) {
if (err) return done(err);
data.length.should.equal(1);
data[0].name.should.equal('John Smith');
@ -563,9 +564,9 @@ describe('upsertWithWhere', function() {
it('allows upsertWithWhere by accepting where, data, options, and cb as arguments', function(done) {
options = {};
User.upsertWithWhere({ name: 'John Lennon' }, { name: 'John Smith' }, options, function(err) {
User.upsertWithWhere({name: 'John Lennon'}, {name: 'John Smith'}, options, function(err) {
if (err) return done(err);
User.find({ where: { name: 'John Smith' }}, function(err, data) {
User.find({where: {name: 'John Smith'}}, function(err, data) {
if (err) return done(err);
data.length.should.equal(1);
data[0].name.should.equal('John Smith');
@ -600,10 +601,10 @@ function seed(done) {
order: 1,
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([

View File

@ -2,6 +2,7 @@
// Node module: loopback-datasource-juggler
// This file is licensed under the MIT License.
// License text available at https://opensource.org/licenses/MIT
'use strict';
var should = require('./init.js');
var DataSource = require('../lib/datasource.js').DataSource;

View File

@ -2,6 +2,7 @@
// Node module: loopback-datasource-juggler
// This file is licensed under the MIT License.
// License text available at https://opensource.org/licenses/MIT
'use strict';
// This test written in mocha+should.js
var should = require('./init.js');
@ -11,14 +12,14 @@ var db, Model;
describe('datatypes', function() {
before(function(done) {
db = getSchema();
Nested = db.define('Nested', {});
var Nested = db.define('Nested', {});
Model = db.define('Model', {
str: String,
date: Date,
num: Number,
bool: Boolean,
list: { type: [String] },
list: {type: [String]},
arr: Array,
nested: Nested,
});
@ -28,12 +29,12 @@ describe('datatypes', function() {
it('should return 400 when property of type array is set to string value',
function(done) {
var myModel = db.define('myModel', {
list: { type: ['object'] },
list: {type: ['object']},
});
(function() {
myModel.create({ list: 'This string will crash the server' });
}).should.throw({ statusCode: 400 });
myModel.create({list: 'This string will crash the server'});
}).should.throw({statusCode: 400});
done();
});
@ -41,12 +42,12 @@ describe('datatypes', function() {
it('should return 400 when property of type array is set to object value',
function(done) {
var myModel = db.define('myModel', {
list: { type: ['object'] },
list: {type: ['object']},
});
(function() {
myModel.create({ list: { key: 'This string will crash the server' }});
}).should.throw({ statusCode: 400 });
myModel.create({list: {key: 'This string will crash the server'}});
}).should.throw({statusCode: 400});
done();
});
@ -54,12 +55,12 @@ describe('datatypes', function() {
it('throws an error when property of type Date is set to an invalid value',
function() {
var myModel = db.define('myModel', {
date: { type: Date },
date: {type: Date},
});
(function() {
myModel.create({ date: 'invalid' });
}).should.throw({ message: 'Invalid date: invalid' });
myModel.create({date: 'invalid'});
}).should.throw({message: 'Invalid date: invalid'});
});
it('should keep types when get read data from db', function(done) {
@ -114,7 +115,7 @@ describe('datatypes', function() {
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);
@ -162,7 +163,7 @@ describe('datatypes', function() {
});
it('should not coerce nested objects into ModelConstructor types', function() {
var coerced = Model._coerce({ nested: { foo: 'bar' }});
var coerced = Model._coerce({nested: {foo: 'bar'}});
coerced.nested.constructor.name.should.equal('Object');
});
@ -170,10 +171,10 @@ describe('datatypes', function() {
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) {
Model.create({num: [1, 2, 3]}, function(err, inst) {
should.exist(err);
err.should.have.property('name').equal('ValidationError');
done();
@ -187,8 +188,8 @@ describe('datatypes', function() {
TestModel = db.define(
'TestModel',
{
desc: { type: String, required: false },
stars: { type: Number, required: false },
desc: {type: String, required: false},
stars: {type: Number, required: false},
},
{
persistUndefinedAsNull: true,
@ -200,8 +201,8 @@ describe('datatypes', function() {
});
it('should set missing optional properties to null', function(done) {
var EXPECTED = { desc: null, stars: null };
TestModel.create({ name: 'a-test-name' }, function(err, created) {
var EXPECTED = {desc: null, stars: null};
TestModel.create({name: 'a-test-name'}, function(err, created) {
if (err) return done(err);
created.should.have.properties(EXPECTED);
@ -214,13 +215,13 @@ describe('datatypes', function() {
});
it('should convert property value undefined to null', function(done) {
var EXPECTED = { desc: null, extra: null };
var EXPECTED = {desc: null, extra: null};
if (isStrict) {
// SQL-based connectors don't support dynamic properties
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);
@ -249,7 +250,7 @@ describe('datatypes', function() {
});
it('should convert undefined to null on save', function(done) {
var EXPECTED = { desc: null, stars: null, extra: null, dx: null };
var EXPECTED = {desc: null, stars: null, extra: null, dx: null};
if (isStrict) {
// SQL-based connectors don't support dynamic properties
delete EXPECTED.extra;
@ -279,14 +280,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
);
}

View File

@ -2,6 +2,7 @@
// Node module: loopback-datasource-juggler
// This file is licensed under the MIT License.
// License text available at https://opensource.org/licenses/MIT
'use strict';
// This test written in mocha+should.js
var should = require('./init.js');
@ -18,31 +19,31 @@ 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();
});
@ -62,10 +63,10 @@ describe('default scope', function() {
name: String,
kind: String,
description: String,
active: { type: Boolean, default: true },
active: {type: Boolean, default: true},
}, {
scope: { order: 'name' },
scopes: { active: { where: { active: true }}},
scope: {order: 'name'},
scopes: {active: {where: {active: true}}},
});
Product.lookupModel = function(data) {
@ -76,46 +77,46 @@ describe('default scope', function() {
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' },
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' },
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' },
Person = db.define('Person', {name: String}, {
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 };
return {kind: this.modelName};
};
Thing = db.define('Thing', Product.definition.properties, {
base: 'Product',
attributes: propertiesFn,
scope: scopeFn,
mongodb: { collection: 'Product' },
memory: { collection: 'Product' },
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);
@ -138,10 +139,10 @@ describe('default scope', function() {
});
it('should return a scoped instance', function() {
var p = new Tool({ name: 'Product A', kind: 'ignored' });
var p = new Tool({name: 'Product A', kind: 'ignored'});
p.name.should.equal('Product A');
p.kind.should.equal('Tool');
p.setAttributes({ kind: 'ignored' });
p.setAttributes({kind: 'ignored'});
p.kind.should.equal('Tool');
p.setAttribute('kind', 'other'); // currently not enforced
@ -149,7 +150,7 @@ describe('default scope', function() {
});
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,7 +160,7 @@ describe('default scope', function() {
});
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');
@ -170,7 +171,7 @@ describe('default scope', function() {
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');
@ -198,7 +199,7 @@ 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');
@ -270,7 +271,7 @@ describe('default scope', function() {
});
it('should apply default scope - order override', function(done) {
Product.find({ order: 'name DESC' }, function(err, products) {
Product.find({order: 'name DESC'}, function(err, products) {
should.not.exist(err);
products.should.have.length(5);
products[0].name.should.equal('Widget Z');
@ -293,7 +294,7 @@ describe('default scope', function() {
});
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');
@ -303,7 +304,7 @@ describe('default scope', function() {
});
it('should apply default scope - order (widget)', function(done) {
Widget.find({ order: 'name DESC' }, function(err, products) {
Widget.find({order: 'name DESC'}, function(err, products) {
should.not.exist(err);
products.should.have.length(3);
products[0].name.should.equal('Widget Z');
@ -394,7 +395,7 @@ describe('default scope', function() {
});
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();
@ -402,7 +403,7 @@ describe('default scope', function() {
});
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();
@ -476,9 +477,9 @@ describe('default scope', function() {
});
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');
@ -490,7 +491,7 @@ 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);
@ -501,7 +502,7 @@ 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');
@ -521,7 +522,7 @@ describe('default scope', function() {
});
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);
@ -535,7 +536,7 @@ 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);
@ -561,7 +562,7 @@ 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);
@ -629,7 +630,7 @@ describe('default scope', function() {
});
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();
@ -637,7 +638,7 @@ describe('default scope', function() {
});
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();
@ -645,7 +646,7 @@ describe('default scope', function() {
});
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();
@ -653,7 +654,7 @@ describe('default scope', function() {
});
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();
@ -661,7 +662,7 @@ describe('default scope', function() {
});
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');
@ -681,20 +682,20 @@ describe('default scope', function() {
});
before(function(done) {
Category.create({ name: 'Category A' }, function(err, cat) {
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);
});
@ -776,7 +777,7 @@ 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);
});
});
@ -800,8 +801,8 @@ describe('default scope', function() {
});
before(function(done) {
Person.create({ id: 1, name: 'Person A' }, function(err, person) {
person.things.create({ name: 'Thing A' }, done);
Person.create({id: 1, name: 'Person A'}, function(err, person) {
person.things.create({name: 'Thing A'}, done);
});
});

View File

@ -2,6 +2,7 @@
// Node module: loopback-datasource-juggler
// This file is licensed under the MIT License.
// License text available at https://opensource.org/licenses/MIT
'use strict';
// This test written in mocha+should.js
var should = require('./init.js');
@ -14,8 +15,8 @@ describe('defaults', 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'},
});
});
@ -43,10 +44,10 @@ describe('defaults', function() {
});
it('should ignore defaults with limited fields', function(done) {
Server.create({ host: 'localhost', port: 8080 }, function(err, s) {
Server.create({host: 'localhost', port: 8080}, function(err, s) {
should.not.exist(err);
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);
@ -56,7 +57,7 @@ describe('defaults', function() {
});
it('should apply defaults in upsert create', function(done) {
Server.upsert({ port: 8181 }, function(err, server) {
Server.upsert({port: 8181}, function(err, server) {
should.not.exist(err);
should.exist(server.createdAt);
done();
@ -65,7 +66,7 @@ describe('defaults', function() {
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

@ -2,6 +2,7 @@
// Node module: loopback-datasource-juggler
// This file is licensed under the MIT License.
// License text available at https://opensource.org/licenses/MIT
'use strict';
var jdb = require('../');
var DataSource = jdb.DataSource;
@ -11,11 +12,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() {
@ -102,7 +103,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,8 +118,8 @@ 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) {
@ -126,7 +127,7 @@ describe('Memory connector with mocked discovery', 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,8 +138,8 @@ 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) {
@ -184,7 +185,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: {
@ -285,11 +286,11 @@ describe('Memory connector with mocked discovery', function() {
describe('discoverModelDefinitions', 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.connector.discoverModelDefinitions = function(options, cb) {
process.nextTick(function() {
@ -352,7 +353,7 @@ describe('discoverModelProperties', function() {
var ds;
var modelProperties;
before(function() {
ds = new DataSource({ connector: 'memory' });
ds = new DataSource({connector: 'memory'});
modelProperties = [{
owner: 'STRONGLOOP',
@ -436,9 +437,9 @@ describe('discoverModelProperties', function() {
describe('discoverPrimaryKeys', function() {
var ds;
var modelProperties;
var modelProperties, primaryKeys;
before(function() {
ds = new DataSource({ connector: 'memory' });
ds = new DataSource({connector: 'memory'});
primaryKeys = [
{
@ -496,9 +497,9 @@ describe('discoverPrimaryKeys', function() {
describe('discoverForeignKeys', function() {
var ds;
var modelProperties;
var modelProperties, foreignKeys;
before(function() {
ds = new DataSource({ connector: 'memory' });
ds = new DataSource({connector: 'memory'});
foreignKeys = [{
fkOwner: 'STRONGLOOP',
@ -553,9 +554,9 @@ describe('discoverForeignKeys', function() {
describe('discoverExportedForeignKeys', function() {
var ds;
var modelProperties;
var modelProperties, exportedForeignKeys;
before(function() {
ds = new DataSource({ connector: 'memory' });
ds = new DataSource({connector: 'memory'});
exportedForeignKeys = [{
fkName: 'PRODUCT_FK',

View File

@ -2,6 +2,7 @@
// Node module: loopback-datasource-juggler
// This file is licensed under the MIT License.
// License text available at https://opensource.org/licenses/MIT
'use strict';
var should = require('./init.js');
@ -28,25 +29,25 @@ describe('events', function() {
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 +69,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

@ -2,6 +2,7 @@
// Node module: loopback-datasource-juggler
// This file is licensed under the MIT License.
// License text available at https://opensource.org/licenses/MIT
'use strict';
/*global describe,it*/
/*jshint expr:true */
@ -21,7 +22,7 @@ describe('GeoPoint', function() {
});
it('should support a valid object', function() {
var point = new GeoPoint({ lat: -34, lng: 150 });
var point = new GeoPoint({lat: -34, lng: 150});
point.lat.should.equal(-34);
point.lng.should.equal(150);
@ -80,14 +81,14 @@ describe('GeoPoint', function() {
describe('toString()', function() {
it('should return a string in the form "lat,lng"', function() {
var point = new GeoPoint({ lat: -34, lng: 150 });
var point = new GeoPoint({lat: -34, lng: 150});
point.toString().should.equal('-34,150');
});
});
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 });
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() {
var distance = GeoPoint.distanceBetween(here, there);
@ -105,27 +106,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

@ -2,6 +2,7 @@
// Node module: loopback-datasource-juggler
// This file is licensed under the MIT License.
// License text available at https://opensource.org/licenses/MIT
'use strict';
var traverse = require('traverse');

View File

@ -2,6 +2,7 @@
// Node module: loopback-datasource-juggler
// This file is licensed under the MIT License.
// License text available at https://opensource.org/licenses/MIT
'use strict';
module.exports = HookMonitor;

View File

@ -2,6 +2,7 @@
// Node module: loopback-datasource-juggler
// This file is licensed under the MIT License.
// License text available at https://opensource.org/licenses/MIT
'use strict';
var lastId = 0;

View File

@ -2,6 +2,7 @@
// Node module: loopback-datasource-juggler
// This file is licensed under the MIT License.
// License text available at https://opensource.org/licenses/MIT
'use strict';
// This test written in mocha+should.js
var should = require('./init.js');
@ -18,7 +19,7 @@ describe('hooks', function() {
db = getSchema();
User = db.define('User', {
email: { type: String, index: true },
email: {type: String, index: true},
name: String,
password: String,
state: String,
@ -46,7 +47,7 @@ describe('hooks', function() {
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();
@ -127,7 +128,7 @@ describe('hooks', function() {
it('should be triggered on updateAttributes', function(done) {
User.create(function(err, user) {
addHooks('Save', done);
user.updateAttributes({ name: 'Anatoliy' });
user.updateAttributes({name: 'Anatoliy'});
});
});
@ -161,7 +162,7 @@ describe('hooks', function() {
password: '53cr3t',
}, function() {
User.findOne({
where: { email: 'james.bond@example.com' },
where: {email: 'james.bond@example.com'},
}, function(err, jb) {
jb.password.should.equal('hash');
done();
@ -184,7 +185,7 @@ describe('hooks', function() {
should.exist(u);
u.password.should.equal('hash');
User.findOne({
where: { email: 'james.bond@example.com' },
where: {email: 'james.bond@example.com'},
}, function(err, jb) {
jb.password.should.equal('hash');
done();
@ -229,7 +230,7 @@ describe('hooks', function() {
it('should be triggered on updateAttributes', function(done) {
User.create(function(err, user) {
addHooks('Update', done);
user.updateAttributes({ name: 'Anatoliy' });
user.updateAttributes({name: 'Anatoliy'});
});
});
@ -247,7 +248,7 @@ describe('hooks', function() {
data.should.have.keys('name', 'email');
done();
};
user.updateAttributes({ name: 1, email: 2 });
user.updateAttributes({name: 1, email: 2});
});
});
@ -392,7 +393,7 @@ describe('hooks', function() {
});
it('should describe updateAttributes sequence', function(done) {
user.updateAttributes({ name: 'Antony' }, function() {
user.updateAttributes({name: 'Antony'}, function() {
life.should.eql([
'beforeValidate',
'afterValidate',

View File

@ -2,6 +2,7 @@
// Node module: loopback-datasource-juggler
// This file is licensed under the MIT License.
// License text available at https://opensource.org/licenses/MIT
'use strict';
// This test written in mocha+should.js
var should = require('./init.js');
@ -16,7 +17,7 @@ describe('include', function() {
before(setup);
it('should fetch belongsTo relation', function(done) {
Passport.find({ include: 'owner' }, function(err, passports) {
Passport.find({include: 'owner'}, function(err, passports) {
passports.length.should.be.ok;
passports.forEach(function(p) {
p.__cachedRelations.should.have.property('owner');
@ -39,7 +40,7 @@ describe('include', function() {
});
it('should fetch hasMany relation', function(done) {
User.find({ include: 'posts' }, function(err, users) {
User.find({include: 'posts'}, function(err, users) {
should.not.exist(err);
should.exist(users);
users.length.should.be.ok;
@ -59,7 +60,7 @@ describe('include', function() {
});
it('should fetch Passport - Owner - Posts', function(done) {
Passport.find({ include: { owner: 'posts' }}, function(err, passports) {
Passport.find({include: {owner: 'posts'}}, function(err, passports) {
should.not.exist(err);
should.exist(passports);
passports.length.should.be.ok;
@ -90,7 +91,7 @@ describe('include', function() {
});
it('should fetch Passport - Owner - empty Posts', function(done) {
Passport.findOne({ where: { number: '4' }, include: { owner: 'posts' }}, function(err, passport) {
Passport.findOne({where: {number: '4'}, include: {owner: 'posts'}}, function(err, passport) {
should.not.exist(err);
should.exist(passport);
passport.__cachedRelations.should.have.property('owner');
@ -112,7 +113,7 @@ describe('include', function() {
});
it('should fetch Passport - Owner - Posts - alternate syntax', function(done) {
Passport.find({ include: { owner: { relation: 'posts' }}}, function(err, passports) {
Passport.find({include: {owner: {relation: 'posts'}}}, function(err, passports) {
should.not.exist(err);
should.exist(passports);
passports.length.should.be.ok;
@ -124,7 +125,7 @@ describe('include', function() {
it('should fetch Passports - User - Posts - User', function(done) {
Passport.find({
include: { owner: { posts: 'author' }},
include: {owner: {posts: 'author'}},
}, function(err, passports) {
should.not.exist(err);
should.exist(passports);
@ -154,7 +155,7 @@ describe('include', function() {
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',
}}},
@ -209,7 +210,7 @@ describe('include', function() {
it('should fetch Users with include scope on Posts - belongsTo', function(done) {
Post.find({
include: { relation: 'author', scope: { fields: ['name'] }},
include: {relation: 'author', scope: {fields: ['name']}},
}, function(err, posts) {
should.not.exist(err);
should.exist(posts);
@ -262,7 +263,7 @@ describe('include', function() {
include: {
relation: 'passports',
scope: {
where: { number: '2' },
where: {number: '2'},
},
},
}, function(err, users) {
@ -282,7 +283,7 @@ describe('include', function() {
});
it('should fetch User - Posts AND Passports', function(done) {
User.find({ include: ['posts', 'passports'] }, function(err, users) {
User.find({include: ['posts', 'passports']}, function(err, users) {
should.not.exist(err);
should.exist(users);
users.length.should.be.ok;
@ -315,12 +316,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) {
]}, function(err, users) {
should.not.exist(err);
should.exist(users);
users.length.should.be.ok;
@ -353,7 +354,7 @@ describe('include', function() {
});
it('should not fetch User - AccessTokens', function(done) {
User.find({ include: ['accesstokens'] }, function(err, users) {
User.find({include: ['accesstokens']}, function(err, users) {
should.not.exist(err);
should.exist(users);
users.length.should.be.ok;
@ -366,8 +367,8 @@ describe('include', function() {
});
it('should support hasAndBelongsToMany', function(done) {
Assembly.create({ name: 'car' }, function(err, assembly) {
Part.create({ partNumber: 'engine' }, function(err, part) {
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);
@ -376,8 +377,8 @@ describe('include', function() {
parts[0].partNumber.should.equal('engine');
// Create a part
assembly.parts.create({ partNumber: 'door' }, function(err, part4) {
Assembly.find({ include: 'parts' }, function(err, assemblies) {
assembly.parts.create({partNumber: 'door'}, function(err, part4) {
Assembly.find({include: 'parts'}, function(err, assemblies) {
assemblies.length.should.equal(1);
assemblies[0].parts().length.should.equal(2);
done();
@ -390,7 +391,7 @@ describe('include', function() {
});
it('should fetch User - Profile (HasOne)', function(done) {
User.find({ include: ['profile'] }, function(err, users) {
User.find({include: ['profile']}, function(err, users) {
should.not.exist(err);
should.exist(users);
users.length.should.be.ok;
@ -422,8 +423,8 @@ 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' },
Assembly.find({include: {relation: 'parts', scope: {
where: {partNumber: 'engine'},
}}}, function(err, assemblies) {
assemblies.length.should.equal(1);
var parts = assemblies[0].parts();
@ -471,7 +472,7 @@ describe('include', function() {
});
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) {
p.__cachedRelations.should.have.property('owner');
@ -494,11 +495,11 @@ describe('include', function() {
it('including hasManyThrough should make only 3 db calls', function(done) {
var self = this;
Assembly.create([{ name: 'sedan' }, { name: 'hatchback' },
{ name: 'SUV' }],
Assembly.create([{name: 'sedan'}, {name: 'hatchback'},
{name: 'SUV'}],
function(err, assemblies) {
Part.create([{ partNumber: 'engine' }, { partNumber: 'bootspace' },
{ partNumber: 'silencer' }],
Part.create([{partNumber: 'engine'}, {partNumber: 'bootspace'},
{partNumber: 'silencer'}],
function(err, parts) {
async.each(parts, function(part, next) {
async.each(assemblies, function(assembly, next) {
@ -547,7 +548,7 @@ describe('include', function() {
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;
@ -582,9 +583,9 @@ describe('include', function() {
it('should not make n+1 db calls in relation syntax',
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;
@ -619,22 +620,22 @@ describe('include', function() {
});
it('should support disableInclude for hasAndBelongsToMany', function() {
var Patient = db.define('Patient', { name: String });
var Doctor = db.define('Doctor', { name: String });
var Patient = db.define('Patient', {name: String});
var Doctor = db.define('Doctor', {name: String});
var DoctorPatient = db.define('DoctorPatient');
Doctor.hasAndBelongsToMany('patients', {
model: 'Patient',
options: { disableInclude: true },
options: {disableInclude: true},
});
var doctor;
return db.automigrate(['Patient', 'Doctor', 'DoctorPatient']).then(function() {
return Doctor.create({ name: 'Who' });
return Doctor.create({name: 'Who'});
}).then(function(inst) {
doctor = inst;
return doctor.patients.create({ name: 'Lazarus' });
return doctor.patients.create({name: 'Lazarus'});
}).then(function() {
return Doctor.find({ include: ['patients'] });
return Doctor.find({include: ['patients']});
}).then(function(list) {
list.should.have.length(1);
list[0].toJSON().should.not.have.property('patients');
@ -664,16 +665,16 @@ function setup(done) {
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,
@ -696,11 +697,11 @@ 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) {
createdUsers = items;
@ -714,8 +715,8 @@ 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) {}
);
@ -725,10 +726,10 @@ 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) {
createdPassports = items;
@ -741,9 +742,9 @@ 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;
@ -756,11 +757,11 @@ 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) {
createdPosts = items;
@ -796,7 +797,7 @@ 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,
@ -852,25 +853,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];
assert(levelOneInclusion.__data === undefined, '.__data of a level 1 inclusion is undefined.');

View File

@ -2,6 +2,7 @@
// Node module: loopback-datasource-juggler
// This file is licensed under the MIT License.
// License text available at https://opensource.org/licenses/MIT
'use strict';
/* eslint-disable camelcase */
@ -14,8 +15,8 @@ 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');
result.get(11).should.be.ok;
@ -24,10 +25,10 @@ describe('include_util', function() {
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!' },
{id: 11, letter: 'A'},
{id: 22, letter: 'B'},
{id: 33, letter: 'C'},
{id: 11, letter: 'HA!'},
];
var result = includeUtils.buildOneToOneIdentityMapWithOrigKeys(objs, 'id');
@ -41,8 +42,8 @@ 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');
result.get(11).should.be.ok;
@ -53,8 +54,8 @@ describe('include_util', function() {
describe('#buildOneToManyIdentityMap', 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.buildOneToManyIdentityMapWithOrigKeys(objs, 'id');
result.exist(11).should.be.true;
@ -63,10 +64,10 @@ describe('include_util', function() {
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!' },
{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');
@ -92,11 +93,11 @@ describe('KVMap', function() {
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() {
var map = new includeUtils.KVMap();

View File

@ -2,6 +2,7 @@
// Node module: loopback-datasource-juggler
// This file is licensed under the MIT License.
// License text available at https://opensource.org/licenses/MIT
'use strict';
module.exports = require('should');

View File

@ -2,6 +2,7 @@
// Node module: loopback-datasource-juggler
// This file is licensed under the MIT License.
// License text available at https://opensource.org/licenses/MIT
'use strict';
var assert = require('assert');
var ModelBuilder = require('..').ModelBuilder;
@ -23,8 +24,8 @@ var json = {
},
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: [],
};
@ -59,7 +60,7 @@ describe('Introspection of model definitions from JSON', function() {
});
it('should return a schema for object', function() {
var json = { a: 'str', b: 0, c: true };
var json = {a: 'str', b: 0, c: true};
var type = introspectType(json);
assert.equal(type.a, 'string');
assert.equal(type.b, 'number');
@ -67,7 +68,7 @@ describe('Introspection of model definitions from JSON', function() {
});
it('should handle nesting objects', function() {
var json = { a: 'str', b: 0, c: true, d: { x: 10, y: 5 }};
var json = {a: 'str', b: 0, c: true, d: {x: 10, y: 5}};
var type = introspectType(json);
assert.equal(type.a, 'string');
assert.equal(type.b, 'number');
@ -77,7 +78,7 @@ describe('Introspection of model definitions from JSON', function() {
});
it('should handle nesting arrays', function() {
var json = { a: 'str', b: 0, c: true, d: [1, 2] };
var json = {a: 'str', b: 0, c: true, d: [1, 2]};
var type = introspectType(json);
assert.equal(type.a, 'string');
assert.equal(type.b, 'number');
@ -91,7 +92,7 @@ describe('Introspection of model definitions from JSON', function() {
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);
@ -106,7 +107,7 @@ describe('Introspection of model definitions from JSON', function() {
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();
@ -119,7 +120,7 @@ describe('Introspection of model definitions from JSON', function() {
var builder = new DataSource('memory');
var Model = builder.buildModelFromInstance('MyModel', copy,
{ idInjection: false });
{idInjection: false});
assert.equal(Model.dataSource, builder);

View File

@ -2,6 +2,7 @@
// Node module: loopback-datasource-juggler
// This file is licensed under the MIT License.
// License text available at https://opensource.org/licenses/MIT
'use strict';
// This test written in mocha+should.js
var should = require('./init.js');
@ -14,7 +15,7 @@ describe('JSON property', 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);
@ -30,7 +31,7 @@ describe('JSON property', 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');
});

View File

@ -1,9 +1,11 @@
'use strict';
var kvMemory = require('../lib/connectors/kv-memory');
var DataSource = require('..').DataSource;
describe('KeyValue-Memory connector', function() {
var dataSourceFactory = function() {
return new DataSource({ connector: kvMemory });
return new DataSource({connector: kvMemory});
};
require('./kvao.suite')(dataSourceFactory);

View File

@ -31,9 +31,9 @@ module.exports = function(dataSourceFactory, connectorCapabilities) {
});
it('works for Object values', function() {
return CacheItem.set('a-key', { a: 1, b: 2 })
return CacheItem.set('a-key', {a: 1, b: 2})
.then(function() { return CacheItem.get('a-key'); })
.then(function(value) { value.should.eql({ a: 1, b: 2 }); });
.then(function(value) { value.should.eql({a: 1, b: 2}); });
});
it('works for Buffer values', function() {
@ -70,7 +70,7 @@ module.exports = function(dataSourceFactory, connectorCapabilities) {
});
it('honours options.ttl', function() {
return Promise.resolve(CacheItem.set('a-key', 'a-value', { ttl: TTL_PRECISION }))
return Promise.resolve(CacheItem.set('a-key', 'a-value', {ttl: TTL_PRECISION}))
.delay(2 * TTL_PRECISION)
.then(function() { return CacheItem.get('a-key'); })
.then(function(value) { should.equal(value, null); });
@ -92,7 +92,7 @@ module.exports = function(dataSourceFactory, connectorCapabilities) {
});
it('resets TTL timer', function() {
return Promise.resolve(CacheItem.set('a-key', 'a-value', { ttl: TTL_PRECISION }))
return Promise.resolve(CacheItem.set('a-key', 'a-value', {ttl: TTL_PRECISION}))
.then(function() {
return CacheItem.set('a-key', 'another-value'); // no TTL
})

View File

@ -87,19 +87,19 @@ module.exports = function(dataSourceFactory, connectorCapabilities) {
});
it('supports "?" operator', function() {
return CacheItem.sortedKeys({ match: 'h?llo' }).then(function(keys) {
return CacheItem.sortedKeys({match: 'h?llo'}).then(function(keys) {
should(keys).eql(['hallo', 'hello', 'hxllo']);
});
});
it('supports "*" operator', function() {
return CacheItem.sortedKeys({ match: 'h*llo' }).then(function(keys) {
return CacheItem.sortedKeys({match: 'h*llo'}).then(function(keys) {
should(keys).eql(['hallo', 'heeello', 'hello', 'hllo', 'hxllo']);
});
});
it('handles no matches found', function() {
return CacheItem.sortedKeys({ match: 'not-found' })
return CacheItem.sortedKeys({match: 'not-found'})
.then(function(keys) {
should(keys).eql([]);
});

View File

@ -28,7 +28,7 @@ module.exports = function(dataSourceFactory, connectorCapabilities) {
it('gets TTL when key with unexpired TTL exists - Promise API',
function() {
return Promise.resolve(
CacheItem.set('a-key', 'a-value', { ttl: INITIAL_TTL }))
CacheItem.set('a-key', 'a-value', {ttl: INITIAL_TTL}))
.delay(SMALL_DELAY)
.then(function() { return CacheItem.ttl('a-key'); })
.then(function(ttl) { ttl.should.be.within(1, INITIAL_TTL); });
@ -36,7 +36,7 @@ module.exports = function(dataSourceFactory, connectorCapabilities) {
it('gets TTL when key with unexpired TTL exists - Callback API',
function(done) {
CacheItem.set('a-key', 'a-value', { ttl: INITIAL_TTL }, function(err) {
CacheItem.set('a-key', 'a-value', {ttl: INITIAL_TTL}, function(err) {
if (err) return done(err);
CacheItem.ttl('a-key', function(err, ttl) {
if (err) return done(err);
@ -54,7 +54,7 @@ module.exports = function(dataSourceFactory, connectorCapabilities) {
it('fails when getting TTL for a key with expired TTL', function() {
return Promise.resolve(
CacheItem.set('expired-key', 'a-value', { ttl: TTL_PRECISION }))
CacheItem.set('expired-key', 'a-value', {ttl: TTL_PRECISION}))
.delay(2 * TTL_PRECISION)
.then(function() {
return CacheItem.ttl('expired-key');

View File

@ -2,6 +2,7 @@
// Node module: loopback-datasource-juggler
// This file is licensed under the MIT License.
// License text available at https://opensource.org/licenses/MIT
'use strict';
// This test written in mocha+should.js
var should = require('./init.js');

File diff suppressed because it is too large Load Diff

View File

@ -2,6 +2,7 @@
// Node module: loopback-datasource-juggler
// This file is licensed under the MIT License.
// License text available at https://opensource.org/licenses/MIT
'use strict';
// This test written in mocha+should.js
var async = require('async');
@ -20,10 +21,10 @@ describe('manipulation', function() {
name: String,
gender: String,
married: Boolean,
age: { type: Number, index: true },
age: {type: Number, index: true},
dob: Date,
createdAt: { type: Date, default: Date },
}, { forceId: true, strict: true });
createdAt: {type: Date, default: Date},
}, {forceId: true, strict: true});
db.automigrate(['Person'], done);
});
@ -33,7 +34,7 @@ describe('manipulation', function() {
// For the purpose of the tests, we use a counter instead of a hash fn.
var StubUser;
before(function setupStubUserModel(done) {
StubUser = db.createModel('StubUser', { password: String }, { forceId: true });
StubUser = db.createModel('StubUser', {password: String}, {forceId: true});
StubUser.setter.password = function(plain) {
var hashed = false;
if (!plain) return;
@ -50,7 +51,7 @@ describe('manipulation', function() {
});
beforeEach(function resetStubPasswordCounter() {
stubPasswordCounter = 0;
var stubPasswordCounter = 0;
});
describe('create', function() {
@ -59,7 +60,7 @@ describe('manipulation', function() {
});
it('should create instance', function(done) {
Person.create({ name: 'Anatoliy' }, function(err, p) {
Person.create({name: 'Anatoliy'}, function(err, p) {
p.name.should.equal('Anatoliy');
should.not.exist(err);
should.exist(p);
@ -72,7 +73,7 @@ describe('manipulation', function() {
});
it('should create instance (promise variant)', function(done) {
Person.create({ name: 'Anatoliy' })
Person.create({name: 'Anatoliy'})
.then (function(p) {
p.name.should.equal('Anatoliy');
should.exist(p);
@ -87,7 +88,7 @@ describe('manipulation', function() {
});
it('should instantiate an object', function(done) {
var p = new Person({ name: 'Anatoliy' });
var p = new Person({name: 'Anatoliy'});
p.name.should.equal('Anatoliy');
p.isNewRecord().should.be.true;
p.save(function(err, inst) {
@ -99,7 +100,7 @@ describe('manipulation', function() {
});
it('should instantiate an object (promise variant)', function(done) {
var p = new Person({ name: 'Anatoliy' });
var p = new Person({name: 'Anatoliy'});
p.name.should.equal('Anatoliy');
p.isNewRecord().should.be.true;
p.save()
@ -122,7 +123,7 @@ describe('manipulation', function() {
});
it('should not allow user-defined value for the id of object - create', function(done) {
Person.create({ id: 123456 }, function(err, p) {
Person.create({id: 123456}, function(err, p) {
err.should.be.instanceof(ValidationError);
err.statusCode.should.equal(422);
err.details.messages.id.should.eql(['can\'t be set']);
@ -134,7 +135,7 @@ describe('manipulation', function() {
});
it('should not allow user-defined value for the id of object - create (promise variant)', function(done) {
Person.create({ id: 123456 })
Person.create({id: 123456})
.then (function(p) {
done(new Error('Person.create should have failed.'));
}, function(err) {
@ -147,7 +148,7 @@ describe('manipulation', function() {
});
it('should not allow user-defined value for the id of object - save', function(done) {
var p = new Person({ id: 123456 });
var p = new Person({id: 123456});
p.isNewRecord().should.be.true;
p.save(function(err, inst) {
err.should.be.instanceof(ValidationError);
@ -160,7 +161,7 @@ describe('manipulation', function() {
});
it('should not allow user-defined value for the id of object - save (promise variant)', function(done) {
var p = new Person({ id: 123456 });
var p = new Person({id: 123456});
p.isNewRecord().should.be.true;
p.save()
.then (function(inst) {
@ -183,7 +184,7 @@ describe('manipulation', function() {
next();
setTimeout(done, 10);
};
Person.create({ name: 'Nickolay' });
Person.create({name: 'Nickolay'});
});
it('should create instance with blank data', function(done) {
@ -227,8 +228,8 @@ describe('manipulation', function() {
it('should create batch of objects', function(done) {
var batch = [
{ name: 'Shaltay' },
{ name: 'Boltay' },
{name: 'Shaltay'},
{name: 'Boltay'},
{},
];
Person.create(batch, function(e, ps) {
@ -257,14 +258,14 @@ describe('manipulation', function() {
it('should create batch of objects with beforeCreate', function(done) {
Person.beforeCreate = function(next, data) {
if (data && data.name === 'A') {
return next(null, { id: 'a', name: 'A' });
return next(null, {id: 'a', name: 'A'});
} else {
return next();
}
};
var batch = [
{ name: 'A' },
{ name: 'B' },
{name: 'A'},
{name: 'B'},
undefined,
];
Person.create(batch, function(e, ps) {
@ -272,14 +273,14 @@ describe('manipulation', function() {
should.exist(ps);
ps.should.be.instanceOf(Array);
ps.should.have.lengthOf(batch.length);
ps[0].should.be.eql({ id: 'a', name: 'A' });
ps[0].should.be.eql({id: 'a', name: 'A'});
done();
});
});
it('should preserve properties with "undefined" value', function(done) {
Person.create(
{ name: 'a-name', gender: undefined },
{name: 'a-name', gender: undefined},
function(err, created) {
if (err) return done(err);
created.toObject().should.have.properties({
@ -305,13 +306,13 @@ describe('manipulation', function() {
it('should refuse to create object with duplicate id', function(done) {
// NOTE(bajtos) We cannot reuse Person model here,
// `settings.forceId` aborts the CREATE request at the validation step.
var Product = db.define('ProductTest', { name: String });
var Product = db.define('ProductTest', {name: String});
db.automigrate('ProductTest', function(err) {
if (err) return done(err);
Product.create({ name: 'a-name' }, function(err, p) {
Product.create({name: 'a-name'}, function(err, p) {
if (err) return done(err);
Product.create({ id: p.id, name: 'duplicate' }, function(err) {
Product.create({id: p.id, name: 'duplicate'}, function(err) {
if (!err) {
return done(new Error('Create should have rejected duplicate id.'));
}
@ -385,7 +386,7 @@ describe('manipulation', function() {
p.name = 'Nana';
p.save(function(err) {
should.exist(err);
p.save({ validate: false }, function(err) {
p.save({validate: false}, function(err) {
should.not.exist(err);
done();
});
@ -406,7 +407,7 @@ describe('manipulation', function() {
done(new Error('save should have failed.'));
}, function(err) {
should.exist(err);
p.save({ validate: false })
p.save({validate: false})
.then(function(d) {
should.exist(d);
done();
@ -434,7 +435,7 @@ describe('manipulation', function() {
it('should preserve properties with dynamic setters', function(done) {
// This test reproduces a problem discovered by LoopBack unit-test
// "User.hasPassword() should match a password after it is changed"
StubUser.create({ password: 'foo' }, function(err, created) {
StubUser.create({password: 'foo'}, function(err, created) {
if (err) return done(err);
created.password = 'bar';
created.save(function(err, saved) {
@ -455,7 +456,7 @@ describe('manipulation', function() {
before(function(done) {
Person.destroyAll(function() {
Person.create({ name: 'Mary', age: 15 }, function(err, p) {
Person.create({name: 'Mary', age: 15}, function(err, p) {
if (err) return done(err);
person = p;
done();
@ -470,7 +471,7 @@ describe('manipulation', function() {
it('should have updated password hashed with updateAttribute',
function(done) {
StubUser.create({ password: 'foo' }, function(err, created) {
StubUser.create({password: 'foo'}, function(err, created) {
if (err) return done(err);
created.updateAttribute('password', 'test', function(err, created) {
if (err) return done(err);
@ -509,7 +510,7 @@ describe('manipulation', function() {
});
it('should ignore undefined values on updateAttributes', function(done) {
person.updateAttributes({ 'name': 'John', age: undefined },
person.updateAttributes({'name': 'John', age: undefined},
function(err, p) {
if (err) return done(err);
Person.findById(p.id, function(e, p) {
@ -525,7 +526,7 @@ describe('manipulation', function() {
// Using {foo: 'bar'} only causes dependent test failures due to the
// stripping of object properties when in strict mode (ie. {foo: 'bar'}
// changes to '{}' and breaks other tests
person.updateAttributes({ name: 'John', foo: 'bar' },
person.updateAttributes({name: 'John', foo: 'bar'},
function(err, p) {
if (err) return done(err);
should.not.exist(p.foo);
@ -540,7 +541,7 @@ describe('manipulation', function() {
it('should throw error on unknown attributes when strict: throw', function(done) {
Person.definition.settings.strict = 'throw';
Person.findById(person.id, function(err, p) {
p.updateAttributes({ foo: 'bar' },
p.updateAttributes({foo: 'bar'},
function(err, p) {
should.exist(err);
err.name.should.equal('Error');
@ -558,7 +559,7 @@ describe('manipulation', function() {
it('should throw error on unknown attributes when strict: throw', function(done) {
Person.definition.settings.strict = 'validate';
Person.findById(person.id, function(err, p) {
p.updateAttributes({ foo: 'bar' },
p.updateAttributes({foo: 'bar'},
function(err, p) {
should.exist(err);
err.name.should.equal('ValidationError');
@ -573,7 +574,7 @@ describe('manipulation', function() {
});
it('should allow same id value on updateAttributes', function(done) {
person.updateAttributes({ id: person.id, name: 'John' },
person.updateAttributes({id: person.id, name: 'John'},
function(err, p) {
if (err) return done(err);
Person.findById(p.id, function(e, p) {
@ -592,7 +593,7 @@ describe('manipulation', function() {
// For example MongoDB ObjectId
pid = person.id.toString();
}
person.updateAttributes({ id: pid, name: 'John' },
person.updateAttributes({id: pid, name: 'John'},
function(err, p) {
if (err) return done(err);
Person.findById(p.id, function(e, p) {
@ -606,7 +607,7 @@ describe('manipulation', function() {
it('should fail if an id value is to be changed on updateAttributes',
function(done) {
person.updateAttributes({ id: person.id + 1, name: 'John' },
person.updateAttributes({id: person.id + 1, name: 'John'},
function(err, p) {
should.exist(err);
done();
@ -614,7 +615,7 @@ describe('manipulation', function() {
});
it('should allow model instance on updateAttributes', function(done) {
person.updateAttributes(new Person({ 'name': 'John', age: undefined }),
person.updateAttributes(new Person({'name': 'John', age: undefined}),
function(err, p) {
if (err) return done(err);
Person.findById(p.id, function(e, p) {
@ -627,7 +628,7 @@ describe('manipulation', function() {
});
it('should allow model instance on updateAttributes (promise variant)', function(done) {
person.updateAttributes(new Person({ 'name': 'Jane', age: undefined }))
person.updateAttributes(new Person({'name': 'Jane', age: undefined}))
.then(function(p) {
return Person.findById(p.id)
.then(function(p) {
@ -646,7 +647,7 @@ describe('manipulation', function() {
},
};
person.getConnector = function() { return fakeConnector; };
person.updateAttributes({ name: 'John' }, function(err, p) {
person.updateAttributes({name: 'John'}, function(err, p) {
should.exist(err);
done();
});
@ -659,8 +660,8 @@ describe('manipulation', function() {
before('prepare "Post" model', function(done) {
Post = ds.define('Post', {
title: { type: String, id: true },
content: { type: String },
title: {type: String, id: true},
content: {type: String},
});
ds.automigrate('Post', done);
});
@ -670,7 +671,7 @@ describe('manipulation', function() {
});
it('should preserve properties with dynamic setters on create', function(done) {
StubUser.updateOrCreate({ password: 'foo' }, function(err, created) {
StubUser.updateOrCreate({password: 'foo'}, function(err, created) {
if (err) return done(err);
created.password.should.equal('foo-FOO');
StubUser.findById(created.id, function(err, found) {
@ -682,9 +683,9 @@ describe('manipulation', function() {
});
it('should preserve properties with dynamic setters on update', function(done) {
StubUser.create({ password: 'foo' }, function(err, created) {
StubUser.create({password: 'foo'}, function(err, created) {
if (err) return done(err);
var data = { id: created.id, password: 'bar' };
var data = {id: created.id, password: 'bar'};
StubUser.updateOrCreate(data, function(err, updated) {
if (err) return done(err);
updated.password.should.equal('bar-BAR');
@ -699,7 +700,7 @@ describe('manipulation', function() {
it('should preserve properties with "undefined" value', function(done) {
Person.create(
{ name: 'a-name', gender: undefined },
{name: 'a-name', gender: undefined},
function(err, instance) {
if (err) return done(err);
instance.toObject().should.have.properties({
@ -709,7 +710,7 @@ describe('manipulation', function() {
});
Person.updateOrCreate(
{ id: instance.id, name: 'updated name' },
{id: instance.id, name: 'updated name'},
function(err, updated) {
if (err) return done(err);
var result = updated.toObject();
@ -725,8 +726,8 @@ describe('manipulation', function() {
it.skip('updates specific instances when PK is not an auto-generated id', function(done) {
Post.create([
{ title: 'postA', content: 'contentA' },
{ title: 'postB', content: 'contentB' },
{title: 'postA', content: 'contentA'},
{title: 'postB', content: 'contentB'},
], function(err, instance) {
if (err) return done(err);
@ -756,7 +757,7 @@ describe('manipulation', function() {
it('should allow save() of the created instance', function(done) {
Person.updateOrCreate(
{ id: 999 /* a new id */, name: 'a-name' },
{id: 999 /* a new id */, name: 'a-name'},
function(err, inst) {
if (err) return done(err);
inst.save(done);
@ -772,15 +773,15 @@ describe('manipulation', function() {
var ds = getSchema();
before(function(done) {
Post = ds.define('Post', {
title: { type: String, length: 255, index: true },
content: { type: String },
title: {type: String, length: 255, index: true},
content: {type: String},
comments: [String],
});
ds.automigrate('Post', done);
});
it('works without options on create (promise variant)', function(done) {
var post = { id: 123, title: 'a', content: 'AAA' };
var post = {id: 123, title: 'a', content: 'AAA'};
Post.replaceOrCreate(post)
.then(function(p) {
should.exist(p);
@ -802,8 +803,8 @@ describe('manipulation', function() {
});
it('works with options on create (promise variant)', function(done) {
var post = { id: 123, title: 'a', content: 'AAA' };
Post.replaceOrCreate(post, { validate: false })
var post = {id: 123, title: 'a', content: 'AAA'};
Post.replaceOrCreate(post, {validate: false})
.then(function(p) {
should.exist(p);
p.should.be.instanceOf(Post);
@ -824,7 +825,7 @@ describe('manipulation', function() {
});
it('works without options on update (promise variant)', function(done) {
var post = { title: 'a', content: 'AAA', comments: ['Comment1'] };
var post = {title: 'a', content: 'AAA', comments: ['Comment1']};
Post.create(post)
.then(function(created) {
created = created.toObject();
@ -854,14 +855,14 @@ describe('manipulation', function() {
});
it('works with options on update (promise variant)', function(done) {
var post = { title: 'a', content: 'AAA', comments: ['Comment1'] };
var post = {title: 'a', content: 'AAA', comments: ['Comment1']};
Post.create(post)
.then(function(created) {
created = created.toObject();
delete created.comments;
delete created.content;
created.title = 'b';
return Post.replaceOrCreate(created, { validate: false })
return Post.replaceOrCreate(created, {validate: false})
.then(function(p) {
should.exist(p);
p.should.be.instanceOf(Post);
@ -884,7 +885,7 @@ describe('manipulation', function() {
});
it('works without options on update (callback variant)', function(done) {
Post.create({ title: 'a', content: 'AAA', comments: ['Comment1'] },
Post.create({title: 'a', content: 'AAA', comments: ['Comment1']},
function(err, post) {
if (err) return done(err);
post = post.toObject();
@ -912,8 +913,8 @@ describe('manipulation', function() {
});
it('works with options on update (callback variant)', function(done) {
Post.create({ title: 'a', content: 'AAA', comments: ['Comment1'] },
{ validate: false },
Post.create({title: 'a', content: 'AAA', comments: ['Comment1']},
{validate: false},
function(err, post) {
if (err) return done(err);
post = post.toObject();
@ -941,7 +942,7 @@ describe('manipulation', function() {
});
it('works without options on create (callback variant)', function(done) {
var post = { id: 123, title: 'a', content: 'AAA' };
var post = {id: 123, title: 'a', content: 'AAA'};
Post.replaceOrCreate(post, function(err, p) {
if (err) return done(err);
p.id.should.equal(post.id);
@ -960,8 +961,8 @@ describe('manipulation', function() {
});
it('works with options on create (callback variant)', function(done) {
var post = { id: 123, title: 'a', content: 'AAA' };
Post.replaceOrCreate(post, { validate: false }, function(err, p) {
var post = {id: 123, title: 'a', content: 'AAA'};
Post.replaceOrCreate(post, {validate: false}, function(err, p) {
if (err) return done(err);
p.id.should.equal(post.id);
p.should.not.have.property('_id');
@ -989,15 +990,15 @@ describe('manipulation', function() {
var ds = getSchema();
before(function(done) {
Post = ds.define('Post', {
title: { type: String, length: 255, index: true },
content: { type: String },
title: {type: String, length: 255, index: true},
content: {type: String},
comments: [String],
});
ds.automigrate('Post', done);
});
beforeEach(function(done) {
Post.destroyAll(function() {
Post.create({ title: 'a', content: 'AAA' }, function(err, p) {
Post.create({title: 'a', content: 'AAA'}, function(err, p) {
if (err) return done(err);
postInstance = p;
done();
@ -1007,9 +1008,9 @@ describe('manipulation', function() {
it('should have updated password hashed with replaceAttributes',
function(done) {
StubUser.create({ password: 'foo' }, function(err, created) {
StubUser.create({password: 'foo'}, function(err, created) {
if (err) return done(err);
created.replaceAttributes({ password: 'test' },
created.replaceAttributes({password: 'test'},
function(err, created) {
if (err) return done(err);
created.password.should.equal('test-TEST');
@ -1027,7 +1028,7 @@ describe('manipulation', function() {
Post.findById(postInstance.id, function(err, p) {
if (err) return done(err);
changePostIdInHook('before save');
p.replaceAttributes({ title: 'b' }, function(err, data) {
p.replaceAttributes({title: 'b'}, function(err, data) {
data.id.should.eql(postInstance.id);
if (err) return done(err);
Post.find(function(err, p) {
@ -1045,7 +1046,7 @@ describe('manipulation', function() {
Post.findById(postInstance.id, function(err, p) {
if (err) return done(err);
changePostIdInHook('before save');
p.replaceAttributes({ title: 'b' }, function(err, data) {
p.replaceAttributes({title: 'b'}, function(err, data) {
if (err) return done(err);
Post._warned.cannotOverwritePKInBeforeSaveHook.should.equal(true);
data.id.should.equal(postInstance.id);
@ -1059,7 +1060,7 @@ describe('manipulation', function() {
Post.findById(postInstance.id, function(err, p) {
if (err) return done(err);
changePostIdInHook('loaded');
p.replaceAttributes({ title: 'b' }, function(err, data) {
p.replaceAttributes({title: 'b'}, function(err, data) {
data.id.should.eql(postInstance.id);
if (err) return done(err);
// clear observers to make sure `loaded`
@ -1077,7 +1078,7 @@ describe('manipulation', function() {
it('works without options(promise variant)', function(done) {
Post.findById(postInstance.id)
.then(function(p) {
p.replaceAttributes({ title: 'b' })
p.replaceAttributes({title: 'b'})
.then(function(p) {
should.exist(p);
p.should.be.instanceOf(Post);
@ -1097,7 +1098,7 @@ describe('manipulation', function() {
it('works with options(promise variant)', function(done) {
Post.findById(postInstance.id)
.then(function(p) {
p.replaceAttributes({ title: 'b' }, { validate: false })
p.replaceAttributes({title: 'b'}, {validate: false})
.then(function(p) {
should.exist(p);
p.should.be.instanceOf(Post);
@ -1117,7 +1118,7 @@ describe('manipulation', function() {
it('should fail when changing id', function(done) {
Post.findById(postInstance.id, function(err, p) {
if (err) return done(err);
p.replaceAttributes({ title: 'b', id: 999 }, function(err, p) {
p.replaceAttributes({title: 'b', id: 999}, function(err, p) {
should.exist(err);
var expectedErrMsg = 'id property (id) cannot be updated from ' + postInstance.id + ' to 999';
err.message.should.equal(expectedErrMsg);
@ -1129,7 +1130,7 @@ describe('manipulation', function() {
it('works without options(callback variant)', function(done) {
Post.findById(postInstance.id, function(err, p) {
if (err) return done(err);
p.replaceAttributes({ title: 'b' }, function(err, p) {
p.replaceAttributes({title: 'b'}, function(err, p) {
if (err) return done(err);
p.should.have.property('content', undefined);
p.title.should.equal('b');
@ -1141,7 +1142,7 @@ describe('manipulation', function() {
it('works with options(callback variant)', function(done) {
Post.findById(postInstance.id, function(err, p) {
if (err) return done(err);
p.replaceAttributes({ title: 'b' }, { validate: false }, function(err, p) {
p.replaceAttributes({title: 'b'}, {validate: false}, function(err, p) {
if (err) return done(err);
p.should.have.property('content', undefined);
p.title.should.equal('b');
@ -1161,7 +1162,7 @@ describe('manipulation', function() {
describe('findOrCreate', function() {
it('should create a record with if new', function(done) {
Person.findOrCreate({ name: 'Zed', gender: 'male' },
Person.findOrCreate({name: 'Zed', gender: 'male'},
function(err, p, created) {
if (err) return done(err);
should.exist(p);
@ -1175,8 +1176,8 @@ describe('manipulation', function() {
it('should find a record if exists', function(done) {
Person.findOrCreate(
{ where: { name: 'Zed' }},
{ name: 'Zed', gender: 'male' },
{where: {name: 'Zed'}},
{name: 'Zed', gender: 'male'},
function(err, p, created) {
if (err) return done(err);
should.exist(p);
@ -1189,7 +1190,7 @@ describe('manipulation', function() {
});
it('should create a record with if new (promise variant)', function(done) {
Person.findOrCreate({ name: 'Jed', gender: 'male' })
Person.findOrCreate({name: 'Jed', gender: 'male'})
.then(function(res) {
should.exist(res);
res.should.be.instanceOf(Array);
@ -1207,8 +1208,8 @@ describe('manipulation', function() {
it('should find a record if exists (promise variant)', function(done) {
Person.findOrCreate(
{ where: { name: 'Jed' }},
{ name: 'Jed', gender: 'male' })
{where: {name: 'Jed'}},
{name: 'Jed', gender: 'male'})
.then(function(res) {
res.should.be.instanceOf(Array);
res.should.have.lengthOf(2);
@ -1308,13 +1309,13 @@ describe('manipulation', function() {
it('should only delete instances that satisfy the where condition',
function(done) {
Person.deleteAll({ name: 'John' }, function(err, info) {
Person.deleteAll({name: 'John'}, function(err, info) {
if (err) return done(err);
info.should.have.property('count', 1);
Person.find({ where: { name: 'John' }}, function(err, data) {
Person.find({where: {name: 'John'}}, function(err, data) {
if (err) return done(err);
data.should.have.length(0);
Person.find({ where: { name: 'Jane' }}, function(err, data) {
Person.find({where: {name: 'Jane'}}, function(err, data) {
if (err) return done(err);
data.should.have.length(1);
done();
@ -1325,7 +1326,7 @@ describe('manipulation', function() {
it('should report zero deleted instances when no matches are found',
function(done) {
Person.deleteAll({ name: 'does-not-match' }, function(err, info) {
Person.deleteAll({name: 'does-not-match'}, function(err, info) {
if (err) return done(err);
info.should.have.property('count', 0);
Person.count(function(err, count) {
@ -1440,7 +1441,7 @@ describe('manipulation', function() {
it('should initialize object properly', function() {
var hw = 'Hello word',
now = Date.now(),
person = new Person({ name: hw });
person = new Person({name: hw});
person.name.should.equal(hw);
person.name = 'Goodbye, Lenin';
@ -1453,7 +1454,7 @@ describe('manipulation', function() {
before(function(done) {
CustomModel = db.define('CustomModel1', {
createdAt: { type: Date, default: '$now' },
createdAt: {type: Date, default: '$now'},
});
db.automigrate('CustomModel1', done);
});
@ -1477,7 +1478,7 @@ describe('manipulation', function() {
before(function(done) {
CustomModel = db.define('CustomModel2', {
now: { type: String, default: '$now' },
now: {type: String, default: '$now'},
});
db.automigrate('CustomModel2', done);
});
@ -1499,7 +1500,7 @@ describe('manipulation', function() {
before(function(done) {
CustomModel = db.define('CustomModel3', {
now: { type: Date, defaultFn: 'now' },
now: {type: Date, defaultFn: 'now'},
});
db.automigrate('CustomModel3', done);
});
@ -1521,7 +1522,7 @@ describe('manipulation', function() {
before(function(done) {
CustomModel = db.define('CustomModel4', {
guid: { type: String, defaultFn: 'guid' },
guid: {type: String, defaultFn: 'guid'},
});
db.automigrate('CustomModel4', done);
});
@ -1540,7 +1541,7 @@ describe('manipulation', function() {
before(function(done) {
CustomModel = db.define('CustomModel5', {
guid: { type: String, defaultFn: 'uuid' },
guid: {type: String, defaultFn: 'uuid'},
});
db.automigrate('CustomModel5', done);
});
@ -1559,7 +1560,7 @@ describe('manipulation', function() {
before(function(done) {
CustomModel = db.define('CustomModel5', {
guid: { type: String, defaultFn: 'uuidv4' },
guid: {type: String, defaultFn: 'uuidv4'},
});
db.automigrate('CustomModel5', done);
});
@ -1588,7 +1589,7 @@ describe('manipulation', function() {
function createModelWithShortId(cb) {
ModelWithShortId = db.define('ModelWithShortId', {
shortid: { type: String, defaultFn: 'shortid' },
shortid: {type: String, defaultFn: 'shortid'},
});
db.automigrate('ModelWithShortId', cb);
}
@ -1603,67 +1604,67 @@ describe('manipulation', function() {
describe('property value coercion', function() {
it('should coerce boolean types properly', function() {
var p1 = new Person({ name: 'John', married: 'false' });
var p1 = new Person({name: 'John', married: 'false'});
p1.married.should.equal(false);
p1 = new Person({ name: 'John', married: 'true' });
p1 = new Person({name: 'John', married: 'true'});
p1.married.should.equal(true);
p1 = new Person({ name: 'John', married: '1' });
p1 = new Person({name: 'John', married: '1'});
p1.married.should.equal(true);
p1 = new Person({ name: 'John', married: '0' });
p1 = new Person({name: 'John', married: '0'});
p1.married.should.equal(false);
p1 = new Person({ name: 'John', married: true });
p1 = new Person({name: 'John', married: true});
p1.married.should.equal(true);
p1 = new Person({ name: 'John', married: false });
p1 = new Person({name: 'John', married: false});
p1.married.should.equal(false);
p1 = new Person({ name: 'John', married: 'null' });
p1 = new Person({name: 'John', married: 'null'});
p1.married.should.equal(true);
p1 = new Person({ name: 'John', married: '' });
p1 = new Person({name: 'John', married: ''});
p1.married.should.equal(false);
p1 = new Person({ name: 'John', married: 'X' });
p1 = new Person({name: 'John', married: 'X'});
p1.married.should.equal(true);
p1 = new Person({ name: 'John', married: 0 });
p1 = new Person({name: 'John', married: 0});
p1.married.should.equal(false);
p1 = new Person({ name: 'John', married: 1 });
p1 = new Person({name: 'John', married: 1});
p1.married.should.equal(true);
p1 = new Person({ name: 'John', married: null });
p1 = new Person({name: 'John', married: null});
p1.should.have.property('married', null);
p1 = new Person({ name: 'John', married: undefined });
p1 = new Person({name: 'John', married: undefined});
p1.should.have.property('married', undefined);
});
it('should coerce date types properly', function() {
var p1 = new Person({ name: 'John', dob: '2/1/2015' });
var p1 = new Person({name: 'John', dob: '2/1/2015'});
p1.dob.should.eql(new Date('2/1/2015'));
p1 = new Person({ name: 'John', dob: '2/1/2015' });
p1 = new Person({name: 'John', dob: '2/1/2015'});
p1.dob.should.eql(new Date('2/1/2015'));
p1 = new Person({ name: 'John', dob: '12' });
p1 = new Person({name: 'John', dob: '12'});
p1.dob.should.eql(new Date('12'));
p1 = new Person({ name: 'John', dob: 12 });
p1 = new Person({name: 'John', dob: 12});
p1.dob.should.eql(new Date(12));
p1 = new Person({ name: 'John', dob: null });
p1 = new Person({name: 'John', dob: null});
p1.should.have.property('dob', null);
p1 = new Person({ name: 'John', dob: undefined });
p1 = new Person({name: 'John', dob: undefined});
p1.should.have.property('dob', undefined);
try {
p1 = new Person({ name: 'John', dob: 'X' });
p1 = new Person({name: 'John', dob: 'X'});
throw new Error('new Person() should have thrown');
} catch (e) {
e.should.be.eql(new Error('Invalid date: X'));
@ -1702,11 +1703,11 @@ describe('manipulation', function() {
it('should not update instances that do not satisfy the where condition',
function(done) {
Person.update({ name: 'Harry Hoe' }, { name: 'Marta Moe' }, function(err,
Person.update({name: 'Harry Hoe'}, {name: 'Marta Moe'}, function(err,
info) {
if (err) return done(err);
info.should.have.property('count', 0);
Person.find({ where: { name: 'Harry Hoe' }}, function(err, people) {
Person.find({where: {name: 'Harry Hoe'}}, function(err, people) {
if (err) return done(err);
people.should.be.empty;
done();
@ -1716,11 +1717,11 @@ describe('manipulation', function() {
it('should only update instances that satisfy the where condition',
function(done) {
Person.update({ name: 'Brett Boe' }, { name: 'Harry Hoe' }, function(err,
Person.update({name: 'Brett Boe'}, {name: 'Harry Hoe'}, function(err,
info) {
if (err) return done(err);
info.should.have.property('count', 1);
Person.find({ where: { age: 19 }}, function(err, people) {
Person.find({where: {age: 19}}, function(err, people) {
if (err) return done(err);
people.should.have.length(1);
people[0].name.should.equal('Harry Hoe');
@ -1731,13 +1732,13 @@ describe('manipulation', function() {
it('should update all instances when the where condition is not provided',
function(done) {
Person.update({ name: 'Harry Hoe' }, function(err, info) {
Person.update({name: 'Harry Hoe'}, function(err, info) {
if (err) return done(err);
info.should.have.property('count', 5);
Person.find({ where: { name: 'Brett Boe' }}, function(err, people) {
Person.find({where: {name: 'Brett Boe'}}, function(err, people) {
if (err) return done(err);
people.should.be.empty;
Person.find({ where: { name: 'Harry Hoe' }}, function(err, people) {
Person.find({where: {name: 'Harry Hoe'}}, function(err, people) {
if (err) return done(err);
people.should.have.length(5);
done();
@ -1748,11 +1749,11 @@ describe('manipulation', function() {
it('should ignore where conditions with undefined values',
function(done) {
Person.update({ name: 'Brett Boe' }, { name: undefined, gender: 'male' },
Person.update({name: 'Brett Boe'}, {name: undefined, gender: 'male'},
function(err, info) {
if (err) return done(err);
info.should.have.property('count', 1);
Person.find({ where: { name: 'Brett Boe' }}, function(err, people) {
Person.find({where: {name: 'Brett Boe'}}, function(err, people) {
if (err) return done(err);
people.should.have.length(1);
people[0].name.should.equal('Brett Boe');
@ -1763,7 +1764,7 @@ describe('manipulation', function() {
it('should not coerce invalid values provided in where conditions',
function(done) {
Person.update({ name: 'Brett Boe' }, { dob: 'Carla Coe' }, function(err) {
Person.update({name: 'Brett Boe'}, {dob: 'Carla Coe'}, function(err) {
should.exist(err);
err.message.should.equal('Invalid date: Carla Coe');
done();
@ -1776,9 +1777,9 @@ describe('manipulation', function() {
var Person;
before('prepare "Person" model', function(done) {
Person = ds.define('Person', {
id: { type: Number, id: true },
name: { type: String },
city: { type: String },
id: {type: Number, id: true},
name: {type: String},
city: {type: String},
});
ds.automigrate('Person', done);
});
@ -1788,7 +1789,7 @@ describe('manipulation', function() {
});
it('should preserve properties with dynamic setters on create', function(done) {
StubUser.upsertWithWhere({ password: 'foo' }, { password: 'foo' }, function(err, created) {
StubUser.upsertWithWhere({password: 'foo'}, {password: 'foo'}, function(err, created) {
if (err) return done(err);
created.password.should.equal('foo-FOO');
StubUser.findById(created.id, function(err, found) {
@ -1800,10 +1801,10 @@ describe('manipulation', function() {
});
it('should preserve properties with dynamic setters on update', function(done) {
StubUser.create({ password: 'foo' }, function(err, created) {
StubUser.create({password: 'foo'}, function(err, created) {
if (err) return done(err);
var data = { password: 'bar' };
StubUser.upsertWithWhere({ id: created.id }, data, function(err, updated) {
var data = {password: 'bar'};
StubUser.upsertWithWhere({id: created.id}, data, function(err, updated) {
if (err) return done(err);
updated.password.should.equal('bar-BAR');
StubUser.findById(created.id, function(err, found) {
@ -1817,7 +1818,7 @@ describe('manipulation', function() {
it('should preserve properties with "undefined" value', function(done) {
Person.create(
{ id: 10, name: 'Ritz', city: undefined },
{id: 10, name: 'Ritz', city: undefined},
function(err, instance) {
if (err) return done(err);
instance.toObject().should.have.properties({
@ -1826,8 +1827,8 @@ describe('manipulation', function() {
city: undefined,
});
Person.upsertWithWhere({ id: 10 },
{ name: 'updated name' },
Person.upsertWithWhere({id: 10},
{name: 'updated name'},
function(err, updated) {
if (err) return done(err);
var result = updated.toObject();
@ -1842,9 +1843,9 @@ describe('manipulation', function() {
});
it('should allow save() of the created instance', function(done) {
Person.upsertWithWhere({ id: 999 },
Person.upsertWithWhere({id: 999},
// Todo @mountain: This seems a bug why in data object still I need to pass id?
{ id: 999, name: 'a-name' },
{id: 999, name: 'a-name'},
function(err, inst) {
if (err) return done(err);
inst.save(done);
@ -1852,8 +1853,8 @@ describe('manipulation', function() {
});
it('works without options on create (promise variant)', function(done) {
var person = { id: 123, name: 'a', city: 'city a' };
Person.upsertWithWhere({ id: 123 }, person)
var person = {id: 123, name: 'a', city: 'city a'};
Person.upsertWithWhere({id: 123}, person)
.then(function(p) {
should.exist(p);
p.should.be.instanceOf(Person);
@ -1874,8 +1875,8 @@ describe('manipulation', function() {
});
it('works with options on create (promise variant)', function(done) {
var person = { id: 234, name: 'b', city: 'city b' };
Person.upsertWithWhere({ id: 234 }, person, { validate: false })
var person = {id: 234, name: 'b', city: 'city b'};
Person.upsertWithWhere({id: 234}, person, {validate: false})
.then(function(p) {
should.exist(p);
p.should.be.instanceOf(Person);
@ -1896,13 +1897,13 @@ describe('manipulation', function() {
});
it('works without options on update (promise variant)', function(done) {
var person = { id: 456, name: 'AAA', city: 'city AAA' };
var person = {id: 456, name: 'AAA', city: 'city AAA'};
Person.create(person)
.then(function(created) {
created = created.toObject();
delete created.city;
created.name = 'BBB';
return Person.upsertWithWhere({ id: 456 }, created)
return Person.upsertWithWhere({id: 456}, created)
.then(function(p) {
should.exist(p);
p.should.be.instanceOf(Person);
@ -1923,13 +1924,13 @@ describe('manipulation', function() {
});
it('works with options on update (promise variant)', function(done) {
var person = { id: 789, name: 'CCC', city: 'city CCC' };
var person = {id: 789, name: 'CCC', city: 'city CCC'};
Person.create(person)
.then(function(created) {
created = created.toObject();
delete created.city;
created.name = 'Carlton';
return Person.upsertWithWhere({ id: 789 }, created, { validate: false })
return Person.upsertWithWhere({id: 789}, created, {validate: false})
.then(function(p) {
should.exist(p);
p.should.be.instanceOf(Person);
@ -1950,8 +1951,8 @@ describe('manipulation', function() {
});
it('fails the upsertWithWhere operation when data object is empty', function(done) {
options = {};
Person.upsertWithWhere({ name: 'John Lennon' }, {}, options,
var options = {};
Person.upsertWithWhere({name: 'John Lennon'}, {}, options,
function(err) {
err.message.should.equal('data object cannot be empty!');
done();
@ -1959,7 +1960,7 @@ describe('manipulation', function() {
});
it('creates a new record when no matching instance is found', function(done) {
Person.upsertWithWhere({ city: 'Florida' }, { name: 'Nick Carter', id: 1, city: 'Florida' },
Person.upsertWithWhere({city: 'Florida'}, {name: 'Nick Carter', id: 1, city: 'Florida'},
function(err, created) {
if (err) return done(err);
Person.findById(1, function(err, data) {
@ -1975,11 +1976,11 @@ describe('manipulation', function() {
it('fails the upsertWithWhere operation when multiple instances are ' +
'retrieved based on the filter criteria', function(done) {
Person.create([
{ id: '2', name: 'Howie', city: 'Florida' },
{ id: '3', name: 'Kevin', city: 'Florida' },
{id: '2', name: 'Howie', city: 'Florida'},
{id: '3', name: 'Kevin', city: 'Florida'},
], function(err, instance) {
if (err) return done(err);
Person.upsertWithWhere({ city: 'Florida' }, {
Person.upsertWithWhere({city: 'Florida'}, {
id: '4', name: 'Brian',
}, function(err) {
err.message.should.equal('There are multiple instances found.' +
@ -1992,12 +1993,12 @@ describe('manipulation', function() {
it('updates the record when one matching instance is found ' +
'based on the filter criteria', function(done) {
Person.create([
{ id: '5', name: 'Howie', city: 'Kentucky' },
{id: '5', name: 'Howie', city: 'Kentucky'},
], function(err, instance) {
if (err) return done(err);
Person.upsertWithWhere({ city: 'Kentucky' }, {
Person.upsertWithWhere({city: 'Kentucky'}, {
name: 'Brian',
}, { validate: false }, function(err, instance) {
}, {validate: false}, function(err, instance) {
if (err) return done(err);
Person.findById(5, function(err, data) {
if (err) return done(err);
@ -2014,12 +2015,12 @@ describe('manipulation', function() {
function givenSomePeople(done) {
var beatles = [
{ name: 'John Lennon', gender: 'male' },
{ name: 'Paul McCartney', gender: 'male' },
{ name: 'George Harrison', gender: 'male' },
{ name: 'Ringo Starr', gender: 'male' },
{ name: 'Pete Best', gender: 'male' },
{ name: 'Stuart Sutcliffe', gender: 'male' },
{name: 'John Lennon', gender: 'male'},
{name: 'Paul McCartney', gender: 'male'},
{name: 'George Harrison', gender: 'male'},
{name: 'Ringo Starr', gender: 'male'},
{name: 'Pete Best', gender: 'male'},
{name: 'Stuart Sutcliffe', gender: 'male'},
];
async.series([

View File

@ -2,6 +2,7 @@
// Node module: loopback-datasource-juggler
// This file is licensed under the MIT License.
// License text available at https://opensource.org/licenses/MIT
'use strict';
var jdb = require('../');
var DataSource = jdb.DataSource;
@ -64,7 +65,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 +93,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 +111,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);
@ -144,13 +145,13 @@ describe('Memory connector', function() {
});
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,
@ -171,7 +172,7 @@ describe('Memory connector', function() {
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();
@ -179,7 +180,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();
@ -187,7 +188,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();
@ -195,7 +196,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();
@ -203,7 +204,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();
@ -211,7 +212,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();
@ -219,56 +220,56 @@ 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');
@ -277,7 +278,7 @@ describe('Memory connector', function() {
});
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();
@ -285,7 +286,7 @@ describe('Memory connector', function() {
});
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');
@ -298,7 +299,7 @@ describe('Memory connector', function() {
User.find({
where: {
name: 'John Lennon',
and: [{ role: 'lead' }, { vip: true }],
and: [{role: 'lead'}, {vip: true}],
},
}, function(err, users) {
should(users.length).be.equal(1);
@ -308,8 +309,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();
@ -317,7 +318,7 @@ 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();
@ -356,7 +357,7 @@ describe('Memory connector', function() {
it('should successfully extract 5 users matching a neq filter over array values', function(done) {
User.find({
where: {
'children': { neq: 'Dhani' },
'children': {neq: 'Dhani'},
},
}, function(err, users) {
should.not.exist(err);
@ -366,7 +367,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();
@ -374,7 +375,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);
@ -383,7 +384,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);
@ -393,14 +394,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++) {
@ -411,7 +412,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++) {
@ -424,7 +425,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++) {
@ -436,7 +437,7 @@ 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) {
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');
@ -445,7 +446,7 @@ describe('Memory connector', function() {
});
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');
@ -454,7 +455,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');
@ -463,7 +464,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);
@ -473,7 +474,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++) {
@ -484,7 +485,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');
@ -494,7 +495,7 @@ 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) {
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++) {
@ -505,7 +506,7 @@ describe('Memory connector', function() {
});
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);
@ -516,8 +517,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);
@ -529,7 +530,7 @@ describe('Memory connector', function() {
});
it('should support multi-level nested array property in query', function(done) {
User.find({ where: { 'address.tags.tag': 'business' }}, function(err, users) {
User.find({where: {'address.tags.tag': 'business'}}, function(err, users) {
should.not.exist(err);
users.length.should.be.equal(1);
users[0].address.tags[0].tag.should.be.equal('business');
@ -553,14 +554,14 @@ describe('Memory connector', function() {
state: 'CA',
zipCode: '95131',
tags: [
{ tag: 'business' },
{ tag: 'rent' },
{tag: 'business'},
{tag: 'rent'},
],
},
friends: [
{ name: 'Paul McCartney' },
{ name: 'George Harrison' },
{ name: 'Ringo Starr' },
{name: 'Paul McCartney'},
{name: 'George Harrison'},
{name: 'Ringo Starr'},
],
children: ['Sean', 'Julian'],
},
@ -579,16 +580,16 @@ describe('Memory connector', function() {
zipCode: '94065',
},
friends: [
{ name: 'John Lennon' },
{ name: 'George Harrison' },
{ name: 'Ringo Starr' },
{name: 'John Lennon'},
{name: 'George Harrison'},
{name: 'Ringo Starr'},
],
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([
@ -611,32 +612,32 @@ describe('Memory connector', function() {
var Tool = ds.createModel('Tool', {
name: String,
}, { memory: { collection: 'Product' }});
}, {memory: {collection: 'Product'}});
var Widget = ds.createModel('Widget', {
name: String,
}, { memory: { collection: 'Product' }});
}, {memory: {collection: 'Product'}});
ds.connector.getCollection('Tool').should.equal('Product');
ds.connector.getCollection('Widget').should.equal('Product');
async.series([
function(next) {
Tool.create({ name: 'Tool A' }, next);
Tool.create({name: 'Tool A'}, next);
},
function(next) {
Tool.create({ name: 'Tool B' }, next);
Tool.create({name: 'Tool B'}, next);
},
function(next) {
Widget.create({ name: 'Widget A' }, next);
Widget.create({name: 'Widget A'}, next);
},
], function(err) {
Product.find(function(err, products) {
should.not.exist(err);
products.should.have.length(3);
products[0].toObject().should.eql({ name: 'Tool A', id: 1 });
products[1].toObject().should.eql({ name: 'Tool B', id: 2 });
products[2].toObject().should.eql({ name: 'Widget A', id: 3 });
products[0].toObject().should.eql({name: 'Tool A', id: 1});
products[1].toObject().should.eql({name: 'Tool B', id: 2});
products[2].toObject().should.eql({name: 'Widget A', id: 3});
done();
});
});
@ -724,7 +725,7 @@ 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,
});
@ -733,8 +734,8 @@ describe('Memory connector', function() {
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);
@ -867,7 +868,7 @@ describe('Memory connector', function() {
});
describe('Optimized connector', function() {
var ds = new DataSource({ connector: Memory });
var ds = new DataSource({connector: Memory});
require('./persistence-hooks.suite')(ds, should, {
replaceOrCreateReportsNewInstance: true,
@ -875,7 +876,7 @@ describe('Optimized connector', function() {
});
describe('Unoptimized connector', function() {
var ds = new DataSource({ connector: Memory });
var ds = new DataSource({connector: Memory});
// disable optimized methods
ds.connector.updateOrCreate = false;
@ -891,7 +892,7 @@ 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() {
@ -902,14 +903,14 @@ 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'}]);
});
};
@ -920,15 +921,15 @@ describe('Memory connector with options', function() {
});
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);
@ -936,7 +937,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);
@ -944,16 +945,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);
@ -975,7 +976,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);
@ -997,7 +998,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

@ -2,6 +2,7 @@
// Node module: loopback-datasource-juggler
// This file is licensed under the MIT License.
// License text available at https://opensource.org/licenses/MIT
'use strict';
// This test written in mocha+should.js
var should = require('./init.js');
@ -15,8 +16,8 @@ var modelBuilder = new ModelBuilder();
var mixins = modelBuilder.mixins;
function timestamps(Model, options) {
Model.defineProperty('createdAt', { type: Date });
Model.defineProperty('updatedAt', { type: Date });
Model.defineProperty('createdAt', {type: Date});
Model.defineProperty('updatedAt', {type: Date});
var originalBeforeSave = Model.beforeSave;
Model.beforeSave = function(next, data) {
@ -62,34 +63,34 @@ 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 },
street: {type: 'string', required: true},
city: {type: 'string', required: true},
});
var memory = new DataSource('mem', { connector: Memory }, modelBuilder);
var Item = memory.createModel('Item', { name: 'string' }, {
mixins: { Address: true },
var memory = new DataSource('mem', {connector: Memory}, modelBuilder);
var Item = memory.createModel('Item', {name: 'string'}, {
mixins: {Address: true},
});
var properties = Item.definition.properties;
properties.street.should.eql({ type: String, required: true });
properties.city.should.eql({ type: String, required: true });
properties.street.should.eql({type: String, required: true});
properties.city.should.eql({type: String, required: true});
});
it('should apply mixins', function(done) {
var memory = new DataSource('mem', { connector: Memory }, modelBuilder);
var Item = memory.createModel('Item', { name: 'string' }, {
var memory = new DataSource('mem', {connector: Memory}, modelBuilder);
var Item = memory.createModel('Item', {name: 'string'}, {
mixins: {
TimeStamp: true, Demo: { value: true },
TimeStamp: true, Demo: {value: true},
Multi: [
{ key: 'foo', value: 'bar' },
{ key: 'fox', value: 'baz' },
{key: 'foo', value: 'bar'},
{key: 'fox', value: 'baz'},
],
},
});
Item.mixin('Example', { foo: 'bar' });
Item.mixin('Example', {foo: 'bar'});
Item.demoMixin.should.be.true;
@ -97,13 +98,13 @@ describe('Model class', function() {
Item.multiMixin.fox.should.equal('baz');
var properties = Item.definition.properties;
properties.createdAt.should.eql({ type: Date });
properties.updatedAt.should.eql({ type: Date });
properties.createdAt.should.eql({type: Date});
properties.updatedAt.should.eql({type: Date});
Item.create({ name: 'Item 1' }, function(err, inst) {
Item.create({name: 'Item 1'}, function(err, inst) {
inst.createdAt.should.be.a.date;
inst.updatedAt.should.be.a.date;
inst.example().should.eql({ foo: 'bar' });
inst.example().should.eql({foo: 'bar'});
done();
});
});
@ -113,12 +114,12 @@ describe('Model class', function() {
beforeEach(function() {
Address = modelBuilder.define('Address', {
street: { type: 'string', required: true },
city: { type: 'string', required: true },
street: {type: 'string', required: true},
city: {type: 'string', required: true},
});
var memory = new DataSource('mem', { connector: Memory }, modelBuilder);
Person = memory.createModel('Person', { name: 'string' });
Author = memory.createModel('Author', { name: 'string' });
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() {

View File

@ -2,6 +2,7 @@
// Node module: loopback-datasource-juggler
// This file is licensed under the MIT License.
// License text available at https://opensource.org/licenses/MIT
'use strict';
// This test written in mocha+should.js
var should = require('./init.js');
@ -17,7 +18,7 @@ var ModelDefinition = require('../lib/model-definition');
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) {
@ -66,7 +67,7 @@ describe('ModelDefinition class', function() {
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);
@ -76,7 +77,7 @@ 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();
});
@ -114,10 +115,10 @@ describe('ModelDefinition class', function() {
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' }});
assert.deepEqual(json.properties.address.type, {street: {type: 'String'},
city: {type: 'String'},
zipCode: {type: 'String'},
state: {type: 'String'}});
done();
});
@ -206,7 +207,7 @@ describe('ModelDefinition class', function() {
var modelBuilder = new ModelBuilder();
var User = new ModelDefinition(modelBuilder, 'User', {
userId: { type: String, id: true },
userId: {type: String, id: true},
name: 'string',
bio: ModelBuilder.Text,
approved: Boolean,
@ -223,8 +224,8 @@ describe('ModelDefinition class', function() {
var modelBuilder = new ModelBuilder();
var User = new ModelDefinition(modelBuilder, 'User', {
userId: { type: String, id: 2 },
userType: { type: String, id: 1 },
userId: {type: String, id: 2},
userType: {type: String, id: 1},
name: 'string',
bio: ModelBuilder.Text,
approved: Boolean,
@ -245,9 +246,9 @@ describe('ModelDefinition class', function() {
var modelBuilder = new ModelBuilder();
var User = new ModelDefinition(modelBuilder, 'User', {
userId: { type: String, id: true, oracle: { column: 'ID' }},
userId: {type: String, id: true, oracle: {column: 'ID'}},
name: 'string',
}, { oracle: { table: 'USER' }});
}, {oracle: {table: 'USER'}});
assert.equal(User.tableName('oracle'), 'USER');
assert.equal(User.tableName('mysql'), 'User');
@ -278,7 +279,7 @@ describe('ModelDefinition class', function() {
it('should ignore inherited options.base', function() {
var modelBuilder = memory.modelBuilder;
var base = modelBuilder.define('base');
var child = base.extend('child', {}, { base: 'base' });
var child = base.extend('child', {}, {base: 'base'});
var grandChild = child.extend('grand-child');
assert.equal('child', grandChild.base.modelName);
assert(grandChild.prototype instanceof child);
@ -287,7 +288,7 @@ describe('ModelDefinition class', function() {
it('should ignore inherited options.super', function() {
var modelBuilder = memory.modelBuilder;
var base = modelBuilder.define('base');
var child = base.extend('child', {}, { super: 'base' });
var child = base.extend('child', {}, {super: 'base'});
var grandChild = child.extend('grand-child');
assert.equal('child', grandChild.base.modelName);
assert(grandChild.prototype instanceof child);
@ -310,7 +311,7 @@ describe('ModelDefinition class', function() {
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',
@ -319,7 +320,7 @@ describe('ModelDefinition class', function() {
name: 'child',
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');
@ -350,7 +351,7 @@ describe('ModelDefinition class', function() {
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',
@ -359,7 +360,7 @@ describe('ModelDefinition class', function() {
name: 'child',
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');
@ -374,7 +375,7 @@ describe('ModelDefinition class', function() {
var message = 'deprecation not reported';
process.once('deprecation', function(err) { message = err.message; });
memory.createModel('Dotted', { 'dot.name': String });
memory.createModel('Dotted', {'dot.name': String});
message.should.match(/Dotted.*dot\.name/);
});
@ -384,7 +385,7 @@ describe('ModelDefinition class', function() {
process.once('deprecation', function(err) { message = err.message; });
var Model = memory.createModel('DynamicDotted');
Model.create({ 'dot.name': 'dot.value' }, function(err) {
Model.create({'dot.name': 'dot.value'}, function(err) {
if (err) return done(err);
message.should.match(/Dotted.*dot\.name/);
done();

View File

@ -2,6 +2,7 @@
// Node module: loopback-datasource-juggler
// This file is licensed under the MIT License.
// License text available at https://opensource.org/licenses/MIT
'use strict';
var ValidationError = require('../..').ValidationError;
@ -18,7 +19,7 @@ module.exports = function(dataSource, should, connectorCapabilities) {
beforeEach(function setupHelpers() {
ctxRecorder = new ContextRecorder('hook not called');
hookMonitor = new HookMonitor({ includeModelName: true });
hookMonitor = new HookMonitor({includeModelName: true});
expectedError = new Error('test error');
});
@ -28,9 +29,9 @@ module.exports = function(dataSource, should, connectorCapabilities) {
beforeEach(function setupDatabase() {
Embedded = dataSource.createModel('Embedded', {
// Set id.generated to false to honor client side values
id: { type: String, id: true, generated: false, default: uid.next },
name: { type: String, required: true },
extra: { type: String, required: false },
id: {type: String, id: true, generated: false, default: uid.next},
name: {type: String, required: true},
extra: {type: String, required: false},
});
Owner = dataSource.createModel('Owner', {});
@ -55,7 +56,7 @@ module.exports = function(dataSource, should, connectorCapabilities) {
});
function callCreate() {
var item = new Embedded({ name: 'created' });
var item = new Embedded({name: 'created'});
return ownerInstance.embeddedList.create(item);
}
@ -111,7 +112,7 @@ module.exports = function(dataSource, should, connectorCapabilities) {
// and produces a single "invalid" error only
// Compare this to `embedsOne.create`, which correctly reports
// codes: { name: ['presence'] }
(err.details.codes || {}).should.eql({ embeddeds: ['invalid'] });
(err.details.codes || {}).should.eql({embeddeds: ['invalid']});
});
});

View File

@ -2,6 +2,7 @@
// Node module: loopback-datasource-juggler
// This file is licensed under the MIT License.
// License text available at https://opensource.org/licenses/MIT
'use strict';
var Promise = require('bluebird');
var ValidationError = require('../..').ValidationError;
@ -18,7 +19,7 @@ module.exports = function(dataSource, should, connectorCapabilities) {
var ctxRecorder, hookMonitor, expectedError;
beforeEach(function sharedSetup() {
ctxRecorder = new ContextRecorder('hook not called');
hookMonitor = new HookMonitor({ includeModelName: true });
hookMonitor = new HookMonitor({includeModelName: true});
expectedError = new Error('test error');
});
@ -27,9 +28,9 @@ module.exports = function(dataSource, should, connectorCapabilities) {
beforeEach(function setupDatabase() {
Embedded = dataSource.createModel('Embedded', {
// Set id.generated to false to honor client side values
id: { type: String, id: true, generated: false, default: uid.next },
name: { type: String, required: true },
extra: { type: String, required: false },
id: {type: String, id: true, generated: false, default: uid.next},
name: {type: String, required: true},
extra: {type: String, required: false},
});
Owner = dataSource.createModel('Owner', {});
@ -46,14 +47,14 @@ module.exports = function(dataSource, should, connectorCapabilities) {
}
});
var ownerInstance, existingInstance;
var ownerInstance, existingInstance, existingItem;
beforeEach(function setupData() {
return Owner.create({})
.then(function(inst) {
ownerInstance = inst;
})
.then(function() {
var item = new Embedded({ name: 'created' });
var item = new Embedded({name: 'created'});
return ownerInstance.embeddedList.create(item).then(function(it) {
existingItem = it;
});

View File

@ -2,6 +2,7 @@
// Node module: loopback-datasource-juggler
// This file is licensed under the MIT License.
// License text available at https://opensource.org/licenses/MIT
'use strict';
var Promise = require('bluebird');
var ValidationError = require('../..').ValidationError;
@ -18,7 +19,7 @@ module.exports = function(dataSource, should, connectorCapabilities) {
var ctxRecorder, hookMonitor, expectedError;
beforeEach(function setupHelpers() {
ctxRecorder = new ContextRecorder('hook not called');
hookMonitor = new HookMonitor({ includeModelName: true });
hookMonitor = new HookMonitor({includeModelName: true});
expectedError = new Error('test error');
});
@ -27,9 +28,9 @@ module.exports = function(dataSource, should, connectorCapabilities) {
beforeEach(function setupDatabase() {
Embedded = dataSource.createModel('Embedded', {
// Set id.generated to false to honor client side values
id: { type: String, id: true, generated: false, default: uid.next },
name: { type: String, required: true },
extra: { type: String, required: false },
id: {type: String, id: true, generated: false, default: uid.next},
name: {type: String, required: true},
extra: {type: String, required: false},
});
Owner = dataSource.createModel('Owner', {});
@ -53,7 +54,7 @@ module.exports = function(dataSource, should, connectorCapabilities) {
ownerInstance = inst;
})
.then(function() {
var item = new Embedded({ name: 'created' });
var item = new Embedded({name: 'created'});
return ownerInstance.embeddedList.create(item).then(function(it) {
existingItem = it;
});
@ -68,7 +69,7 @@ module.exports = function(dataSource, should, connectorCapabilities) {
return new Promise(function(resolve, reject) {
ownerInstance.embeddedList.updateById(
existingItem.id,
{ name: 'updated' },
{name: 'updated'},
function(err, result) {
if (err) reject(err);
else resolve(result);
@ -125,7 +126,7 @@ module.exports = function(dataSource, should, connectorCapabilities) {
Embedded.observe('before save', invalidateEmbeddedModel);
return callUpdate().then(throwShouldHaveFailed, function(err) {
err.should.be.instanceOf(ValidationError);
(err.details.codes || {}).should.eql({ name: ['presence'] });
(err.details.codes || {}).should.eql({name: ['presence']});
});
});

View File

@ -2,6 +2,7 @@
// Node module: loopback-datasource-juggler
// This file is licensed under the MIT License.
// License text available at https://opensource.org/licenses/MIT
'use strict';
var ValidationError = require('../..').ValidationError;
@ -18,7 +19,7 @@ module.exports = function(dataSource, should, connectorCapabilities) {
beforeEach(function setupHelpers() {
ctxRecorder = new ContextRecorder('hook not called');
hookMonitor = new HookMonitor({ includeModelName: true });
hookMonitor = new HookMonitor({includeModelName: true});
expectedError = new Error('test error');
});
@ -28,9 +29,9 @@ module.exports = function(dataSource, should, connectorCapabilities) {
beforeEach(function setupDatabase() {
Embedded = dataSource.createModel('Embedded', {
// Set id.generated to false to honor client side values
id: { type: String, id: true, generated: false, default: uid.next },
name: { type: String, required: true },
extra: { type: String, required: false },
id: {type: String, id: true, generated: false, default: uid.next},
name: {type: String, required: true},
extra: {type: String, required: false},
});
Owner = dataSource.createModel('Owner', {});
@ -55,7 +56,7 @@ module.exports = function(dataSource, should, connectorCapabilities) {
});
function callCreate() {
var item = new Embedded({ name: 'created' });
var item = new Embedded({name: 'created'});
return ownerInstance.embeddedItem.create(item);
}
@ -106,7 +107,7 @@ module.exports = function(dataSource, should, connectorCapabilities) {
Embedded.observe('before save', invalidateEmbeddedModel);
return callCreate().then(throwShouldHaveFailed, function(err) {
err.should.be.instanceOf(ValidationError);
(err.details.codes || {}).should.eql({ name: ['presence'] });
(err.details.codes || {}).should.eql({name: ['presence']});
});
});

View File

@ -2,6 +2,7 @@
// Node module: loopback-datasource-juggler
// This file is licensed under the MIT License.
// License text available at https://opensource.org/licenses/MIT
'use strict';
var ValidationError = require('../..').ValidationError;
@ -17,7 +18,7 @@ module.exports = function(dataSource, should, connectorCapabilities) {
var ctxRecorder, hookMonitor, expectedError;
beforeEach(function sharedSetup() {
ctxRecorder = new ContextRecorder('hook not called');
hookMonitor = new HookMonitor({ includeModelName: true });
hookMonitor = new HookMonitor({includeModelName: true});
expectedError = new Error('test error');
});
@ -26,9 +27,9 @@ module.exports = function(dataSource, should, connectorCapabilities) {
beforeEach(function setupDatabase() {
Embedded = dataSource.createModel('Embedded', {
// Set id.generated to false to honor client side values
id: { type: String, id: true, generated: false, default: uid.next },
name: { type: String, required: true },
extra: { type: String, required: false },
id: {type: String, id: true, generated: false, default: uid.next},
name: {type: String, required: true},
extra: {type: String, required: false},
});
Owner = dataSource.createModel('Owner', {});
@ -45,14 +46,14 @@ module.exports = function(dataSource, should, connectorCapabilities) {
}
});
var ownerInstance, existingInstance;
var ownerInstance, existingInstance, existingItem;
beforeEach(function setupData() {
return Owner.create({})
.then(function(inst) {
ownerInstance = inst;
})
.then(function() {
var item = new Embedded({ name: 'created' });
var item = new Embedded({name: 'created'});
return ownerInstance.embeddedItem.create(item).then(function(it) {
existingItem = it;
});

View File

@ -2,6 +2,7 @@
// Node module: loopback-datasource-juggler
// This file is licensed under the MIT License.
// License text available at https://opensource.org/licenses/MIT
'use strict';
var ValidationError = require('../..').ValidationError;
@ -17,7 +18,7 @@ module.exports = function(dataSource, should, connectorCapabilities) {
var ctxRecorder, hookMonitor, expectedError;
beforeEach(function setupHelpers() {
ctxRecorder = new ContextRecorder('hook not called');
hookMonitor = new HookMonitor({ includeModelName: true });
hookMonitor = new HookMonitor({includeModelName: true});
expectedError = new Error('test error');
});
@ -26,9 +27,9 @@ module.exports = function(dataSource, should, connectorCapabilities) {
beforeEach(function setupDatabase() {
Embedded = dataSource.createModel('Embedded', {
// Set id.generated to false to honor client side values
id: { type: String, id: true, generated: false, default: uid.next },
name: { type: String, required: true },
extra: { type: String, required: false },
id: {type: String, id: true, generated: false, default: uid.next},
name: {type: String, required: true},
extra: {type: String, required: false},
});
Owner = dataSource.createModel('Owner', {});
@ -52,7 +53,7 @@ module.exports = function(dataSource, should, connectorCapabilities) {
ownerInstance = inst;
})
.then(function() {
var item = new Embedded({ name: 'created' });
var item = new Embedded({name: 'created'});
return ownerInstance.embeddedItem.create(item).then(function(it) {
existingItem = it;
});
@ -63,7 +64,7 @@ module.exports = function(dataSource, should, connectorCapabilities) {
});
function callUpdate() {
return ownerInstance.embeddedItem.update({ name: 'updated' });
return ownerInstance.embeddedItem.update({name: 'updated'});
}
it('triggers hooks in the correct order', function() {
@ -115,7 +116,7 @@ module.exports = function(dataSource, should, connectorCapabilities) {
Embedded.observe('before save', invalidateEmbeddedModel);
return callUpdate().then(throwShouldHaveFailed, function(err) {
err.should.be.instanceOf(ValidationError);
(err.details.codes || {}).should.eql({ name: ['presence'] });
(err.details.codes || {}).should.eql({name: ['presence']});
});
});

View File

@ -1,3 +1,5 @@
'use strict';
var debug = require('debug')('test');
var fs = require('fs');
var path = require('path');

View File

@ -2,6 +2,7 @@
// Node module: loopback-datasource-juggler
// This file is licensed under the MIT License.
// License text available at https://opensource.org/licenses/MIT
'use strict';
// This test written in mocha+should.js
var async = require('async');
@ -12,25 +13,25 @@ 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() {
before(function(done) {
db = getSchema();
ModelWithForceId = db.createModel(
'ModelWithForceId',
{ name: String },
{ forceId: true });
{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 },
}, { forceId: true, strict: true });
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);
});
@ -54,7 +55,7 @@ describe('optional-validation', function() {
function expectCreateSuccess(data, done) {
if (done === undefined && typeof data === 'function') {
done = data;
data = { name: INITIAL_NAME };
data = {name: INITIAL_NAME};
}
return function(err, instance) {
if (err) return done(err);
@ -71,7 +72,7 @@ describe('optional-validation', function() {
function expectChangeSuccess(data, done) {
if (done === undefined && typeof data === 'function') {
done = data;
data = { name: NEW_NAME };
data = {name: NEW_NAME};
}
return function(err, instance) {
if (err) return done(err);
@ -86,36 +87,36 @@ 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) {
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() {
context('replaceAttributes', function() {
it('should not fail if you do not pass the Primary key in data object',
function(done) {
ModelWithForceId.create({ name: 'foo' }, function(err, created) {
ModelWithForceId.create({name: 'foo'}, function(err, created) {
if (err) return done(err);
created.replaceAttributes({ name: 'bar' }, function(err, data) {
created.replaceAttributes({name: 'bar'}, function(err, data) {
done(err);
});
});
@ -123,9 +124,9 @@ describe('optional-validation', function() {
it('should fail if you pass the Primary key in data object',
function(done) {
ModelWithForceId.create({ name: 'foo' }, function(err, created) {
ModelWithForceId.create({name: 'foo'}, function(err, created) {
if (err) return done(err);
created.replaceAttributes({ name: 'bar', id: 999 },
created.replaceAttributes({name: 'bar', id: 999},
function(err, data) {
should.exist(err);
done();
@ -138,19 +139,19 @@ 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));
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));
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));
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));
User.create(VALID_DATA, {validate: false}, expectCreateSuccess(done));
});
it('should throw on create with invalid data', function(done) {
@ -164,7 +165,7 @@ describe('optional-validation', function() {
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));
User.findOrCreate(getNewWhere(), INVALID_DATA, {validate: true}, expectValidationError(done));
});
it('should NOT throw on findOrCreate with validate:false with invalid ' +
@ -172,17 +173,17 @@ describe('optional-validation', function() {
User.findOrCreate(
getNewWhere(),
INVALID_DATA,
{ validate: false },
{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));
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));
User.findOrCreate(getNewWhere(), VALID_DATA, {validate: false}, expectCreateSuccess(done));
});
it('should throw on findOrCreate with invalid data', function(done) {
@ -199,7 +200,7 @@ describe('optional-validation', function() {
'data', function(done) {
callUpdateOrCreateWithExistingUserId(
null,
{ validate: true },
{validate: true},
expectValidationError(done)
);
});
@ -208,17 +209,17 @@ describe('optional-validation', function() {
'invalid data', function(done) {
callUpdateOrCreateWithExistingUserId(
null,
{ validate: false },
{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));
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));
callUpdateOrCreateWithExistingUserId(NEW_NAME, {validate: false}, expectChangeSuccess(done));
});
// backwards compatible with validateUpsert
@ -234,25 +235,25 @@ describe('optional-validation', function() {
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));
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));
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));
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));
d.save({validate: false}, expectChangeSuccess(done));
});
});
@ -272,25 +273,25 @@ describe('optional-validation', function() {
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));
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));
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));
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));
d.updateAttributes({'name': NEW_NAME}, {validate: false}, expectChangeSuccess(done));
});
});
@ -302,7 +303,7 @@ describe('optional-validation', function() {
it('should NOT throw on updateAttributes(cb) with valid data', function(done) {
createUser(function(err, d) {
d.updateAttributes({ 'name': NEW_NAME }, expectChangeSuccess(done));
d.updateAttributes({'name': NEW_NAME}, expectChangeSuccess(done));
});
});
});
@ -316,19 +317,19 @@ describe('optional-validation', 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));
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));
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));
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));
User.create(VALID_DATA, {validate: false}, expectCreateSuccess(done));
});
it('should NOT throw on create with invalid data', function(done) {
@ -342,24 +343,24 @@ describe('optional-validation', function() {
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));
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 },
{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));
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));
User.findOrCreate(getNewWhere(), VALID_DATA, {validate: false}, expectCreateSuccess(done));
});
it('should NOT throw on findOrCreate with invalid data', function(done) {
@ -380,7 +381,7 @@ describe('optional-validation', function() {
'data', function(done) {
callUpdateOrCreateWithExistingUserId(
null,
{ validate: true },
{validate: true},
expectValidationError(done)
);
});
@ -389,17 +390,17 @@ describe('optional-validation', function() {
'invalid data', function(done) {
callUpdateOrCreateWithExistingUserId(
null,
{ validate: false },
{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));
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));
callUpdateOrCreateWithExistingUserId(NEW_NAME, {validate: false}, expectChangeSuccess(done));
});
it('should NOT throw on updateOrCreate(id) with invalid data', function(done) {
@ -414,25 +415,25 @@ describe('optional-validation', function() {
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));
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));
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));
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));
d.save({validate: false}, expectChangeSuccess(done));
});
});
@ -458,19 +459,19 @@ describe('optional-validation', 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));
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));
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));
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));
User.create(VALID_DATA, {validate: false}, expectCreateSuccess(done));
});
it('should throw on create with invalid data', function(done) {
@ -484,24 +485,24 @@ describe('optional-validation', function() {
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));
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 },
{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));
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));
User.findOrCreate(getNewWhere(), VALID_DATA, {validate: false}, expectCreateSuccess(done));
});
it('should throw on findOrCreate with invalid data', function(done) {
@ -518,7 +519,7 @@ describe('optional-validation', function() {
'data', function(done) {
callUpdateOrCreateWithExistingUserId(
null,
{ validate: true },
{validate: true},
expectValidationError(done)
);
});
@ -527,7 +528,7 @@ describe('optional-validation', function() {
'invalid data', function(done) {
callUpdateOrCreateWithExistingUserId(
null,
{ validate: false },
{validate: false},
expectChangeSuccess(INVALID_DATA, done)
);
});
@ -536,7 +537,7 @@ describe('optional-validation', function() {
'valid data', function(done) {
callUpdateOrCreateWithExistingUserId(
NEW_NAME,
{ validate: true },
{validate: true},
expectChangeSuccess(done)
);
});
@ -545,7 +546,7 @@ describe('optional-validation', function() {
'valid data', function(done) {
callUpdateOrCreateWithExistingUserId(
NEW_NAME,
{ validate: false },
{validate: false},
expectChangeSuccess(done)
);
});
@ -571,19 +572,19 @@ describe('optional-validation', function() {
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));
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));
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));
d.save({validate: false}, expectChangeSuccess(done));
});
});

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@ -2,6 +2,7 @@
// Node module: loopback-datasource-juggler
// This file is licensed under the MIT License.
// License text available at https://opensource.org/licenses/MIT
'use strict';
// This test written in mocha+should.js
var should = require('./init.js');

View File

@ -2,6 +2,7 @@
// Node module: loopback-datasource-juggler
// This file is licensed under the MIT License.
// License text available at https://opensource.org/licenses/MIT
'use strict';
// This test written in mocha+should.js
var should = require('./init.js');
@ -12,7 +13,7 @@ describe('scope', function() {
before(function() {
db = getSchema();
Railway = db.define('Railway', {
URID: { type: String, index: true },
URID: {type: String, index: true},
}, {
scopes: {
highSpeed: {
@ -23,11 +24,11 @@ describe('scope', function() {
},
});
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},
});
});
@ -43,7 +44,7 @@ describe('scope', function() {
});
it('should define scope with query', function(done) {
Station.scope('active', { where: { isActive: true }});
Station.scope('active', {where: {isActive: true}});
Station.scopes.should.have.property('active');
Station.active.create(function(err, station) {
should.not.exist(err);
@ -55,8 +56,8 @@ describe('scope', function() {
});
it('should allow scope chaining', function(done) {
Station.scope('active', { where: { isActive: true }});
Station.scope('subway', { where: { isUndeground: true }});
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);
@ -67,9 +68,9 @@ describe('scope', function() {
});
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.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) {
@ -81,7 +82,7 @@ describe('scope', function() {
});
it('should not cache any results', function(done) {
Station.scope('active', { where: { isActive: true }});
Station.scope('active', {where: {isActive: true}});
Station.active.create(function(err, s) {
if (err) return done(err);
s.isActive.should.be.true;
@ -107,10 +108,10 @@ describe('scope - order', 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) {
@ -118,15 +119,15 @@ describe('scope - order', function() {
});
beforeEach(function(done) {
Station.create({ name: 'a', order: 1 }, done);
Station.create({name: 'a', order: 1}, done);
});
beforeEach(function(done) {
Station.create({ name: 'b', order: 2 }, done);
Station.create({name: 'b', order: 2}, done);
});
beforeEach(function(done) {
Station.create({ name: 'c', order: 3 }, done);
Station.create({name: 'c', order: 3}, done);
});
it('should define scope with default order', function(done) {
@ -142,7 +143,7 @@ describe('scope - order', function() {
});
it('should override default scope order', function(done) {
Station.reverse({ order: 'order ASC' }, function(err, stations) {
Station.reverse({order: 'order ASC'}, function(err, stations) {
stations[0].name.should.equal('a');
stations[0].order.should.equal(1);
stations[1].name.should.equal('b');
@ -160,15 +161,15 @@ describe('scope - filtered count, updateAll and destroyAll', 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) {
@ -176,22 +177,22 @@ describe('scope - filtered count, updateAll and destroyAll', function() {
});
beforeEach(function(done) {
Station.create({ name: 'b', order: 2, active: false }, done);
Station.create({name: 'b', order: 2, active: false}, done);
});
beforeEach(function(done) {
Station.create({ name: 'a', order: 1 }, function(err, inst) {
Station.create({name: 'a', order: 1}, function(err, inst) {
stationA = inst;
done();
});
});
beforeEach(function(done) {
Station.create({ name: 'd', order: 4, active: false }, done);
Station.create({name: 'd', order: 4, active: false}, done);
});
beforeEach(function(done) {
Station.create({ name: 'c', order: 3 }, done);
Station.create({name: 'c', order: 3}, done);
});
it('should find all - verify', function(done) {
@ -215,7 +216,7 @@ describe('scope - filtered count, updateAll and destroyAll', function() {
});
it('should find one - with filter', function(done) {
Station.active.findOne({ where: { name: 'c' }}, function(err, station) {
Station.active.findOne({where: {name: 'c'}}, function(err, station) {
should.not.exist(err);
station.name.should.equal('c');
done();
@ -255,7 +256,7 @@ describe('scope - filtered count, updateAll and destroyAll', function() {
});
it('should count filtered - active', function(done) {
Station.active.count({ order: { gt: 1 }}, function(err, count) {
Station.active.count({order: {gt: 1}}, function(err, count) {
should.not.exist(err);
count.should.equal(1);
done();
@ -263,7 +264,7 @@ describe('scope - filtered count, updateAll and destroyAll', function() {
});
it('should count filtered - inactive', function(done) {
Station.inactive.count({ order: 2 }, function(err, count) {
Station.inactive.count({order: 2}, function(err, count) {
should.not.exist(err);
count.should.equal(1);
done();
@ -271,7 +272,7 @@ describe('scope - filtered count, updateAll and destroyAll', function() {
});
it('should allow updateAll', function(done) {
Station.inactive.updateAll({ flagged: true }, function(err, result) {
Station.inactive.updateAll({flagged: true}, function(err, result) {
should.not.exist(err);
result.count.should.equal(2);
verify();
@ -287,7 +288,7 @@ 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) {
Station.ordered.updateAll({active: true}, {flagged: true}, function(err, result) {
should.not.exist(err);
result.count.should.equal(2);
verify();
@ -303,7 +304,7 @@ describe('scope - filtered count, updateAll and destroyAll', function() {
});
it('should allow filtered destroyAll', function(done) {
Station.ordered.destroyAll({ active: false }, function(err) {
Station.ordered.destroyAll({active: false}, function(err) {
should.not.exist(err);
verify();
});
@ -327,15 +328,15 @@ describe('scope - dynamic target class', 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) {
}, null, {}, {isStatic: false, modelTo: function(receiver) {
return db.models[receiver.modelName];
} });
}});
});
beforeEach(function(done) {
@ -347,27 +348,27 @@ describe('scope - dynamic target class', function() {
});
beforeEach(function(done) {
Collection.create({ name: 'Images', modelName: 'Image' }, done);
Collection.create({name: 'Images', modelName: 'Image'}, done);
});
beforeEach(function(done) {
Collection.create({ name: 'Videos', modelName: 'Video' }, done);
Collection.create({name: 'Videos', modelName: 'Video'}, done);
});
beforeEach(function(done) {
Collection.create({ name: 'Things', modelName: 'Unknown' }, done);
Collection.create({name: 'Things', modelName: 'Unknown'}, done);
});
beforeEach(function(done) {
Image.create({ name: 'Image A' }, done);
Image.create({name: 'Image A'}, done);
});
beforeEach(function(done) {
Video.create({ name: 'Video A' }, done);
Video.create({name: 'Video A'}, done);
});
it('should deduce modelTo at runtime - Image', function(done) {
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) {
@ -381,7 +382,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) {
@ -395,7 +396,7 @@ 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() {
@ -411,16 +412,16 @@ describe('scope - dynamic function', function() {
before(function() {
db = getSchema();
Item = db.define('Item', { title: Number, creator: Number });
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);
Item.create({title: 1, creator: 1}, function() {
Item.create({title: 2, creator: 2}, done);
});
});

View File

@ -2,6 +2,7 @@
// Node module: loopback-datasource-juggler
// This file is licensed under the MIT License.
// License text available at https://opensource.org/licenses/MIT
'use strict';
/* eslint-disable camelcase */

View File

@ -2,6 +2,7 @@
// Node module: loopback-datasource-juggler
// This file is licensed under the MIT License.
// License text available at https://opensource.org/licenses/MIT
'use strict';
var jdb = require('../');
var DataSource = jdb.DataSource;
@ -18,14 +19,14 @@ var getTransientDataSource = function(settings) {
describe('Transient connector', function() {
before(function() {
db = getTransientDataSource();
TransientModel = db.define('TransientModel', {}, { idInjection: false });
TransientModel = db.define('TransientModel', {}, {idInjection: false});
Person = TransientModel.extend('Person', { name: String });
Person = TransientModel.extend('Person', {name: String});
Person.attachTo(db);
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,
});
});
@ -33,9 +34,9 @@ describe('Transient connector', function() {
should.not.exist(Person.definition.properties.id);
should.exist(Person.definition.properties.name);
Person.create({ name: 'Wilma' }, function(err, inst) {
Person.create({name: 'Wilma'}, function(err, inst) {
should.not.exist(err);
inst.toObject().should.eql({ name: 'Wilma' });
inst.toObject().should.eql({name: 'Wilma'});
Person.count(function(err, count) {
should.not.exist(err);
@ -51,7 +52,7 @@ describe('Transient connector', function() {
Widget.definition.properties.id.type.should.equal(String);
Widget.create({ name: 'Thing' }, function(err, inst) {
Widget.create({name: 'Thing'}, function(err, inst) {
should.not.exist(err);
inst.id.should.match(/^[0-9a-fA-F]{24}$/);
inst.name.should.equal('Thing');
@ -70,7 +71,7 @@ describe('Transient connector', function() {
Item.definition.properties.id.type.should.equal(Number);
Item.create({ name: 'Example' }, function(err, inst) {
Item.create({name: 'Example'}, function(err, inst) {
should.not.exist(err);
inst.name.should.equal('Example');

View File

@ -2,6 +2,7 @@
// Node module: loopback-datasource-juggler
// This file is licensed under the MIT License.
// License text available at https://opensource.org/licenses/MIT
'use strict';
var should = require('./init.js');
var utils = require('../lib/utils');
@ -29,10 +30,10 @@ describe('util.fieldsToArray', function() {
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() {
@ -41,23 +42,23 @@ describe('util.fieldsToArray', function() {
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 }});
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);
@ -66,14 +67,14 @@ 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 }};
var q6 = {where: {x: 1, y: undefined}};
(function() { removeUndefined(q6, 'throw'); }).should.throw(/`undefined` in query/);
});
});
@ -138,71 +139,71 @@ describe('util.parseSettings', 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' }},
var src = {base: 'User',
relations: {accessTokens: {model: 'accessToken', type: 'hasMany',
foreignKey: 'userId'},
account: {model: 'account', type: 'belongsTo'}},
acls: [
{ accessType: '*',
{accessType: '*',
permission: 'DENY',
principalType: 'ROLE',
principalId: '$everyone' },
{ accessType: '*',
principalId: '$everyone'},
{accessType: '*',
permission: 'ALLOW',
principalType: 'ROLE',
property: 'login',
principalId: '$everyone' },
{ permission: 'ALLOW',
principalId: '$everyone'},
{permission: 'ALLOW',
property: 'findById',
principalType: 'ROLE',
principalId: '$owner' },
] };
var tgt = { strict: false,
principalId: '$owner'},
]};
var tgt = {strict: false,
acls: [
{ principalType: 'ROLE',
{principalType: 'ROLE',
principalId: '$everyone',
permission: 'ALLOW',
property: 'create' },
{ principalType: 'ROLE',
property: 'create'},
{principalType: 'ROLE',
principalId: '$owner',
permission: 'ALLOW',
property: 'removeById' },
property: 'removeById'},
],
maxTTL: 31556926,
ttl: 1209600 };
ttl: 1209600};
var dst = mergeSettings(tgt, src);
var expected = { strict: false,
var expected = {strict: false,
acls: [
{ principalType: 'ROLE',
{principalType: 'ROLE',
principalId: '$everyone',
permission: 'ALLOW',
property: 'create' },
{ principalType: 'ROLE',
property: 'create'},
{principalType: 'ROLE',
principalId: '$owner',
permission: 'ALLOW',
property: 'removeById' },
{ accessType: '*',
property: 'removeById'},
{accessType: '*',
permission: 'DENY',
principalType: 'ROLE',
principalId: '$everyone' },
{ accessType: '*',
principalId: '$everyone'},
{accessType: '*',
permission: 'ALLOW',
principalType: 'ROLE',
property: 'login',
principalId: '$everyone' },
{ permission: 'ALLOW',
principalId: '$everyone'},
{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' }}};
relations: {accessTokens: {model: 'accessToken', type: 'hasMany',
foreignKey: 'userId'},
account: {model: 'account', type: 'belongsTo'}}};
should.deepEqual(dst.acls, expected.acls, 'Merged settings should match the expectation');
});
@ -210,12 +211,12 @@ describe('mergeSettings', function() {
describe('sortObjectsByIds', function() {
var items = [
{ id: 1, name: 'a' },
{ id: 2, name: 'b' },
{ id: 3, name: 'c' },
{ id: 4, name: 'd' },
{ id: 5, name: 'e' },
{ id: 6, name: 'f' },
{id: 1, name: 'a'},
{id: 2, name: 'b'},
{id: 3, name: 'c'},
{id: 4, name: 'd'},
{id: 5, name: 'e'},
{id: 6, name: 'f'},
];
it('should sort', function() {
@ -248,8 +249,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);
});
@ -258,18 +259,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);
});
@ -278,37 +279,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);
});
@ -316,9 +317,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);
});
@ -327,10 +328,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);
});
@ -341,39 +342,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);
});
});

View File

@ -2,6 +2,7 @@
// Node module: loopback-datasource-juggler
// This file is licensed under the MIT License.
// License text available at https://opensource.org/licenses/MIT
'use strict';
// This test written in mocha+should.js
var should = require('./init.js');
@ -41,8 +42,8 @@ describe('validations', function() {
updatedAt: Date,
});
Entry = db.define('Entry', {
id: { type: 'string', id: true, generated: false },
name: { type: 'string' },
id: {type: 'string', id: true, generated: false},
name: {type: 'string'},
});
Entry.validatesUniquenessOf('id');
db.automigrate(done);
@ -62,7 +63,7 @@ describe('validations', function() {
describe('commons', function() {
describe('skipping', function() {
it('should NOT skip when `if` is fulfilled', function() {
User.validatesPresenceOf('pendingPeriod', { if: 'createdByAdmin' });
User.validatesPresenceOf('pendingPeriod', {if: 'createdByAdmin'});
var user = new User;
user.createdByAdmin = true;
user.isValid().should.be.false;
@ -72,7 +73,7 @@ describe('validations', function() {
});
it('should skip when `if` is NOT fulfilled', function() {
User.validatesPresenceOf('pendingPeriod', { if: 'createdByAdmin' });
User.validatesPresenceOf('pendingPeriod', {if: 'createdByAdmin'});
var user = new User;
user.createdByAdmin = false;
user.isValid().should.be.true;
@ -82,7 +83,7 @@ describe('validations', function() {
});
it('should NOT skip when `unless` is fulfilled', function() {
User.validatesPresenceOf('pendingPeriod', { unless: 'createdByAdmin' });
User.validatesPresenceOf('pendingPeriod', {unless: 'createdByAdmin'});
var user = new User;
user.createdByAdmin = false;
user.isValid().should.be.false;
@ -92,7 +93,7 @@ describe('validations', function() {
});
it('should skip when `unless` is NOT fulfilled', function() {
User.validatesPresenceOf('pendingPeriod', { unless: 'createdByAdmin' });
User.validatesPresenceOf('pendingPeriod', {unless: 'createdByAdmin'});
var user = new User;
user.createdByAdmin = true;
user.isValid().should.be.true;
@ -107,7 +108,7 @@ describe('validations', function() {
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) {
@ -121,7 +122,7 @@ describe('validations', function() {
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) {
@ -135,7 +136,7 @@ describe('validations', function() {
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) {
@ -149,7 +150,7 @@ describe('validations', function() {
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) {
@ -166,7 +167,7 @@ describe('validations', function() {
User.validatesPresenceOf('name');
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();
});
@ -176,7 +177,7 @@ describe('validations', function() {
it('should work on update', function(done) {
delete User.validations;
User.validatesPresenceOf('name');
User.create({ name: 'Valid' }, function(e, d) {
User.create({name: 'Valid'}, function(e, d) {
d.updateAttribute('name', null, function(e) {
should.exist(e);
e.should.be.instanceOf(Error);
@ -194,7 +195,7 @@ describe('validations', function() {
User.validatesPresenceOf('name');
// It's important to pass an id value, otherwise DAO falls back
// to regular create()
User.updateOrCreate({ id: 999 }, done);
User.updateOrCreate({id: 999}, done);
});
it('should be skipped by upsert when disabled via settings', function(done) {
@ -208,7 +209,7 @@ describe('validations', function() {
Customer.settings.validateUpsert = false;
// It's important to pass an id value, otherwise DAO falls back
// to regular create()
Customer.updateOrCreate({ id: 999 }, done);
Customer.updateOrCreate({id: 999}, done);
});
});
@ -218,7 +219,7 @@ describe('validations', function() {
User.settings.validateUpsert = true;
// It's important to pass an id value, otherwise DAO falls back
// to regular create()
User.upsert({ id: 999 }, function(err, u) {
User.upsert({id: 999}, function(err, u) {
if (!err) return done(new Error('Validation should have failed.'));
err.should.be.instanceOf(ValidationError);
done();
@ -273,7 +274,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;
@ -286,12 +287,12 @@ describe('validations', function() {
it('should work on update with options', function(done) {
delete User.validations;
User.validatesPresenceOf('name');
User.create({ name: 'Valid' }, function(e, d) {
d.updateAttribute('name', null, { options: 'options' }, function(e) {
User.create({name: 'Valid'}, function(e, d) {
d.updateAttribute('name', null, {options: 'options'}, function(e) {
should.exist(e);
e.should.be.instanceOf(Error);
e.should.be.instanceOf(ValidationError);
d.updateAttribute('name', 'Vasiliy', { options: 'options' }, function(e) {
d.updateAttribute('name', 'Vasiliy', {options: 'options'}, function(e) {
should.not.exist(e);
done();
});
@ -302,7 +303,7 @@ describe('validations', function() {
it('should work on update without options', function(done) {
delete User.validations;
User.validatesPresenceOf('name');
User.create({ name: 'Valid' }, function(e, d) {
User.create({name: 'Valid'}, function(e, d) {
d.updateAttribute('name', null, function(e) {
should.exist(e);
e.should.be.instanceOf(Error);
@ -320,7 +321,7 @@ describe('validations', function() {
User.validatesPresenceOf('name');
User.create(function(e, u) {
should.exist(e);
User.create({ name: 'Valid' }, { options: 'options' }, function(e, d) {
User.create({name: 'Valid'}, {options: 'options'}, function(e, d) {
should.not.exist(e);
done();
});
@ -332,7 +333,7 @@ describe('validations', function() {
User.validatesPresenceOf('name');
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();
});
@ -345,8 +346,8 @@ describe('validations', 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;
@ -375,7 +376,7 @@ describe('validations', function() {
});
it('should skip validation by property (if/unless)', function() {
User.validatesPresenceOf('domain', { unless: 'createdByScript' });
User.validatesPresenceOf('domain', {unless: 'createdByScript'});
var user = new User(getValidAttributes());
user.isValid().should.be.true;
@ -391,12 +392,12 @@ describe('validations', function() {
describe('absence', function() {
it('should validate absence', function() {
User.validatesAbsenceOf('reserved', { if: 'locked' });
var u = new User({ reserved: 'foo', locked: true });
User.validatesAbsenceOf('reserved', {if: 'locked'});
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;
});
});
@ -404,11 +405,11 @@ describe('validations', function() {
describe('uniqueness', function() {
it('should validate uniqueness', function(done) {
User.validatesUniquenessOf('email');
var u = new User({ email: 'hey' });
var u = new User({email: 'hey'});
Boolean(u.isValid(function(valid) {
valid.should.be.true;
u.save(function() {
var u2 = new User({ email: 'hey' });
var u2 = new User({email: 'hey'});
u2.isValid(function(valid) {
valid.should.be.false;
done();
@ -419,7 +420,7 @@ describe('validations', function() {
it('should handle same object modification', function(done) {
User.validatesUniquenessOf('email');
var u = new User({ email: 'hey' });
var u = new User({email: 'hey'});
Boolean(u.isValid(function(valid) {
valid.should.be.true;
u.save(function() {
@ -439,23 +440,23 @@ describe('validations', function() {
siteId: String,
email: String,
});
SiteUser.validatesUniquenessOf('email', { scopedTo: ['siteId'] });
SiteUser.validatesUniquenessOf('email', {scopedTo: ['siteId']});
async.waterfall([
function automigrate(next) {
db.automigrate(next);
},
function createSite1User(next) {
SiteUser.create(
{ siteId: 1, email: EMAIL },
{siteId: 1, email: EMAIL},
next);
},
function createSite2User(user1, next) {
SiteUser.create(
{ siteId: 2, email: EMAIL },
{siteId: 2, email: EMAIL},
next);
},
function validateDuplicateUser(user2, next) {
var user3 = new SiteUser({ siteId: 1, email: EMAIL });
var user3 = new SiteUser({siteId: 1, email: EMAIL});
user3.isValid(function(valid) {
valid.should.be.false;
next();
@ -471,11 +472,11 @@ describe('validations', function() {
it('should skip blank values', function(done) {
User.validatesUniquenessOf('email');
var u = new User({ email: ' ' });
var u = new User({email: ' '});
Boolean(u.isValid(function(valid) {
valid.should.be.true;
u.save(function() {
var u2 = new User({ email: null });
var u2 = new User({email: null});
u2.isValid(function(valid) {
valid.should.be.true;
done();
@ -489,7 +490,7 @@ describe('validations', function() {
if: function() { return true; },
unless: function() { return false; },
});
var u = new User({ email: 'hello' });
var u = new User({email: 'hello'});
Boolean(u.isValid(function(valid) {
valid.should.be.true;
done();
@ -497,8 +498,8 @@ describe('validations', function() {
});
it('should work with id property on create', function(done) {
Entry.create({ id: 'entry' }, function(err, entry) {
var e = new Entry({ id: 'entry' });
Entry.create({id: 'entry'}, function(err, entry) {
var e = new Entry({id: 'entry'});
Boolean(e.isValid(function(valid) {
valid.should.be.false;
done();
@ -521,26 +522,26 @@ describe('validations', function() {
it('should overwrite default blank message with custom format message');
it('should skip missing values when allowing null', function() {
User.validatesFormatOf('email', { with: /^\S+@\S+\.\S+$/, allowNull: true });
User.validatesFormatOf('email', {with: /^\S+@\S+\.\S+$/, allowNull: true});
var u = new User({});
u.isValid().should.be.true;
});
it('should skip null values when allowing null', function() {
User.validatesFormatOf('email', { with: /^\S+@\S+\.\S+$/, allowNull: true });
var u = new User({ email: null });
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() {
User.validatesFormatOf('email', { with: /^\S+@\S+\.\S+$/ });
User.validatesFormatOf('email', {with: /^\S+@\S+\.\S+$/});
var u = new User({});
u.isValid().should.be.false;
});
it('should not skip null values', function() {
User.validatesFormatOf('email', { with: /^\S+@\S+\.\S+$/ });
var u = new User({ email: null });
User.validatesFormatOf('email', {with: /^\S+@\S+\.\S+$/});
var u = new User({email: null});
u.isValid().should.be.false;
});
});
@ -565,10 +566,10 @@ describe('validations', function() {
it('should validate using custom sync validation', function() {
User.validate('email', function(err) {
if (this.email === 'hello') err();
}, { code: 'invalid-email' });
var u = new User({ email: 'hello' });
}, {code: 'invalid-email'});
var u = new User({email: 'hello'});
Boolean(u.isValid()).should.be.false;
u.errors.codes.should.eql({ email: ['invalid-email'] });
u.errors.codes.should.eql({email: ['invalid-email']});
});
it('should validate and return detailed error messages', function() {
@ -578,10 +579,10 @@ describe('validations', function() {
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'] });
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) {
@ -591,7 +592,7 @@ describe('validations', function() {
if: function() { return true; },
unless: function() { return false; },
});
var u = new User({ email: 'hello' });
var u = new User({email: 'hello'});
Boolean(u.isValid(function(valid) {
valid.should.be.true;
done();
@ -618,26 +619,26 @@ describe('validations', function() {
it('should truncate long objects', function() {
ValidationError.maxPropertyStringLength = 12;
var err = givenValidationError('prop', { foo: 'bar' }, 'is invalid');
var err = givenValidationError('prop', {foo: 'bar'}, 'is invalid');
getErrorDetails(err)
.should.equal('`prop` is invalid (value: { foo:... }).');
});
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...} ]).');
});
it('should print only top-level object properties', function() {
var err = givenValidationError('prop', { a: { b: 'c' }}, 'is invalid');
var err = givenValidationError('prop', {a: {b: 'c'}}, 'is invalid');
getErrorDetails(err)
.should.equal('`prop` is invalid (value: { a: [Object] }).');
});
it('should print only top-level props of objects in array', function() {
var err = givenValidationError('prop', [{ a: { b: 'c' }}], 'is invalid');
var err = givenValidationError('prop', [{a: {b: 'c'}}], 'is invalid');
getErrorDetails(err)
.should.equal('`prop` is invalid (value: [ { a: [Object] } ]).');
});