diff --git a/.eslintrc b/.eslintrc index 9cafbbd9..d6864ff9 100644 --- a/.eslintrc +++ b/.eslintrc @@ -8,6 +8,8 @@ }], // NOTE(bajtos) we should eventually remove this override // and fix all of those 100+ violations - "one-var": "off" + "one-var": "off", + "no-unused-expressions": "off", + "strict": ["warn", "global"] } } diff --git a/examples/app-noschema.js b/examples/app-noschema.js index 95ce3c98..e1027d90 100644 --- a/examples/app-noschema.js +++ b/examples/app-noschema.js @@ -3,6 +3,8 @@ // 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; var introspectType = require('../lib/introspection')(ModelBuilder); @@ -10,14 +12,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 +35,7 @@ var application = { 'interval': 300, }, }}, - ] }; + ]}; console.log(new Application(application).toObject()); @@ -59,8 +61,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 +71,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); diff --git a/examples/app.js b/examples/app.js index 67ecfd22..ef6bb722 100644 --- a/examples/app.js +++ b/examples/app.js @@ -3,17 +3,19 @@ // 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 +27,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); diff --git a/examples/datasource-app.js b/examples/datasource-app.js index fe9e656e..cf976de6 100644 --- a/examples/datasource-app.js +++ b/examples/datasource-app.js @@ -3,19 +3,21 @@ // 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; 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 +29,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 +58,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 +114,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); diff --git a/examples/inclusion.js b/examples/inclusion.js index 5f4a49d7..acd149bc 100644 --- a/examples/inclusion.js +++ b/examples/inclusion.js @@ -3,37 +3,39 @@ // This file is licensed under the MIT License. // License text available at https://opensource.org/licenses/MIT +'use strict'; + var jdb = require('../index'); 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 +50,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 +64,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 +81,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 +96,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; diff --git a/examples/load-schemas.js b/examples/load-schemas.js index 2359b00c..94be345f 100644 --- a/examples/load-schemas.js +++ b/examples/load-schemas.js @@ -3,6 +3,8 @@ // 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'), DataSource = require('../lib/datasource').DataSource; diff --git a/examples/nesting-schema.js b/examples/nesting-schema.js index c1502fc8..db99a503 100644 --- a/examples/nesting-schema.js +++ b/examples/nesting-schema.js @@ -3,6 +3,8 @@ // 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(); @@ -32,9 +34,9 @@ var User = modelBuilder.define('User', { var user = new User({ name: 'Joe', age: 20, - address: { street: '123 Main St', 'city': 'San Jose', state: 'CA' }, + address: {street: '123 Main St', 'city': 'San Jose', state: 'CA'}, emails: [ - { label: 'work', email: 'xyz@sample.com' }, + {label: 'work', email: 'xyz@sample.com'}, ], friends: ['John', 'Mary'], }); diff --git a/examples/relations.js b/examples/relations.js index b82fa8b2..f3c68cbd 100644 --- a/examples/relations.js +++ b/examples/relations.js @@ -3,6 +3,8 @@ // 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 +22,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,29 +84,29 @@ 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, patientId: patient1.id }, + {appointmentDate: new Date(), physicianId: physician1.id, patientId: patient1.id}, function(err, appt1) { Appointment.create( - { appointmentDate: new Date(), physicianId: physician1.id, patientId: patient2.id }, + {appointmentDate: new Date(), physicianId: physician1.id, patientId: patient2.id}, function(err, appt2) { physician1.patients(console.log); - physician1.patients({ where: { name: 'Mary' }}, console.log); + physician1.patients({where: {name: 'Mary'}}, console.log); patient1.physicians(console.log); // Build an appointment? - var patient3 = patient1.physicians.build({ name: 'Dr X' }); + var patient3 = patient1.physicians.build({name: 'Dr X'}); console.log('Physician 3: ', patient3, patient3.constructor.modelName); // Create a physician? - patient1.physicians.create({ name: 'Dr X' }, function(err, patient4) { + patient1.physicians.create({name: 'Dr X'}, function(err, patient4) { console.log('Physician 4: ', patient4, patient4.constructor.modelName); }); }); @@ -125,22 +127,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); }); }); diff --git a/index.js b/index.js index bdb84fb0..18e9e292 100644 --- a/index.js +++ b/index.js @@ -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); diff --git a/lib/browser.depd.js b/lib/browser.depd.js index 6148c600..b8c29967 100644 --- a/lib/browser.depd.js +++ b/lib/browser.depd.js @@ -3,6 +3,8 @@ // 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) { var warned = {}; diff --git a/lib/connectors/memory.js b/lib/connectors/memory.js index a4b85f1a..87102e3d 100644 --- a/lib/connectors/memory.js +++ b/lib/connectors/memory.js @@ -3,6 +3,8 @@ // 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'); var Connector = require('loopback-connector').Connector; @@ -107,7 +109,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 +243,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 +258,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 +325,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 +344,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 +414,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 +487,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 +509,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 +524,7 @@ function applyFilter(filter) { var dotIndex = key.indexOf('.'); var subValue = obj[key.substring(0, dotIndex)]; if (dotIndex !== -1 && Array.isArray(subValue)) { - var subFilter = { where: {}}; + var subFilter = {where: {}}; var subKey = key.substring(dotIndex + 1); subFilter.where[subKey] = where[key]; return subValue.some(applyFilter(subFilter)); @@ -606,8 +608,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) { @@ -684,7 +686,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++; @@ -695,14 +697,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)); @@ -719,7 +721,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; @@ -736,7 +738,7 @@ Memory.prototype.update = } }, function(err) { if (err) return cb(err); - self.saveToFile({ count: count }, cb); + self.saveToFile({count: count}, cb); }); }; @@ -800,7 +802,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]; @@ -812,14 +814,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}); }); }; diff --git a/lib/connectors/transient.js b/lib/connectors/transient.js index af615a65..29afc39d 100644 --- a/lib/connectors/transient.js +++ b/lib/connectors/transient.js @@ -3,6 +3,8 @@ // 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'); var Connector = require('loopback-connector').Connector; @@ -104,7 +106,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) { diff --git a/lib/dao.js b/lib/dao.js index 74603b4a..f46cd227 100644 --- a/lib/dao.js +++ b/lib/dao.js @@ -107,7 +107,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 +252,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) { @@ -508,7 +508,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); @@ -581,7 +581,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; @@ -605,11 +605,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); } @@ -674,7 +674,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, @@ -699,7 +699,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); @@ -753,7 +753,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; @@ -772,11 +772,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) { @@ -926,7 +926,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; @@ -951,11 +951,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 @@ -1000,14 +1000,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') { @@ -1018,7 +1018,7 @@ DataAccessObject.findOrCreate = function findOrCreate(query, data, options, cb) } cb = cb || utils.createPromiseCallback(); - query = query || { where: {}}; + query = query || {where: {}}; data = data || {}; options = options || {}; @@ -1049,8 +1049,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) { @@ -1336,9 +1336,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 @@ -2059,7 +2059,7 @@ DataAccessObject.destroyAll = function destroyAll(where, options, cb) { var hookState = {}; - var query = { where: where }; + var query = {where: where}; this.applyScope(query); where = query.where; @@ -2073,7 +2073,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, @@ -2256,7 +2256,7 @@ DataAccessObject.count = function(where, options, cb) { var hookState = {}; - var query = { where: where }; + var query = {where: where}; this.applyScope(query); where = query.where; @@ -2272,7 +2272,7 @@ DataAccessObject.count = function(where, options, cb) { var context = { Model: Model, - query: { where: where }, + query: {where: where}, hookState: hookState, options: options, }; @@ -2394,7 +2394,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, @@ -2502,7 +2502,7 @@ DataAccessObject.updateAll = function(where, data, options, cb) { var hookState = {}; - var query = { where: where }; + var query = {where: where}; this.applyScope(query); this.applyProperties(data); @@ -2510,7 +2510,7 @@ DataAccessObject.updateAll = function(where, data, options, cb) { var context = { Model: Model, - query: { where: where }, + query: {where: where}, hookState: hookState, options: options, }; @@ -2653,7 +2653,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) { @@ -2817,7 +2817,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); diff --git a/lib/datasource.js b/lib/datasource.js index c83a4549..53a882b8 100644 --- a/lib/datasource.js +++ b/lib/datasource.js @@ -3,6 +3,8 @@ // This file is licensed under the MIT License. // License text available at https://opensource.org/licenses/MIT +'use strict'; + /*! * Module dependencies */ @@ -520,7 +522,7 @@ DataSource.prototype.setupDataAccess = function(modelClass, settings) { forceId = true; } if (forceId) { - modelClass.validatesAbsenceOf(idName, { if: 'isNewRecord' }); + modelClass.validatesAbsenceOf(idName, {if: 'isNewRecord'}); } } if (this.connector.define) { @@ -652,7 +654,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) { @@ -1424,7 +1426,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}; } }); } @@ -1575,7 +1577,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}; } }); } @@ -1833,7 +1835,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] = {}; diff --git a/lib/geo.js b/lib/geo.js index 8de8f6eb..022b4942 100644 --- a/lib/geo.js +++ b/lib/geo.js @@ -3,6 +3,8 @@ // 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 +59,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 diff --git a/lib/hooks.js b/lib/hooks.js index 1d809870..f3c45550 100644 --- a/lib/hooks.js +++ b/lib/hooks.js @@ -3,6 +3,8 @@ // 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')(); diff --git a/lib/include.js b/lib/include.js index 332c3863..d36d4976 100644 --- a/lib/include.js +++ b/lib/include.js @@ -3,6 +3,8 @@ // 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')(); var utils = require('./utils'); @@ -328,7 +330,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 || {}; @@ -736,7 +738,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] = { @@ -1012,7 +1014,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 { diff --git a/lib/include_utils.js b/lib/include_utils.js index 2a65cacf..536e6258 100644 --- a/lib/include_utils.js +++ b/lib/include_utils.js @@ -3,6 +3,8 @@ // 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; module.exports.join = join; diff --git a/lib/introspection.js b/lib/introspection.js index ce1a9c82..305f8f1d 100644 --- a/lib/introspection.js +++ b/lib/introspection.js @@ -3,6 +3,8 @@ // 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) { // Unknown type, using Any diff --git a/lib/jutil.js b/lib/jutil.js index 128d6d16..a2650dbc 100644 --- a/lib/jutil.js +++ b/lib/jutil.js @@ -3,6 +3,8 @@ // This file is licensed under the MIT License. // License text available at https://opensource.org/licenses/MIT +'use strict'; + var util = require('util'); /** diff --git a/lib/kvao/set.js b/lib/kvao/set.js index 66311eb6..c3118059 100644 --- a/lib/kvao/set.js +++ b/lib/kvao/set.js @@ -18,7 +18,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 = {}; } diff --git a/lib/list.js b/lib/list.js index 9800a319..1851bb4a 100644 --- a/lib/list.js +++ b/lib/list.js @@ -3,6 +3,8 @@ // 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'); var Any = require('./types').Types.Any; diff --git a/lib/mixins.js b/lib/mixins.js index 3259ccb6..9cff802a 100644 --- a/lib/mixins.js +++ b/lib/mixins.js @@ -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'); diff --git a/lib/model-builder.js b/lib/model-builder.js index 677de9ab..218dad7c 100644 --- a/lib/model-builder.js +++ b/lib/model-builder.js @@ -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; }; @@ -203,7 +204,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; } @@ -216,7 +217,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', {}); @@ -283,7 +284,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 @@ -689,7 +690,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') { @@ -736,7 +737,7 @@ ModelBuilder.prototype.buildModels = function(schemas, createModel) { { name: this.getSchemaName(), properties: schemas, - options: { anonymous: true }, + options: {anonymous: true}, }, ]; } @@ -763,7 +764,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}); } } } diff --git a/lib/model-definition.js b/lib/model-definition.js index 6481f540..280caa54 100644 --- a/lib/model-definition.js +++ b/lib/model-definition.js @@ -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; diff --git a/lib/model.js b/lib/model.js index 678fc2e1..d1e6b440 100644 --- a/lib/model.js +++ b/lib/model.js @@ -201,7 +201,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); } diff --git a/lib/observer.js b/lib/observer.js index f2046eb4..3e493e28 100644 --- a/lib/observer.js +++ b/lib/observer.js @@ -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'); diff --git a/lib/relation-definition.js b/lib/relation-definition.js index 00f5f3bd..4d1f1769 100644 --- a/lib/relation-definition.js +++ b/lib/relation-definition.js @@ -556,7 +556,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 +608,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}); } } @@ -1023,7 +1023,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); @@ -1088,7 +1088,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); @@ -1134,7 +1134,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); @@ -1172,7 +1172,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); @@ -1237,12 +1237,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); @@ -1459,7 +1459,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) { @@ -1557,7 +1557,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; @@ -1570,7 +1570,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); @@ -1611,7 +1611,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}); } } @@ -1703,7 +1703,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); @@ -1880,7 +1880,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) { @@ -1965,7 +1965,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(); }; @@ -2392,7 +2392,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 @@ -2750,7 +2750,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 { @@ -2941,7 +2941,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); @@ -2988,7 +2988,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); @@ -3045,7 +3045,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'), @@ -3349,7 +3349,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); diff --git a/lib/relations.js b/lib/relations.js index b4a2c8b5..c7145c1a 100644 --- a/lib/relations.js +++ b/lib/relations.js @@ -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 diff --git a/lib/scope.js b/lib/scope.js index 2fcb3880..f5ca6e34 100644 --- a/lib/scope.js +++ b/lib/scope.js @@ -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 i8n = require('inflection'); var utils = require('./utils'); @@ -83,7 +84,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) { @@ -369,7 +370,7 @@ function defineScope(cls, targetClass, name, params, methods, options) { var targetModel = definition.targetModel(this._receiver); var scoped = (this._scope && this._scope.where) || {}; - var filter = mergeQuery({ where: scoped }, { where: where || {}}); + var filter = mergeQuery({where: scoped}, {where: where || {}}); return targetModel.destroyAll(filter.where, options, cb); } @@ -389,7 +390,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); } @@ -417,7 +418,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); @@ -437,7 +438,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); } @@ -455,7 +456,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); } diff --git a/lib/transaction.js b/lib/transaction.js index db8312f9..97e535d0 100644 --- a/lib/transaction.js +++ b/lib/transaction.js @@ -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'); diff --git a/lib/types.js b/lib/types.js index c0829a5d..12140386 100644 --- a/lib/types.js +++ b/lib/types.js @@ -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 = {}; /** diff --git a/lib/utils.js b/lib/utils.js index 1d285be2..0c774bd8 100644 --- a/lib/utils.js +++ b/lib/utils.js @@ -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; @@ -163,7 +164,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; } diff --git a/lib/validations.js b/lib/validations.js index 4dadc7c1..4397743b 100644 --- a/lib/validations.js +++ b/lib/validations.js @@ -3,6 +3,8 @@ // 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'); var extend = util._extend; @@ -208,7 +210,7 @@ Validatable.validate = getConfigurator('custom'); * @options {Object} Options See below * @property {String} message Optional error message if property is not valid. Default error message: " is invalid". */ -Validatable.validateAsync = getConfigurator('custom', { async: true }); +Validatable.validateAsync = getConfigurator('custom', {async: true}); /** * Validate uniqueness. Ensure the value for property is unique in the collection of models. @@ -232,7 +234,7 @@ Validatable.validateAsync = getConfigurator('custom', { async: true }); * @property {Array.} scopedTo List of properties defining the scope. * @property {String} message Optional error message if property is not valid. Default error message: "is not unique". */ -Validatable.validatesUniquenessOf = getConfigurator('uniqueness', { async: true }); +Validatable.validatesUniquenessOf = getConfigurator('uniqueness', {async: true}); // implementation of validators @@ -345,7 +347,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) { diff --git a/package.json b/package.json index bed298af..dedff094 100644 --- a/package.json +++ b/package.json @@ -33,8 +33,8 @@ ], "devDependencies": { "async-iterators": "^0.2.2", - "eslint": "^2.5.3", - "eslint-config-loopback": "^2.0.0", + "eslint": "^2.13.1", + "eslint-config-loopback": "^4.0.0", "mocha": "^2.1.0", "should": "^8.0.2" }, diff --git a/support/describe-operation-hooks.js b/support/describe-operation-hooks.js index 5f398d7c..20aa8119 100644 --- a/support/describe-operation-hooks.js +++ b/support/describe-operation-hooks.js @@ -3,6 +3,8 @@ // This file is licensed under the MIT License. // License text available at https://opensource.org/licenses/MIT +'use strict'; + /* * Describe context objects of operation hooks in comprehensive HTML table. * Usage: @@ -35,55 +37,55 @@ Promise.onPossiblyUnhandledRejection(function(err) { /* eslint-disable camelcase */ var operations = [ function find(ds) { - return ds.TestModel.find({ where: { id: '1' }}); + return ds.TestModel.find({where: {id: '1'}}); }, function count(ds) { - return ds.TestModel.count({ id: ds.existingInstance.id }); + return ds.TestModel.count({id: ds.existingInstance.id}); }, function create(ds) { - return ds.TestModel.create({ name: 'created' }); + return ds.TestModel.create({name: 'created'}); }, function findOrCreate_found(ds) { return ds.TestModel.findOrCreate( - { where: { name: ds.existingInstance.name }}, - { name: ds.existingInstance.name }); + {where: {name: ds.existingInstance.name}}, + {name: ds.existingInstance.name}); }, function findOrCreate_create(ds) { return ds.TestModel.findOrCreate( - { where: { name: 'new-record' }}, - { name: 'new-record' }); + {where: {name: 'new-record'}}, + {name: 'new-record'}); }, function updateOrCreate_create(ds) { - return ds.TestModel.updateOrCreate({ id: 'not-found', name: 'not found' }); + return ds.TestModel.updateOrCreate({id: 'not-found', name: 'not found'}); }, function updateOrCreate_update(ds) { return ds.TestModel.updateOrCreate( - { id: ds.existingInstance.id, name: 'new name' }); + {id: ds.existingInstance.id, name: 'new name'}); }, function replaceOrCreate_create(ds) { - return ds.TestModel.replaceOrCreate({ id: 'not-found', name: 'not found' }); + return ds.TestModel.replaceOrCreate({id: 'not-found', name: 'not found'}); }, function replaceOrCreate_update(ds) { return ds.TestModel.replaceOrCreate( - { id: ds.existingInstance.id, name: 'new name' }); + {id: ds.existingInstance.id, name: 'new name'}); }, function replaceById(ds) { return ds.TestModel.replaceById( ds.existingInstance.id, - { name: 'new name' }); + {name: 'new name'}); }, function updateAll(ds) { - return ds.TestModel.updateAll({ name: 'searched' }, { name: 'updated' }); + return ds.TestModel.updateAll({name: 'searched'}, {name: 'updated'}); }, function prototypeSave(ds) { @@ -92,7 +94,7 @@ var operations = [ }, function prototypeUpdateAttributes(ds) { - return ds.existingInstance.updateAttributes({ name: 'changed' }); + return ds.existingInstance.updateAttributes({name: 'changed'}); }, function prototypeDelete(ds) { @@ -100,7 +102,7 @@ var operations = [ }, function deleteAll(ds) { - return ds.TestModel.deleteAll({ name: ds.existingInstance.name }); + return ds.TestModel.deleteAll({name: ds.existingInstance.name}); }, ]; /* eslint-enable camelcase */ @@ -113,13 +115,13 @@ operations.forEach(function(op) { p.then(report, function(err) { console.error(err.stack); }); function createOptimizedDataSource() { - var ds = new DataSource({ connector: Memory }); + var ds = new DataSource({connector: Memory}); ds.name = 'Optimized'; return ds; } function createUnoptimizedDataSource() { - var ds = new DataSource({ connector: Memory }); + var ds = new DataSource({connector: Memory}); ds.name = 'Unoptimized'; // disable optimized methods @@ -133,9 +135,9 @@ function createUnoptimizedDataSource() { function setupTestModels() { dataSources.forEach(function setupOnDataSource(ds) { var TestModel = ds.TestModel = ds.createModel('TestModel', { - id: { type: String, id: true, default: uid }, - name: { type: String, required: true }, - extra: { type: String, required: false }, + id: {type: String, id: true, default: uid}, + name: {type: String, required: true}, + extra: {type: String, required: false}, }); }); return Promise.resolve(); @@ -172,7 +174,7 @@ function resetStorage(ds) { }); return TestModel.deleteAll() .then(function() { - return TestModel.create({ name: 'first' }); + return TestModel.create({name: 'first'}); }) .then(function(instance) { // Look it up from DB so that default values are retrieved @@ -180,7 +182,7 @@ function resetStorage(ds) { }) .then(function(instance) { ds.existingInstance = instance; - return TestModel.create({ name: 'second' }); + return TestModel.create({name: 'second'}); }) .then(function() { HOOK_NAMES.forEach(function(hook) { diff --git a/test/CustomTypeForeignKey.test.js b/test/CustomTypeForeignKey.test.js index 0165dce1..62d1dcf0 100644 --- a/test/CustomTypeForeignKey.test.js +++ b/test/CustomTypeForeignKey.test.js @@ -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'); diff --git a/test/async-observer.test.js b/test/async-observer.test.js index 7edbbd07..b8edff0d 100644 --- a/test/async-observer.test.js +++ b/test/async-observer.test.js @@ -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'); @@ -11,7 +12,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) { @@ -303,7 +304,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) { diff --git a/test/basic-querying.test.js b/test/basic-querying.test.js index bb8006a7..f73c0d6f 100644 --- a/test/basic-querying.test.js +++ b/test/basic-querying.test.js @@ -4,6 +4,8 @@ // License text available at https://opensource.org/licenses/MIT // This test written in mocha+should.js +'use strict'; + var should = require('./init.js'); var async = require('async'); var db, User; @@ -13,13 +15,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); @@ -68,12 +70,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) { @@ -107,7 +109,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) { @@ -147,7 +149,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); @@ -156,7 +158,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); @@ -166,7 +168,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); @@ -176,7 +178,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); @@ -185,7 +187,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) { @@ -196,7 +198,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) { @@ -207,7 +209,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'); @@ -218,7 +220,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'); @@ -230,7 +232,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); @@ -241,10 +243,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(); @@ -252,10 +254,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(); @@ -263,10 +265,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(); @@ -274,10 +276,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(); @@ -285,7 +287,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); @@ -295,7 +297,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); @@ -304,7 +306,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); @@ -314,7 +316,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); @@ -324,7 +326,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); @@ -334,7 +336,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); @@ -343,7 +345,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); @@ -353,7 +355,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); @@ -363,7 +365,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); @@ -372,7 +374,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); @@ -381,7 +383,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); @@ -390,7 +392,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); @@ -400,7 +402,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); @@ -409,7 +411,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); @@ -419,7 +421,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); @@ -429,7 +431,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); @@ -439,7 +441,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); @@ -448,7 +450,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); @@ -458,7 +460,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); @@ -475,7 +477,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); @@ -505,10 +507,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']); @@ -530,7 +532,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); @@ -544,7 +546,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); @@ -555,7 +557,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); @@ -565,7 +567,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); @@ -576,7 +578,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); @@ -589,7 +591,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(); @@ -634,7 +636,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); }); @@ -651,7 +653,7 @@ describe.skip('queries', function() { var db = getSchema(); Todo = db.define('Todo', { id: false, - content: { type: 'string' }, + content: {type: 'string'}, }, { idInjection: false, }); @@ -660,16 +662,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(); }); @@ -678,7 +680,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(); }); @@ -686,14 +688,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(); }); @@ -726,14 +728,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(); }); @@ -803,7 +805,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(); @@ -833,10 +835,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([ diff --git a/test/common.batch.js b/test/common.batch.js index 0e5c69c2..e78c41f8 100644 --- a/test/common.batch.js +++ b/test/common.batch.js @@ -3,6 +3,8 @@ // 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'); require('./manipulation.test.js'); diff --git a/test/common_test.js b/test/common_test.js index 286ee91b..cf944879 100644 --- a/test/common_test.js +++ b/test/common_test.js @@ -3,6 +3,8 @@ // 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; @@ -98,45 +100,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() { } @@ -149,7 +151,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}); @@ -164,7 +166,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 @@ -174,8 +176,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; @@ -202,8 +204,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'); @@ -235,7 +237,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')); @@ -272,7 +274,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() { @@ -303,7 +305,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(); @@ -363,7 +365,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'); @@ -396,8 +398,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(); }); @@ -445,9 +447,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' @@ -472,7 +474,7 @@ function testOrm(dataSource) { 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(); }); @@ -495,7 +497,7 @@ function testOrm(dataSource) { // We could get the user with belongs to relationship but it is better if there is no interactions. User.findById(post.userId, function(err, user) { User.create(function(err, voidUser) { - Post.create({ userId: user.id }, function() { + Post.create({userId: user.id}, function() { // There can't be any concurrency because we are counting requests // We are first testing cases when user has posts @@ -509,7 +511,7 @@ function testOrm(dataSource) { if (dataSource.name === 'mongodb') { // for the moment mongodb doesn\'t support additional conditions on hasMany relations (see above) test.done(); } else { - user.posts({ where: { id: data[0].id }}, function(err, data) { + user.posts({where: {id: data[0].id}}, function(err, data) { test.equal(data.length, 1, 'There should be only one post.'); requestsAreCounted && test.equal(nbInitialRequests + 1, nbSchemaRequests, 'There should be one additional request since we added conditions.'); @@ -561,7 +563,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(); @@ -599,12 +601,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] : [ @@ -616,7 +618,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; @@ -645,7 +647,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) { @@ -657,7 +659,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) { @@ -670,7 +672,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'); @@ -685,7 +687,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) { @@ -699,7 +701,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'); @@ -713,7 +715,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'); @@ -893,7 +895,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; @@ -908,7 +910,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'); @@ -918,7 +920,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'); @@ -936,7 +938,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); @@ -947,7 +949,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 @@ -960,14 +962,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(); }); @@ -1050,7 +1052,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) { @@ -1067,18 +1069,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'); @@ -1093,14 +1095,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); @@ -1129,11 +1131,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); diff --git a/test/crud-with-options.test.js b/test/crud-with-options.test.js index b5ddf216..44ff3e84 100644 --- a/test/crud-with-options.test.js +++ b/test/crud-with-options.test.js @@ -4,6 +4,8 @@ // License text available at https://opensource.org/licenses/MIT // This test written in mocha+should.js +'use strict'; + var should = require('./init.js'); var async = require('async'); var db, User, options, filter; @@ -13,17 +15,17 @@ describe('crud-with-options', function() { before(function(done) { db = getSchema(); User = db.define('User', { - id: { type: Number, id: 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 }, + id: {type: Number, id: 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}, }); options = {}; - filter = { fields: ['name', 'id'] }; + filter = {fields: ['name', 'id']}; db.automigrate(['User'], done); @@ -96,7 +98,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) { @@ -112,7 +114,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) { @@ -128,7 +130,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) { @@ -144,7 +146,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); @@ -194,12 +196,12 @@ describe('crud-with-options', 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) { @@ -222,7 +224,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) { @@ -249,7 +251,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); @@ -267,15 +269,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); @@ -293,7 +295,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'); @@ -301,7 +303,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'); }); @@ -321,7 +323,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); @@ -330,7 +332,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); @@ -345,7 +347,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); @@ -356,7 +358,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); @@ -366,7 +368,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); @@ -376,7 +378,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); @@ -417,7 +419,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) { @@ -440,12 +442,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(); @@ -455,12 +457,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(); @@ -472,10 +474,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(); @@ -491,12 +493,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(); @@ -506,13 +508,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(); @@ -522,11 +524,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(); @@ -564,12 +566,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'); @@ -585,9 +587,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'); @@ -622,10 +624,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([ diff --git a/test/datasource.test.js b/test/datasource.test.js index 802c422e..55a92ce9 100644 --- a/test/datasource.test.js +++ b/test/datasource.test.js @@ -3,6 +3,8 @@ // 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; diff --git a/test/datatype.test.js b/test/datatype.test.js index 353d3857..bbc58aae 100644 --- a/test/datatype.test.js +++ b/test/datatype.test.js @@ -4,6 +4,8 @@ // License text available at https://opensource.org/licenses/MIT // This test written in mocha+should.js +'use strict'; + var should = require('./init.js'); var db, Model; @@ -12,14 +14,14 @@ 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, }); @@ -29,12 +31,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(); }); @@ -42,12 +44,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(); }); @@ -55,12 +57,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) { @@ -116,7 +118,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); @@ -165,7 +167,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'); }); @@ -173,10 +175,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(); @@ -190,8 +192,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, @@ -203,8 +205,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); @@ -217,13 +219,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); @@ -252,7 +254,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; @@ -282,14 +284,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 ); } diff --git a/test/default-scope.test.js b/test/default-scope.test.js index ef902e3e..f48cd9c6 100644 --- a/test/default-scope.test.js +++ b/test/default-scope.test.js @@ -4,6 +4,8 @@ // License text available at https://opensource.org/licenses/MIT // This test written in mocha+should.js +'use strict'; + var should = require('./init.js'); var async = require('async'); @@ -18,31 +20,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(); }); @@ -63,10 +65,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) { @@ -77,23 +79,23 @@ 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'}, forceId: false, }); @@ -101,23 +103,23 @@ describe('default scope', function() { // 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); @@ -141,10 +143,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 @@ -152,7 +154,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'); @@ -162,7 +164,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'); @@ -173,7 +175,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'); @@ -201,7 +203,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'); @@ -277,7 +279,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'); @@ -300,7 +302,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'); @@ -310,7 +312,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'); @@ -405,7 +407,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(); @@ -413,7 +415,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(); @@ -491,9 +493,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'); @@ -505,7 +507,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); @@ -516,7 +518,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'); @@ -538,7 +540,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); @@ -552,7 +554,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); @@ -578,7 +580,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); @@ -650,7 +652,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(); @@ -658,7 +660,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(); @@ -666,7 +668,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(); @@ -674,7 +676,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(); @@ -682,7 +684,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'); @@ -704,20 +706,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); }); @@ -799,7 +801,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); }); }); @@ -825,8 +827,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); }); }); diff --git a/test/defaults.test.js b/test/defaults.test.js index bdadbd7f..b63bdb2c 100644 --- a/test/defaults.test.js +++ b/test/defaults.test.js @@ -4,6 +4,8 @@ // License text available at https://opensource.org/licenses/MIT // This test written in mocha+should.js +'use strict'; + var should = require('./init.js'); var db = getSchema(); @@ -14,8 +16,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 +45,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 +58,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 +67,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); diff --git a/test/discovery.test.js b/test/discovery.test.js index b94a5941..1a1b8409 100644 --- a/test/discovery.test.js +++ b/test/discovery.test.js @@ -3,6 +3,8 @@ // 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; var should = require('./init.js'); @@ -11,11 +13,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 +104,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 +119,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 +128,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 +139,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 +186,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 +287,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 +354,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 +438,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 +498,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 +555,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', @@ -610,9 +612,9 @@ describe('discoverExportedForeignKeys', function() { }); describe('Mock connector', function() { - mockConnectors = require('./mock-connectors'); + var mockConnectors = require('./mock-connectors'); describe('customFieldSettings', function() { - ds = new DataSource(mockConnectors.customFieldSettings); + var ds = new DataSource(mockConnectors.customFieldSettings); it('should be present in discoverSchemas', function(done) { ds.discoverSchemas('person', function(err, schemas) { @@ -630,7 +632,7 @@ describe('Default memory connector', function() { var ds, nonExistantError = 'Table \'NONEXISTENT\' does not exist.'; before(function() { - ds = new DataSource({ connector: 'memory' }); + ds = new DataSource({connector: 'memory'}); }); it('discoverSchema should return an error when table does not exist', function(done) { diff --git a/test/geo.test.js b/test/geo.test.js index 8c0b2f77..3a1160ca 100644 --- a/test/geo.test.js +++ b/test/geo.test.js @@ -6,6 +6,8 @@ /*global describe,it*/ /*jshint expr:true */ +'use strict'; + require('should'); var GeoPoint = require('../lib/geo').GeoPoint; @@ -23,7 +25,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); @@ -85,7 +87,7 @@ describe('GeoPoint', 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'); }); @@ -93,8 +95,8 @@ describe('GeoPoint', function() { describe('distance calculation between two points', function() { - var here = new GeoPoint({ lat: 40.77492964101182, lng: -73.90950187151662 }); - var there = new GeoPoint({ lat: 40.7753227, lng: -73.909217 }); + 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() { @@ -114,27 +116,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); }); diff --git a/test/helpers/context-test-helpers.js b/test/helpers/context-test-helpers.js index cb8d0dc4..752cbb0f 100644 --- a/test/helpers/context-test-helpers.js +++ b/test/helpers/context-test-helpers.js @@ -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'); diff --git a/test/helpers/hook-monitor.js b/test/helpers/hook-monitor.js index 20af6cbc..0197e197 100644 --- a/test/helpers/hook-monitor.js +++ b/test/helpers/hook-monitor.js @@ -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; diff --git a/test/helpers/uid-generator.js b/test/helpers/uid-generator.js index f2bc95b4..393bcaa1 100644 --- a/test/helpers/uid-generator.js +++ b/test/helpers/uid-generator.js @@ -3,6 +3,8 @@ // This file is licensed under the MIT License. // License text available at https://opensource.org/licenses/MIT +'use strict'; + var lastId = 0; exports.next = function() { diff --git a/test/hooks.test.js b/test/hooks.test.js index 7cb9b5c3..a0de550b 100644 --- a/test/hooks.test.js +++ b/test/hooks.test.js @@ -3,6 +3,8 @@ // 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'); @@ -19,7 +21,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, @@ -48,7 +50,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(); @@ -131,7 +133,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'}); }); }); @@ -165,7 +167,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(); @@ -188,7 +190,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(); @@ -234,7 +236,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'}); }); }); @@ -252,7 +254,7 @@ describe('hooks', function() { data.should.have.keys('name', 'email'); done(); }; - user.updateAttributes({ name: 1, email: 2 }); + user.updateAttributes({name: 1, email: 2}); }); }); @@ -399,7 +401,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', diff --git a/test/include.test.js b/test/include.test.js index 8a93a4cd..89dbdb08 100644 --- a/test/include.test.js +++ b/test/include.test.js @@ -3,6 +3,8 @@ // 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 async = require('async'); var assert = require('assert'); @@ -16,7 +18,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 +41,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 +61,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); @@ -91,7 +93,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'); @@ -113,7 +115,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; @@ -125,7 +127,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); @@ -155,7 +157,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', }}}, @@ -282,9 +284,9 @@ describe('include', function() { scope: { where: { and: [ - { id: 1 }, - { userId: 1 }, - { title: 'Post A' }, + {id: 1}, + {userId: 1}, + {title: 'Post A'}, ], }, }, @@ -361,7 +363,7 @@ describe('include', function() { it('works when using `where` without `limit`, `skip` or `offset`', function(done) { - User.findOne({ include: { relation: 'posts' }}, function(err, user) { + User.findOne({include: {relation: 'posts'}}, function(err, user) { if (err) return done(err); var posts = user.posts(); @@ -383,7 +385,7 @@ describe('include', function() { // --superkhau Post.dataSource.settings.inqLimit = 2; - User.find({ include: { relation: 'posts' }}, function(err, users) { + User.find({include: {relation: 'posts'}}, function(err, users) { if (err) return done(err); users.length.should.equal(5); @@ -397,7 +399,7 @@ describe('include', function() { it('works when page size is set to 0', function(done) { Post.dataSource.settings.inqLimit = 0; - User.find({ include: { relation: 'posts' }}, function(err, users) { + User.find({include: {relation: 'posts'}}, function(err, users) { if (err) return done(err); users.length.should.equal(5); @@ -421,13 +423,13 @@ describe('include', function() { // --superkhau it('works when hasOne is called', function(done) { - User.findOne({ include: { relation: 'profile' }}, function(err, user) { + User.findOne({include: {relation: 'profile'}}, function(err, user) { if (err) return done(err); user.name.should.equal('User A'); user.age.should.equal(21); user.id.should.equal(1); - profile = user.profile(); + var profile = user.profile(); profile.profileName.should.equal('Profile A'); profile.userId.should.equal(1); profile.id.should.equal(1); @@ -437,7 +439,7 @@ describe('include', function() { }); it('works when hasMany is called', function(done) { - User.findOne({ include: { relation: 'posts' }}, function(err, user) { + User.findOne({include: {relation: 'posts'}}, function(err, user) { if (err) return done(); user.name.should.equal('User A'); @@ -450,9 +452,9 @@ describe('include', function() { }); it('works when hasManyThrough is called', function(done) { - Physician = db.define('Physician', { name: String }); - Patient = db.define('Patient', { name: String }); - Appointment = db.define('Appointment', { + var Physician = db.define('Physician', {name: String}); + var Patient = db.define('Patient', {name: String}); + var Appointment = db.define('Appointment', { date: { type: Date, default: function() { @@ -460,10 +462,10 @@ describe('include', function() { }, }, }); - Address = db.define('Address', { name: String }); + var Address = db.define('Address', {name: String}); - Physician.hasMany(Patient, { through: Appointment }); - Patient.hasMany(Physician, { through: Appointment }); + Physician.hasMany(Patient, {through: Appointment}); + Patient.hasMany(Physician, {through: Appointment}); Patient.belongsTo(Address); Appointment.belongsTo(Patient); Appointment.belongsTo(Physician); @@ -471,11 +473,11 @@ describe('include', function() { db.automigrate(['Physician', 'Patient', 'Appointment', 'Address'], function() { Physician.create(function(err, physician) { - physician.patients.create({ name: 'a' }, function(err, patient) { - Address.create({ name: 'z' }, function(err, address) { + physician.patients.create({name: 'a'}, function(err, patient) { + Address.create({name: 'z'}, function(err, address) { patient.address(address); patient.save(function() { - physician.patients({ include: 'address' }, + physician.patients({include: 'address'}, function(err, posts) { if (err) return done(err); @@ -496,13 +498,13 @@ describe('include', function() { }); it('works when belongsTo is called', function(done) { - Profile.findOne({ include: 'user' }, function(err, profile) { + Profile.findOne({include: 'user'}, function(err, profile) { if (err) return done(err); profile.profileName.should.equal('Profile A'); profile.userId.should.equal(1); profile.id.should.equal(1); - user = profile.user(); + var user = profile.user(); user.name.should.equal('User A'); user.age.should.equal(21); user.id.should.equal(1); @@ -515,7 +517,7 @@ describe('include', function() { it('should fetch Users with include scope on Posts - belongsTo', function(done) { - Post.find({ include: { relation: 'author', scope: { fields: ['name'] }}}, + Post.find({include: {relation: 'author', scope: {fields: ['name']}}}, function(err, posts) { should.not.exist(err); should.exist(posts); @@ -532,7 +534,7 @@ describe('include', function() { it('should fetch Users with include scope on Posts - hasMany', function(done) { User.find({ - include: { relation: 'posts', scope: { + include: {relation: 'posts', scope: { order: 'title DESC', }}, }, function(err, users) { @@ -562,8 +564,8 @@ describe('include', function() { it('should fetch Users with include scope on Passports - hasMany', function(done) { User.find({ - include: { relation: 'passports', scope: { - where: { number: '2' }, + include: {relation: 'passports', scope: { + where: {number: '2'}, }}, }, function(err, users) { should.not.exist(err); @@ -582,7 +584,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; @@ -615,12 +617,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; @@ -653,7 +655,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; @@ -666,8 +668,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); @@ -676,9 +678,9 @@ describe('include', function() { parts[0].partNumber.should.equal('engine'); // Create a part - assembly.parts.create({ partNumber: 'door' }, function(err, part4) { + assembly.parts.create({partNumber: 'door'}, function(err, part4) { - Assembly.find({ include: 'parts' }, function(err, assemblies) { + Assembly.find({include: 'parts'}, function(err, assemblies) { assemblies.length.should.equal(1); assemblies[0].parts().length.should.equal(2); done(); @@ -692,7 +694,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; @@ -724,8 +726,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(); @@ -773,7 +775,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'); @@ -796,11 +798,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) { @@ -849,7 +851,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; @@ -884,9 +886,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; @@ -921,22 +923,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'); @@ -966,16 +968,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, @@ -998,11 +1000,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; @@ -1016,8 +1018,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) {} ); @@ -1027,10 +1029,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; @@ -1043,9 +1045,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; @@ -1058,11 +1060,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; @@ -1099,7 +1101,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, @@ -1156,25 +1158,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]; diff --git a/test/include_util.test.js b/test/include_util.test.js index 244b9f85..da4c9a3a 100644 --- a/test/include_util.test.js +++ b/test/include_util.test.js @@ -3,6 +3,7 @@ // This file is licensed under the MIT License. // License text available at https://opensource.org/licenses/MIT +'use strict'; var assert = require('assert'); var should = require('should'); @@ -12,8 +13,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; @@ -22,10 +23,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'); @@ -39,8 +40,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; @@ -51,8 +52,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; @@ -61,10 +62,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'); @@ -90,11 +91,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(); diff --git a/test/init.js b/test/init.js index 96dd3396..cd2cb5c2 100644 --- a/test/init.js +++ b/test/init.js @@ -3,6 +3,7 @@ // This file is licensed under the MIT License. // License text available at https://opensource.org/licenses/MIT +'use strict'; module.exports = require('should'); /* diff --git a/test/introspection.test.js b/test/introspection.test.js index 481007b4..54b76db6 100644 --- a/test/introspection.test.js +++ b/test/introspection.test.js @@ -3,6 +3,7 @@ // 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; var DataSource = require('../').DataSource; @@ -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: [], }; @@ -60,7 +61,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'); @@ -68,7 +69,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'); @@ -78,7 +79,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'); @@ -92,7 +93,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); @@ -107,7 +108,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(); @@ -120,7 +121,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); diff --git a/test/json.test.js b/test/json.test.js index d21b2fab..d5356185 100644 --- a/test/json.test.js +++ b/test/json.test.js @@ -4,6 +4,7 @@ // License text available at https://opensource.org/licenses/MIT // This test written in mocha+should.js +'use strict'; var should = require('./init.js'); var Schema = require('../').Schema; @@ -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'); }); diff --git a/test/kv-memory.js b/test/kv-memory.js index f04b49a5..980be0f6 100644 --- a/test/kv-memory.js +++ b/test/kv-memory.js @@ -1,9 +1,10 @@ +'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); diff --git a/test/kvao/get-set.suite.js b/test/kvao/get-set.suite.js index 26948e2e..3405fc89 100644 --- a/test/kvao/get-set.suite.js +++ b/test/kvao/get-set.suite.js @@ -29,9 +29,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() { @@ -68,7 +68,7 @@ module.exports = function(dataSourceFactory, connectorCapabilities) { }); it('honours options.ttl', function() { - return CacheItem.set('a-key', 'a-value', { ttl: 10 }) + return CacheItem.set('a-key', 'a-value', {ttl: 10}) .delay(20) .then(function() { return CacheItem.get('a-key'); }) .then(function(value) { should.equal(value, null); }); @@ -90,7 +90,7 @@ module.exports = function(dataSourceFactory, connectorCapabilities) { describe('set', function() { it('resets TTL timer', function() { - return CacheItem.set('a-key', 'a-value', { ttl: 10 }) + return CacheItem.set('a-key', 'a-value', {ttl: 10}) .then(function() { return CacheItem.set('a-key', 'another-value'); // no TTL }) diff --git a/test/kvao/keys.suite.js b/test/kvao/keys.suite.js index adb1d474..1817b1fa 100644 --- a/test/kvao/keys.suite.js +++ b/test/kvao/keys.suite.js @@ -83,19 +83,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([]); }); diff --git a/test/loopback-data.test.js b/test/loopback-data.test.js index 05e9fa22..8d175b88 100644 --- a/test/loopback-data.test.js +++ b/test/loopback-data.test.js @@ -4,6 +4,7 @@ // License text available at https://opensource.org/licenses/MIT // This test written in mocha+should.js +'use strict'; var should = require('./init.js'); var loopbackData = require('../'); diff --git a/test/loopback-dl.test.js b/test/loopback-dl.test.js index 3897df43..07e59efe 100644 --- a/test/loopback-dl.test.js +++ b/test/loopback-dl.test.js @@ -4,6 +4,7 @@ // License text available at https://opensource.org/licenses/MIT // This test written in mocha+should.js +'use strict'; var should = require('./init.js'); var assert = require('assert'); var async = require('async'); @@ -33,7 +34,7 @@ describe('ModelBuilder define model', function() { modelBuilder.models.should.be.type('object').and.have.property('User').exactly(User); modelBuilder.definitions.should.be.type('object').and.have.property('User'); - var user = new User({ name: 'Joe', age: 20, xyz: false }); + var user = new User({name: 'Joe', age: 20, xyz: false}); User.modelName.should.equal('User'); user.should.be.type('object').and.have.property('name', 'Joe'); @@ -47,9 +48,9 @@ describe('ModelBuilder define model', function() { it('should not take unknown properties in strict mode', function(done) { var modelBuilder = new ModelBuilder(); - var User = modelBuilder.define('User', { name: String, bio: String }, { strict: true }); + var User = modelBuilder.define('User', {name: String, bio: String}, {strict: true}); - var user = new User({ name: 'Joe', age: 20 }); + var user = new User({name: 'Joe', age: 20}); User.modelName.should.equal('User'); user.should.be.type('object'); @@ -64,9 +65,9 @@ describe('ModelBuilder define model', function() { it('should ignore non-predefined properties in strict mode', function(done) { var modelBuilder = new ModelBuilder(); - var User = modelBuilder.define('User', { name: String, bio: String }, { strict: true }); + var User = modelBuilder.define('User', {name: String, bio: String}, {strict: true}); - var user = new User({ name: 'Joe' }); + var user = new User({name: 'Joe'}); user.age = 10; user.bio = 'me'; @@ -88,10 +89,10 @@ describe('ModelBuilder define model', function() { it('should throw when unknown properties are used if strict=throw', function(done) { var modelBuilder = new ModelBuilder(); - var User = modelBuilder.define('User', { name: String, bio: String }, { strict: 'throw' }); + var User = modelBuilder.define('User', {name: String, bio: String}, {strict: 'throw'}); try { - var user = new User({ name: 'Joe', age: 20 }); + var user = new User({name: 'Joe', age: 20}); assert(false, 'The code should have thrown an error'); } catch (e) { assert(true, 'The code is expected to throw an error'); @@ -102,9 +103,9 @@ describe('ModelBuilder define model', function() { it('should be able to define open models', function(done) { var modelBuilder = new ModelBuilder(); - var User = modelBuilder.define('User', {}, { strict: false }); + var User = modelBuilder.define('User', {}, {strict: false}); - var user = new User({ name: 'Joe', age: 20 }); + var user = new User({name: 'Joe', age: 20}); User.modelName.should.equal('User'); user.should.be.type('object').and.have.property('name', 'Joe'); @@ -117,9 +118,9 @@ describe('ModelBuilder define model', function() { it('should take non-predefined properties in non-strict mode', function(done) { var modelBuilder = new ModelBuilder(); - var User = modelBuilder.define('User', { name: String, bio: String }, { strict: false }); + var User = modelBuilder.define('User', {name: String, bio: String}, {strict: false}); - var user = new User({ name: 'Joe' }); + var user = new User({name: 'Joe'}); user.age = 10; user.bio = 'me'; @@ -144,7 +145,7 @@ describe('ModelBuilder define model', function() { var User = modelBuilder.define('User', {}); - var user = new User({ name: 'Joe', age: 20 }); + var user = new User({name: 'Joe', age: 20}); User.modelName.should.equal('User'); user.should.be.type('object').and.have.property('name', 'Joe'); @@ -190,9 +191,9 @@ describe('ModelBuilder define model', function() { var user = new User({ name: 'Joe', age: 20, - address: { street: '123 Main St', 'city': 'San Jose', state: 'CA' }, + address: {street: '123 Main St', 'city': 'San Jose', state: 'CA'}, emails: [ - { label: 'work', email: 'xyz@sample.com' }, + {label: 'work', email: 'xyz@sample.com'}, ], friends: ['Mary', 'John'], }); @@ -219,11 +220,11 @@ describe('ModelBuilder define model', function() { it('should be able to reference models by name before they are defined', function(done) { var modelBuilder = new ModelBuilder(); - var User = modelBuilder.define('User', { name: String, address: 'Address' }); + var User = modelBuilder.define('User', {name: String, address: 'Address'}); var user; try { - user = new User({ name: 'Joe', address: { street: '123 Main St', 'city': 'San Jose', state: 'CA' }}); + user = new User({name: 'Joe', address: {street: '123 Main St', 'city': 'San Jose', state: 'CA'}}); assert(false, 'An exception should have been thrown'); } catch (e) { // Ignore @@ -237,7 +238,7 @@ describe('ModelBuilder define model', function() { country: String, }); - user = new User({ name: 'Joe', address: { street: '123 Main St', 'city': 'San Jose', state: 'CA' }}); + user = new User({name: 'Joe', address: {street: '123 Main St', 'city': 'San Jose', state: 'CA'}}); User.modelName.should.equal('User'); User.definition.properties.address.should.have.property('type', Address); @@ -251,14 +252,14 @@ describe('ModelBuilder define model', function() { it('should define an id property for composite ids', function() { var modelBuilder = new ModelBuilder(); var Follow = modelBuilder.define('Follow', { - followerId: { type: String, id: 1 }, - followeeId: { type: String, id: 2 }, + followerId: {type: String, id: 1}, + followeeId: {type: String, id: 2}, followAt: Date, }); - var follow = new Follow({ followerId: 1, followeeId: 2 }); + var follow = new Follow({followerId: 1, followeeId: 2}); follow.should.have.property('id'); - assert.deepEqual(follow.id, { followerId: 1, followeeId: 2 }); + assert.deepEqual(follow.id, {followerId: 1, followeeId: 2}); }); }); @@ -285,7 +286,7 @@ describe('DataSource ping', function() { it('should cancel invocation after timeout', function(done) { ds.connected = false; // Force connect var Post = ds.define('Post', { - title: { type: String, length: 255 }, + title: {type: String, length: 255}, }); Post.create(function(err) { (!!err).should.be.true; @@ -301,13 +302,13 @@ describe('DataSource define model', function() { // define models var Post = ds.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 @@ -315,11 +316,11 @@ describe('DataSource define model', function() { name: String, bio: ModelBuilder.Text, approved: Boolean, - joinedAt: { type: Date, default: Date }, + joinedAt: {type: Date, default: Date}, age: Number, }); - var Group = ds.define('Group', { group: String }); + var Group = ds.define('Group', {group: String}); User.mixin(Group); // define any custom method @@ -327,49 +328,49 @@ describe('DataSource define model', function() { return this.name + ', ' + this.age; }; - var user = new User({ name: 'Joe', group: 'G1' }); + var user = new User({name: 'Joe', group: 'G1'}); assert.equal(user.name, 'Joe'); assert.equal(user.group, 'G1'); assert(user.joinedAt instanceof Date); // setup relationships - User.hasMany(Post, { as: 'posts', foreignKey: 'userId' }); + User.hasMany(Post, {as: 'posts', foreignKey: 'userId'}); - Post.belongsTo(User, { as: 'author', foreignKey: 'userId' }); + Post.belongsTo(User, {as: 'author', foreignKey: 'userId'}); User.hasAndBelongsToMany('groups'); - var user2 = new User({ name: 'Smith' }); + var user2 = new User({name: 'Smith'}); user2.save(function(err) { - 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' }, function(err, data) { + User.create({name: 'Jeff'}, function(err, data) { if (err) { console.log(err); return; } - var post = data.posts.build({ title: 'My Post' }); + var post = data.posts.build({title: 'My Post'}); }); - User.create({ name: 'Ray' }, function(err, data) { + User.create({name: 'Ray'}, function(err, data) { // console.log(data); }); - 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); @@ -391,9 +392,9 @@ describe('DataSource define model', function() { ds.attach(Color); Color.should.have.property('create'); - 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) { colors.should.have.lengthOf(3); @@ -432,9 +433,9 @@ describe('DataSource define model', function() { it('should not take unknown properties in strict mode', function(done) { var ds = new DataSource('memory'); - var User = ds.define('User', { name: String, bio: String }, { strict: true }); + var User = ds.define('User', {name: String, bio: String}, {strict: true}); - User.create({ name: 'Joe', age: 20 }, function(err, user) { + User.create({name: 'Joe', age: 20}, function(err, user) { User.modelName.should.equal('User'); user.should.be.type('object'); @@ -450,10 +451,10 @@ describe('DataSource define model', function() { it('should throw when unknown properties are used if strict=throw', function(done) { var ds = new DataSource('memory'); - var User = ds.define('User', { name: String, bio: String }, { strict: 'throw' }); + var User = ds.define('User', {name: String, bio: String}, {strict: 'throw'}); try { - var user = new User({ name: 'Joe', age: 20 }); + var user = new User({name: 'Joe', age: 20}); assert(false, 'The code should have thrown an error'); } catch (e) { assert(true, 'The code is expected to throw an error'); @@ -464,8 +465,8 @@ describe('DataSource define model', function() { describe('strict mode "validate"', function() { it('should report validation error for unknown properties', function() { var ds = new DataSource('memory'); - var User = ds.define('User', { name: String }, { strict: 'validate' }); - var user = new User({ name: 'Joe', age: 20 }); + var User = ds.define('User', {name: String}, {strict: 'validate'}); + var user = new User({name: 'Joe', age: 20}); user.isValid().should.be.false; var codes = user.errors && user.errors.codes || {}; codes.should.have.property('age').eql(['unknown-property']); @@ -475,10 +476,10 @@ describe('DataSource define model', function() { it('should be able to define open models', function(done) { var ds = new DataSource('memory'); - var User = ds.define('User', {}, { strict: false }); + var User = ds.define('User', {}, {strict: false}); User.modelName.should.equal('User'); - User.create({ name: 'Joe', age: 20 }, function(err, user) { + User.create({name: 'Joe', age: 20}, function(err, user) { user.should.be.type('object').and.have.property('name', 'Joe'); user.should.have.property('name', 'Joe'); @@ -500,7 +501,7 @@ describe('DataSource define model', function() { var User = ds.define('User', {}); - User.create({ name: 'Joe', age: 20 }, function(err, user) { + User.create({name: 'Joe', age: 20}, function(err, user) { User.modelName.should.equal('User'); user.should.be.type('object').and.have.property('name', 'Joe'); @@ -515,9 +516,9 @@ describe('DataSource define model', function() { var ds = new DataSource('memory'); ds.connector.relational = true; // HACK - var User = ds.define('User', { name: String, bio: String }, { strict: true }); + var User = ds.define('User', {name: String, bio: String}, {strict: true}); - var user = new User({ name: 'Joe', age: 20 }); + var user = new User({name: 'Joe', age: 20}); User.modelName.should.equal('User'); user.should.be.type('object'); @@ -533,10 +534,10 @@ describe('DataSource define model', function() { var ds = new DataSource('memory'); ds.connector.relational = true; // HACK - var User = ds.define('User', { name: String, bio: String }, { strict: 'throw' }); + var User = ds.define('User', {name: String, bio: String}, {strict: 'throw'}); try { - var user = new User({ name: 'Joe', age: 20 }); + var user = new User({name: 'Joe', age: 20}); assert(false, 'The code should have thrown an error'); } catch (e) { assert(true, 'The code is expected to throw an error'); @@ -548,7 +549,7 @@ describe('DataSource define model', function() { var ds = new DataSource('memory');// define models var Post = ds.define('Post'); - Post.create({ price: 900 }, function(err, post) { + Post.create({price: 900}, function(err, post) { assert.equal(post.price, 900); post.price = 1000; post.save(function(err, result) { @@ -561,9 +562,9 @@ describe('DataSource define model', function() { it('supports instance level strict mode', function() { var ds = new DataSource('memory'); - var User = ds.define('User', { name: String, bio: String }, { strict: true }); + var User = ds.define('User', {name: String, bio: String}, {strict: true}); - var user = new User({ name: 'Joe', age: 20 }, { strict: false }); + var user = new User({name: 'Joe', age: 20}, {strict: false}); user.should.have.property('__strict', false); user.should.be.type('object'); @@ -581,13 +582,14 @@ describe('DataSource define model', function() { it('should update the instance with unknown properties', function(done) { var ds = new DataSource('memory');// define models + var Post; Post = ds.define('Post', { - title: { type: String, length: 255, index: true }, - content: { type: String }, + title: {type: String, length: 255, index: true}, + content: {type: String}, }); - Post.create({ title: 'a', content: 'AAA' }, function(err, post) { - post.updateAttributes({ title: 'b', xyz: 'xyz' }, function(err, p) { + Post.create({title: 'a', content: 'AAA'}, function(err, post) { + post.updateAttributes({title: 'b', xyz: 'xyz'}, function(err, p) { should.not.exist(err); p.id.should.be.equal(post.id); p.content.should.be.equal(post.content); @@ -610,7 +612,7 @@ describe('DataSource define model', function() { var User = ds.define('User', {}); assert.deepEqual(User.definition.properties.id, - { type: Number, id: 1, generated: true }); + {type: Number, id: 1, generated: true}); done(); }); @@ -618,7 +620,7 @@ describe('DataSource define model', function() { it('disables idInjection if the value is false', function(done) { var ds = new ModelBuilder(); - var User1 = ds.define('User', {}, { idInjection: false }); + var User1 = ds.define('User', {}, {idInjection: false}); assert(!User1.definition.properties.id); done(); }); @@ -626,15 +628,15 @@ describe('DataSource define model', function() { it('updates generated id type by the connector', function(done) { var builder = new ModelBuilder(); - var User = builder.define('User', { id: { type: String, generated: true, id: true }}); + var User = builder.define('User', {id: {type: String, generated: true, id: true}}); assert.deepEqual(User.definition.properties.id, - { type: String, id: 1, generated: true }); + {type: String, id: 1, generated: true}); var ds = new DataSource('memory');// define models User.attachTo(ds); assert.deepEqual(User.definition.properties.id, - { type: Number, id: 1, generated: true }); + {type: Number, id: 1, generated: true}); done(); }); @@ -642,8 +644,8 @@ describe('DataSource define model', function() { it('should allow an explicit remoting path', function() { var ds = new DataSource('memory'); - var User = ds.define('User', { name: String, bio: String }, { - http: { path: 'accounts' }, + var User = ds.define('User', {name: String, bio: String}, { + http: {path: 'accounts'}, }); User.http.path.should.equal('/accounts'); }); @@ -651,8 +653,8 @@ describe('DataSource define model', function() { it('should allow an explicit remoting path with leading /', function() { var ds = new DataSource('memory'); - var User = ds.define('User', { name: String, bio: String }, { - http: { path: '/accounts' }, + var User = ds.define('User', {name: String, bio: String}, { + http: {path: '/accounts'}, }); User.http.path.should.equal('/accounts'); }); @@ -663,14 +665,14 @@ describe('Load models with base', function() { it('should set up base class via base option', function() { var ds = new ModelBuilder(); - var User = ds.define('User', { name: String }); + var User = ds.define('User', {name: String}); User.staticMethod = function staticMethod() { }; User.prototype.instanceMethod = function instanceMethod() { }; - var Customer = ds.define('Customer', { vip: Boolean }, { base: 'User' }); + var Customer = ds.define('Customer', {vip: Boolean}, {base: 'User'}); assert(Customer.prototype instanceof User); assert(Customer.staticMethod === User.staticMethod); @@ -679,7 +681,7 @@ describe('Load models with base', function() { assert.equal(Customer.base, Customer.super_); try { - var Customer1 = ds.define('Customer1', { vip: Boolean }, { base: 'User1' }); + var Customer1 = ds.define('Customer1', {vip: Boolean}, {base: 'User1'}); } catch (e) { assert(e); } @@ -688,9 +690,9 @@ describe('Load models with base', function() { it('should inherit properties from base option', function() { var ds = new ModelBuilder(); - var User = ds.define('User', { name: String }); + var User = ds.define('User', {name: String}); - var Customer = ds.define('Customer', { vip: Boolean }, { base: 'User' }); + var Customer = ds.define('Customer', {vip: Boolean}, {base: 'User'}); Customer.definition.properties.should.have.property('name'); Customer.definition.properties.name.should.have.property('type', String); @@ -699,10 +701,10 @@ describe('Load models with base', function() { it('should inherit properties by clone from base option', function() { var ds = new ModelBuilder(); - var User = ds.define('User', { name: String }); + var User = ds.define('User', {name: String}); - var Customer1 = ds.define('Customer1', { vip: Boolean }, { base: 'User' }); - var Customer2 = ds.define('Customer2', { vip: Boolean }, { base: 'User' }); + var Customer1 = ds.define('Customer1', {vip: Boolean}, {base: 'User'}); + var Customer2 = ds.define('Customer2', {vip: Boolean}, {base: 'User'}); Customer1.definition.properties.should.have.property('name'); Customer2.definition.properties.should.have.property('name'); @@ -715,21 +717,21 @@ describe('Load models with base', function() { it('should revert properties from base model', function() { var ds = new ModelBuilder(); - var User = ds.define('User', { username: String, email: String }); + var User = ds.define('User', {username: String, email: String}); var Customer = ds.define('Customer', - { name: String, username: null, email: false }, - { base: 'User' }); + {name: String, username: null, email: false}, + {base: 'User'}); Customer.definition.properties.should.have.property('name'); // username/email are now shielded Customer.definition.properties.should.not.have.property('username'); Customer.definition.properties.should.not.have.property('email'); - var c = new Customer({ name: 'John' }); + var c = new Customer({name: 'John'}); c.should.have.property('username', undefined); c.should.have.property('email', undefined); c.should.have.property('name', 'John'); - var u = new User({ username: 'X', email: 'x@y.com' }); + var u = new User({username: 'X', email: 'x@y.com'}); u.should.not.have.property('name'); u.should.have.property('username', 'X'); u.should.have.property('email', 'x@y.com'); @@ -738,14 +740,14 @@ describe('Load models with base', function() { it('should set up base class via parent arg', function() { var ds = new ModelBuilder(); - var User = ds.define('User', { name: String }); + var User = ds.define('User', {name: String}); User.staticMethod = function staticMethod() { }; User.prototype.instanceMethod = function instanceMethod() { }; - var Customer = ds.define('Customer', { vip: Boolean }, {}, User); + var Customer = ds.define('Customer', {vip: Boolean}, {}, User); Customer.definition.properties.should.have.property('name'); Customer.definition.properties.name.should.have.property('type', String); @@ -763,10 +765,10 @@ describe('Models attached to a dataSource', function() { before(function() { var ds = new DataSource('memory');// define models 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], - }, { forceId: false }); + }, {forceId: false}); }); beforeEach(function(done) { @@ -774,7 +776,7 @@ describe('Models attached to a dataSource', function() { }); it('updateOrCreate should update the instance', function(done) { - Post.create({ title: 'a', content: 'AAA' }, function(err, post) { + Post.create({title: 'a', content: 'AAA'}, function(err, post) { post.title = 'b'; Post.updateOrCreate(post, function(err, p) { should.not.exist(err); @@ -796,7 +798,7 @@ describe('Models attached to a dataSource', function() { }); it('updateOrCreate should update the instance without removing existing properties', function(done) { - Post.create({ title: 'a', content: 'AAA', comments: ['Comment1'] }, function(err, post) { + Post.create({title: 'a', content: 'AAA', comments: ['Comment1']}, function(err, post) { post = post.toObject(); delete post.title; delete post.comments; @@ -821,7 +823,7 @@ describe('Models attached to a dataSource', function() { }); it('updateOrCreate should create a new instance if it does not exist', function(done) { - var post = { id: 123, title: 'a', content: 'AAA' }; + var post = {id: 123, title: 'a', content: 'AAA'}; Post.updateOrCreate(post, function(err, p) { should.not.exist(err); p.title.should.be.equal(post.title); @@ -842,7 +844,7 @@ describe('Models attached to a dataSource', function() { }); it('save should update the instance with the same id', function(done) { - Post.create({ title: 'a', content: 'AAA' }, function(err, post) { + Post.create({title: 'a', content: 'AAA'}, function(err, post) { post.title = 'b'; post.save(function(err, p) { should.not.exist(err); @@ -864,7 +866,7 @@ describe('Models attached to a dataSource', function() { }); it('save should update the instance without removing existing properties', function(done) { - Post.create({ title: 'a', content: 'AAA' }, function(err, post) { + Post.create({title: 'a', content: 'AAA'}, function(err, post) { delete post.title; post.save(function(err, p) { should.not.exist(err); @@ -886,7 +888,7 @@ describe('Models attached to a dataSource', function() { }); it('save should create a new instance if it does not exist', function(done) { - var post = new Post({ id: '123', title: 'a', content: 'AAA' }); + var post = new Post({id: '123', title: 'a', content: 'AAA'}); post.save(post, function(err, p) { should.not.exist(err); p.title.should.be.equal(post.title); @@ -1011,9 +1013,9 @@ describe('Load models with relations', function() { it('should set up relations', function(done) { var ds = new DataSource('memory'); - var Post = ds.define('Post', { userId: Number, content: String }); - var User = ds.define('User', { name: String }, { - relations: { posts: { type: 'hasMany', model: 'Post' }}, + var Post = ds.define('Post', {userId: Number, content: String}); + var User = ds.define('User', {name: String}, { + relations: {posts: {type: 'hasMany', model: 'Post'}}, }); assert(User.relations['posts']); @@ -1023,9 +1025,9 @@ describe('Load models with relations', function() { it('should set up belongsTo relations', function(done) { var ds = new DataSource('memory'); - var User = ds.define('User', { name: String }); - var Post = ds.define('Post', { userId: Number, content: String }, { - relations: { user: { type: 'belongsTo', model: 'User' }}, + var User = ds.define('User', {name: String}); + var Post = ds.define('Post', {userId: Number, content: String}, { + relations: {user: {type: 'belongsTo', model: 'User'}}, }); assert(Post.relations['user']); @@ -1035,9 +1037,9 @@ describe('Load models with relations', function() { it('should set up referencesMany relations', function(done) { var ds = new DataSource('memory'); - var Post = ds.define('Post', { userId: Number, content: String }); - var User = ds.define('User', { name: String }, { - relations: { posts: { type: 'referencesMany', model: 'Post' }}, + var Post = ds.define('Post', {userId: Number, content: String}); + var User = ds.define('User', {name: String}, { + relations: {posts: {type: 'referencesMany', model: 'Post'}}, }); assert(User.relations['posts']); @@ -1047,9 +1049,9 @@ describe('Load models with relations', function() { it('should set up embedsMany relations', function(done) { var ds = new DataSource('memory'); - var Post = ds.define('Post', { userId: Number, content: String }); - var User = ds.define('User', { name: String }, { - relations: { posts: { type: 'embedsMany', model: 'Post' }}, + var Post = ds.define('Post', {userId: Number, content: String}); + var User = ds.define('User', {name: String}, { + relations: {posts: {type: 'embedsMany', model: 'Post'}}, }); assert(User.relations['posts']); @@ -1059,11 +1061,11 @@ describe('Load models with relations', function() { it('should set up polymorphic relations', function(done) { var ds = new DataSource('memory'); - var Author = ds.define('Author', { name: String }, { relations: { - pictures: { type: 'hasMany', model: 'Picture', polymorphic: 'imageable' }, + var Author = ds.define('Author', {name: String}, {relations: { + pictures: {type: 'hasMany', model: 'Picture', polymorphic: 'imageable'}, }}); - var Picture = ds.define('Picture', { name: String }, { relations: { - imageable: { type: 'belongsTo', polymorphic: true }, + var Picture = ds.define('Picture', {name: String}, {relations: { + imageable: {type: 'belongsTo', polymorphic: true}, }}); assert(Author.relations['pictures']); @@ -1103,9 +1105,9 @@ describe('Load models with relations', function() { it('should set up foreign key with the correct type', function(done) { var ds = new DataSource('memory'); - var User = ds.define('User', { name: String, id: { type: String, id: true }}); - var Post = ds.define('Post', { content: String }, { relations: { - user: { type: 'belongsTo', model: 'User' }}, + var User = ds.define('User', {name: String, id: {type: String, id: true}}); + var Post = ds.define('Post', {content: String}, {relations: { + user: {type: 'belongsTo', model: 'User'}}, }); var fk = Post.definition.properties['userId']; @@ -1118,22 +1120,22 @@ describe('Load models with relations', function() { it('should set up hasMany and belongsTo relations', function(done) { var ds = new DataSource('memory'); - var User = ds.define('User', { name: String }, { + var User = ds.define('User', {name: String}, { relations: { - posts: { type: 'hasMany', model: 'Post' }, - accounts: { type: 'hasMany', model: 'Account' }, + posts: {type: 'hasMany', model: 'Post'}, + accounts: {type: 'hasMany', model: 'Account'}, }, }); assert(!User.relations['posts']); assert(!User.relations['accounts']); - var Post = ds.define('Post', { userId: Number, content: String }, { - relations: { user: { type: 'belongsTo', model: 'User' }}, + var Post = ds.define('Post', {userId: Number, content: String}, { + relations: {user: {type: 'belongsTo', model: 'User'}}, }); - var Account = ds.define('Account', { userId: Number, type: String }, { - relations: { user: { type: 'belongsTo', model: 'User' }}, + var Account = ds.define('Account', {userId: Number, type: String}, { + relations: {user: {type: 'belongsTo', model: 'User'}}, }); assert(Post.relations['user']); @@ -1173,11 +1175,11 @@ describe('Load models with relations', function() { it('should throw if a relation is missing type', function(done) { var ds = new DataSource('memory'); - var Post = ds.define('Post', { userId: Number, content: String }); + var Post = ds.define('Post', {userId: Number, content: String}); try { - var User = ds.define('User', { name: String }, { - relations: { posts: { model: 'Post' }}, + var User = ds.define('User', {name: String}, { + relations: {posts: {model: 'Post'}}, }); } catch (e) { done(); @@ -1188,11 +1190,11 @@ describe('Load models with relations', function() { it('should throw if the relation type is invalid', function(done) { var ds = new DataSource('memory'); - var Post = ds.define('Post', { userId: Number, content: String }); + var Post = ds.define('Post', {userId: Number, content: String}); try { - var User = ds.define('User', { name: String }, { - relations: { posts: { type: 'hasXYZ', model: 'Post' }}, + var User = ds.define('User', {name: String}, { + relations: {posts: {type: 'hasXYZ', model: 'Post'}}, }); } catch (e) { done(); @@ -1206,7 +1208,7 @@ describe('Load models with relations', function() { name: String, }, { relations: { - patients: { model: 'Patient', type: 'hasMany', through: 'Appointment' }, + patients: {model: 'Patient', type: 'hasMany', through: 'Appointment'}, }, }); @@ -1214,7 +1216,7 @@ describe('Load models with relations', function() { name: String, }, { relations: { - physicians: { model: 'Physician', type: 'hasMany', through: 'Appointment' }, + physicians: {model: 'Physician', type: 'hasMany', through: 'Appointment'}, }, }); @@ -1227,8 +1229,8 @@ describe('Load models with relations', function() { appointmentDate: Date, }, { relations: { - patient: { type: 'belongsTo', model: 'Patient' }, - physician: { type: 'belongsTo', model: 'Physician' }, + patient: {type: 'belongsTo', model: 'Patient'}, + physician: {type: 'belongsTo', model: 'Physician'}, }, }); @@ -1243,7 +1245,7 @@ describe('Load models with relations', function() { name: String, }, { relations: { - patients: { model: 'Patient', type: 'hasMany', foreignKey: 'leftId', through: 'Appointment' }, + patients: {model: 'Patient', type: 'hasMany', foreignKey: 'leftId', through: 'Appointment'}, }, }); @@ -1251,7 +1253,7 @@ describe('Load models with relations', function() { name: String, }, { relations: { - physicians: { model: 'Physician', type: 'hasMany', foreignKey: 'rightId', through: 'Appointment' }, + physicians: {model: 'Physician', type: 'hasMany', foreignKey: 'rightId', through: 'Appointment'}, }, }); @@ -1261,8 +1263,8 @@ describe('Load models with relations', function() { appointmentDate: Date, }, { relations: { - patient: { type: 'belongsTo', model: 'Patient' }, - physician: { type: 'belongsTo', model: 'Physician' }, + patient: {type: 'belongsTo', model: 'Patient'}, + physician: {type: 'belongsTo', model: 'Physician'}, }, }); @@ -1275,9 +1277,9 @@ describe('Load models with relations', function() { var ds = new DataSource('memory'); var modelBuilder = new ModelBuilder(); - var Post = modelBuilder.define('Post', { userId: Number, content: String }); - var User = modelBuilder.define('User', { name: String }, { - relations: { posts: { type: 'hasMany', model: 'Post' }, + var Post = modelBuilder.define('Post', {userId: Number, content: String}); + var User = modelBuilder.define('User', {name: String}, { + relations: {posts: {type: 'hasMany', model: 'Post'}, }}); assert(!User.relations['posts']); @@ -1292,12 +1294,12 @@ describe('Load models with relations', function() { describe('Model with scopes', function() { it('should create scopes', function(done) { var ds = new DataSource('memory'); - var User = ds.define('User', { name: String, vip: Boolean, age: Number }, - { scopes: { vips: { where: { vip: true }}, top5: { limit: 5, order: 'age' }}}); + var User = ds.define('User', {name: String, vip: Boolean, age: Number}, + {scopes: {vips: {where: {vip: true}}, top5: {limit: 5, order: 'age'}}}); var users = []; for (var i = 0; i < 10; i++) { - users.push({ name: 'User' + i, vip: i % 3 === 0, age: 20 + i * 2 }); + users.push({name: 'User' + i, vip: i % 3 === 0, age: 20 + i * 2}); } async.each(users, function(user, callback) { User.create(user, callback); @@ -1317,12 +1319,12 @@ describe('Model with scopes', function() { }); describe('DataAccessObject', function() { - var ds, model, where, error; + var ds, model, where, error, filter; before(function() { ds = new DataSource('memory'); model = ds.createModel('M1', { - id: { type: String, id: true }, + id: {type: String, id: true}, age: Number, vip: Boolean, date: Date, @@ -1336,10 +1338,10 @@ describe('DataAccessObject', function() { }); it('should be able to coerce where clause for string types', function() { - where = model._coerce({ id: 1 }); - assert.deepEqual(where, { id: '1' }); - where = model._coerce({ id: '1' }); - assert.deepEqual(where, { id: '1' }); + where = model._coerce({id: 1}); + assert.deepEqual(where, {id: '1'}); + where = model._coerce({id: '1'}); + assert.deepEqual(where, {id: '1'}); // Mockup MongoDB ObjectID function ObjectID(id) { @@ -1350,73 +1352,73 @@ describe('DataAccessObject', function() { return this.id; }; - where = model._coerce({ id: new ObjectID('1') }); - assert.deepEqual(where, { id: '1' }); + where = model._coerce({id: new ObjectID('1')}); + assert.deepEqual(where, {id: '1'}); }); it('should be able to coerce where clause for number types', function() { - where = model._coerce({ age: '10' }); - assert.deepEqual(where, { age: 10 }); + where = model._coerce({age: '10'}); + assert.deepEqual(where, {age: 10}); - where = model._coerce({ age: 10 }); - assert.deepEqual(where, { age: 10 }); + where = model._coerce({age: 10}); + assert.deepEqual(where, {age: 10}); - where = model._coerce({ age: { gt: 10 }}); - assert.deepEqual(where, { age: { gt: 10 }}); + where = model._coerce({age: {gt: 10}}); + assert.deepEqual(where, {age: {gt: 10}}); - where = model._coerce({ age: { gt: '10' }}); - assert.deepEqual(where, { age: { gt: 10 }}); + where = model._coerce({age: {gt: '10'}}); + assert.deepEqual(where, {age: {gt: 10}}); - where = model._coerce({ age: { between: ['10', '20'] }}); - assert.deepEqual(where, { age: { between: [10, 20] }}); + where = model._coerce({age: {between: ['10', '20']}}); + assert.deepEqual(where, {age: {between: [10, 20]}}); }); it('should be able to coerce where clause for array types', function() { - where = model._coerce({ scores: ['10', '20'] }); - assert.deepEqual(where, { scores: [10, 20] }); + where = model._coerce({scores: ['10', '20']}); + assert.deepEqual(where, {scores: [10, 20]}); }); it('should be able to coerce where clause for date types', function() { var d = new Date(); - where = model._coerce({ date: d }); - assert.deepEqual(where, { date: d }); + where = model._coerce({date: d}); + assert.deepEqual(where, {date: d}); - where = model._coerce({ date: d.toISOString() }); - assert.deepEqual(where, { date: d }); + where = model._coerce({date: d.toISOString()}); + assert.deepEqual(where, {date: d}); }); it('should be able to coerce where clause for boolean types', function() { - where = model._coerce({ vip: 'true' }); - assert.deepEqual(where, { vip: true }); + where = model._coerce({vip: 'true'}); + assert.deepEqual(where, {vip: true}); - where = model._coerce({ vip: true }); - assert.deepEqual(where, { vip: true }); + where = model._coerce({vip: true}); + assert.deepEqual(where, {vip: true}); - where = model._coerce({ vip: 'false' }); - assert.deepEqual(where, { vip: false }); + where = model._coerce({vip: 'false'}); + assert.deepEqual(where, {vip: false}); - where = model._coerce({ vip: false }); - assert.deepEqual(where, { vip: false }); + where = model._coerce({vip: false}); + assert.deepEqual(where, {vip: false}); - where = model._coerce({ vip: '1' }); - assert.deepEqual(where, { vip: true }); + where = model._coerce({vip: '1'}); + assert.deepEqual(where, {vip: true}); - where = model._coerce({ vip: 0 }); - assert.deepEqual(where, { vip: false }); + where = model._coerce({vip: 0}); + assert.deepEqual(where, {vip: false}); - where = model._coerce({ vip: '' }); - assert.deepEqual(where, { vip: false }); + where = model._coerce({vip: ''}); + assert.deepEqual(where, {vip: false}); }); it('should be able to coerce where clause with and operators', function() { - where = model._coerce({ and: [{ age: '10' }, { vip: 'true' }] }); - assert.deepEqual(where, { and: [{ age: 10 }, { vip: true }] }); + where = model._coerce({and: [{age: '10'}, {vip: 'true'}]}); + assert.deepEqual(where, {and: [{age: 10}, {vip: true}]}); }); it('should be able to coerce where clause with or operators', function() { - where = model._coerce({ or: [{ age: '10' }, { vip: 'true' }] }); - assert.deepEqual(where, { or: [{ age: 10 }, { vip: true }] }); + where = model._coerce({or: [{age: '10'}, {vip: 'true'}]}); + assert.deepEqual(where, {or: [{age: 10}, {vip: true}]}); }); it('should throw if the where property is not an object', function() { @@ -1433,7 +1435,7 @@ describe('DataAccessObject', function() { try { // The where clause cannot be an array model._coerce([ - { vip: true }, + {vip: true}, ]); } catch (err) { error = err; @@ -1444,7 +1446,7 @@ describe('DataAccessObject', function() { it('should throw if the and operator does not take an array', function() { try { // The and operator only takes an array of objects - model._coerce({ and: { x: 1 }}); + model._coerce({and: {x: 1}}); } catch (err) { error = err; } @@ -1454,7 +1456,7 @@ describe('DataAccessObject', function() { it('should throw if the or operator does not take an array', function() { try { // The or operator only takes an array of objects - model._coerce({ or: { x: 1 }}); + model._coerce({or: {x: 1}}); } catch (err) { error = err; } @@ -1464,7 +1466,7 @@ describe('DataAccessObject', function() { it('should throw if the or operator does not take an array of objects', function() { try { // The or operator only takes an array of objects - model._coerce({ or: ['x'] }); + model._coerce({or: ['x']}); } catch (err) { error = err; } @@ -1485,7 +1487,7 @@ describe('DataAccessObject', function() { it('should throw if filter.limit property is not a number', function() { try { // The limit param must be a valid number - filter = model._normalize({ limit: 'x' }); + filter = model._normalize({limit: 'x'}); } catch (err) { error = err; } @@ -1495,7 +1497,7 @@ describe('DataAccessObject', function() { it('should throw if filter.limit property is nagative', function() { try { // The limit param must be a valid number - filter = model._normalize({ limit: -1 }); + filter = model._normalize({limit: -1}); } catch (err) { error = err; } @@ -1505,7 +1507,7 @@ describe('DataAccessObject', function() { it('should throw if filter.limit property is not an integer', function() { try { // The limit param must be a valid number - filter = model._normalize({ limit: 5.8 }); + filter = model._normalize({limit: 5.8}); } catch (err) { error = err; } @@ -1515,7 +1517,7 @@ describe('DataAccessObject', function() { it('should throw if filter.offset property is not a number', function() { try { // The limit param must be a valid number - filter = model._normalize({ offset: 'x' }); + filter = model._normalize({offset: 'x'}); } catch (err) { error = err; } @@ -1525,7 +1527,7 @@ describe('DataAccessObject', function() { it('should throw if filter.skip property is not a number', function() { try { // The limit param must be a valid number - filter = model._normalize({ skip: '_' }); + filter = model._normalize({skip: '_'}); } catch (err) { error = err; } @@ -1533,56 +1535,56 @@ describe('DataAccessObject', function() { }); it('should normalize limit/offset/skip', function() { - filter = model._normalize({ limit: '10', skip: 5 }); - assert.deepEqual(filter, { limit: 10, offset: 5, skip: 5 }); + filter = model._normalize({limit: '10', skip: 5}); + assert.deepEqual(filter, {limit: 10, offset: 5, skip: 5}); }); it('should set the default value for limit', function() { - filter = model._normalize({ skip: 5 }); - assert.deepEqual(filter, { limit: 100, offset: 5, skip: 5 }); + filter = model._normalize({skip: 5}); + assert.deepEqual(filter, {limit: 100, offset: 5, skip: 5}); }); it('should apply settings for handling undefined', function() { - filter = model._normalize({ filter: { x: undefined }}); - assert.deepEqual(filter, { filter: {}}); + filter = model._normalize({filter: {x: undefined}}); + assert.deepEqual(filter, {filter: {}}); ds.settings.normalizeUndefinedInQuery = 'ignore'; - filter = model._normalize({ filter: { x: undefined }}); - assert.deepEqual(filter, { filter: {}}, 'Should ignore undefined'); + filter = model._normalize({filter: {x: undefined}}); + assert.deepEqual(filter, {filter: {}}, 'Should ignore undefined'); ds.settings.normalizeUndefinedInQuery = 'nullify'; - filter = model._normalize({ filter: { x: undefined }}); - assert.deepEqual(filter, { filter: { x: null }}, 'Should nullify undefined'); + filter = model._normalize({filter: {x: undefined}}); + assert.deepEqual(filter, {filter: {x: null}}, 'Should nullify undefined'); ds.settings.normalizeUndefinedInQuery = 'throw'; - (function() { model._normalize({ filter: { x: undefined }}); }).should.throw(/`undefined` in query/); + (function() { model._normalize({filter: {x: undefined}}); }).should.throw(/`undefined` in query/); }); it('should skip GeoPoint', function() { - where = model._coerce({ location: { near: { lng: 10, lat: 20 }, maxDistance: 20 }}); - assert.deepEqual(where, { location: { near: { lng: 10, lat: 20 }, maxDistance: 20 }}); + where = model._coerce({location: {near: {lng: 10, lat: 20}, maxDistance: 20}}); + assert.deepEqual(where, {location: {near: {lng: 10, lat: 20}, maxDistance: 20}}); }); it('should skip null values', function() { - where = model._coerce({ date: null }); - assert.deepEqual(where, { date: null }); + where = model._coerce({date: null}); + assert.deepEqual(where, {date: null}); }); it('should skip undefined values', function() { - where = model._coerce({ date: undefined }); - assert.deepEqual(where, { date: undefined }); + where = model._coerce({date: undefined}); + assert.deepEqual(where, {date: undefined}); }); it('should skip conversion if a simple property produces NaN for numbers', function() { - where = model._coerce({ age: 'xyz' }); - assert.deepEqual(where, { age: 'xyz' }); + where = model._coerce({age: 'xyz'}); + assert.deepEqual(where, {age: 'xyz'}); }); it('should skip conversion if an array property produces NaN for numbers', function() { - where = model._coerce({ age: { inq: ['xyz', '12'] }}); - assert.deepEqual(where, { age: { inq: ['xyz', 12] }}); + where = model._coerce({age: {inq: ['xyz', '12']}}); + assert.deepEqual(where, {age: {inq: ['xyz', 12]}}); }); // settings @@ -1632,7 +1634,7 @@ describe('Load models from json', function() { models.should.have.property('AnonymousModel_0'); models.AnonymousModel_0.should.have.property('modelName', 'AnonymousModel_0'); - var m1 = new models.AnonymousModel_0({ title: 'Test' }); + var m1 = new models.AnonymousModel_0({title: 'Test'}); m1.should.have.property('title', 'Test'); m1.should.have.property('author', 'Raymond'); @@ -1669,7 +1671,7 @@ describe('Load models from json', function() { modelBuilder.defaultModelBaseClass = User; - var Customer = modelBuilder.define('Customer', { customerId: { type: String, id: true }}); + var Customer = modelBuilder.define('Customer', {customerId: {type: String, id: true}}); assert(Customer.prototype instanceof User); }); @@ -1685,7 +1687,7 @@ describe('Load models from json', function() { }); var Customer = modelBuilder.define('Customer', - { customerId: { type: String, id: true }}, {}, User); + {customerId: {type: String, id: true}}, {}, User); assert(Customer.prototype instanceof User); }); @@ -1700,9 +1702,9 @@ describe('Load models from json', function() { age: Number, }); - var Customer = User.extend('Customer', { customerId: { type: String, id: true }}); + var Customer = User.extend('Customer', {customerId: {type: String, id: true}}); - var customer = new Customer({ name: 'Joe', age: 20, customerId: 'c01' }); + var customer = new Customer({name: 'Joe', age: 20, customerId: 'c01'}); customer.should.be.type('object').and.have.property('name', 'Joe'); customer.should.have.property('name', 'Joe'); @@ -1756,7 +1758,7 @@ describe('Load models from json', function() { }); var Customer = User.extend('Customer', - { customerId: { type: String, id: true }}, + {customerId: {type: String, id: true}}, { defaultPermission: 'DENY', acls: [ @@ -1837,12 +1839,12 @@ describe('DataSource constructor', function() { }); it('Takes settings object', function() { - var ds = new DataSource({ connector: 'memory' }); + var ds = new DataSource({connector: 'memory'}); assert.equal(ds.connector.name, 'memory'); }); it('Takes settings object and name', function() { - var ds = new DataSource('x', { connector: 'memory' }); + var ds = new DataSource('x', {connector: 'memory'}); assert.equal(ds.connector.name, 'memory'); }); }); @@ -1851,7 +1853,7 @@ describe('ModelBuilder options.models', function() { it('should inject model classes from models', function() { var builder = new ModelBuilder(); var M1 = builder.define('M1'); - var M2 = builder.define('M2', {}, { models: { + var M2 = builder.define('M2', {}, {models: { 'M1': M1, }}); @@ -1861,7 +1863,7 @@ describe('ModelBuilder options.models', function() { it('should inject model classes by name in the models', function() { var builder = new ModelBuilder(); var M1 = builder.define('M1'); - var M2 = builder.define('M2', {}, { models: { + var M2 = builder.define('M2', {}, {models: { 'M1': 'M1', }}); @@ -1871,7 +1873,7 @@ describe('ModelBuilder options.models', function() { it('should inject model classes by name in the models before the class is defined', function() { var builder = new ModelBuilder(); - var M2 = builder.define('M2', {}, { models: { + var M2 = builder.define('M2', {}, {models: { 'M1': 'M1', }}); assert(M2.M1, 'M1 should be injected to M2'); diff --git a/test/manipulation.test.js b/test/manipulation.test.js index 6857190a..ac25c3da 100644 --- a/test/manipulation.test.js +++ b/test/manipulation.test.js @@ -4,6 +4,7 @@ // License text available at https://opensource.org/licenses/MIT // This test written in mocha+should.js +'use strict'; var async = require('async'); var should = require('./init.js'); @@ -21,10 +22,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); @@ -34,8 +35,10 @@ describe('manipulation', function() { // to reproduce problems related to properties with dynamic setters // For the purpose of the tests, we use a counter instead of a hash fn. var StubUser; + var stubPasswordCounter; + 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; @@ -62,13 +65,14 @@ describe('manipulation', function() { }); describe('forceId', function() { + var TestForceId; before(function(done) { TestForceId = db.define('TestForceId'); db.automigrate('TestForceId', done); }); it('it defaults to forceId:true for generated id property', function(done) { - TestForceId.create({ id: 1 }, function(err, t) { + TestForceId.create({id: 1}, function(err, t) { should.exist(err); err.message.should.match(/can\'t be set/); done(); @@ -77,7 +81,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); @@ -90,7 +94,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); @@ -105,7 +109,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) { @@ -117,7 +121,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() @@ -139,7 +143,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']); @@ -151,7 +155,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) { @@ -164,7 +168,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); @@ -177,7 +181,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) { @@ -200,7 +204,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) { @@ -244,8 +248,8 @@ describe('manipulation', function() { it('should create batch of objects', function(done) { var batch = [ - { name: 'Shaltay' }, - { name: 'Boltay' }, + {name: 'Shaltay'}, + {name: 'Boltay'}, {}, ]; var res = Person.create(batch, function(e, ps) { @@ -275,14 +279,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) { @@ -290,14 +294,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({ @@ -323,13 +327,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 }, { forceId: false }); + var Product = db.define('ProductTest', {name: String}, {forceId: false}); 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.')); } @@ -404,7 +408,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(); }); @@ -425,7 +429,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(); @@ -453,7 +457,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) { @@ -474,7 +478,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(); @@ -489,7 +493,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); @@ -528,7 +532,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) { @@ -544,7 +548,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); @@ -559,7 +563,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'); @@ -577,7 +581,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'); @@ -592,7 +596,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) { @@ -611,7 +615,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) { @@ -625,7 +629,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(); @@ -633,7 +637,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) { @@ -646,7 +650,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) { @@ -665,7 +669,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(); }); @@ -677,8 +681,8 @@ describe('manipulation', function() { before('prepare "Post" and "Todo" models', function(done) { Post = db.define('Post', { - title: { type: String, id: true }, - content: { type: String }, + title: {type: String, id: true}, + content: {type: String}, }); Todo = db.define('Todo', { content: String, @@ -695,7 +699,7 @@ describe('manipulation', function() { }); it('creates a model when one does not exist', function(done) { - Todo.updateOrCreate({ content: 'a' }, function(err, data) { + Todo.updateOrCreate({content: 'a'}, function(err, data) { if (err) return done(err); Todo.findById(data.id, function(err, todo) { @@ -709,8 +713,8 @@ describe('manipulation', function() { }); it('updates a model if it exists', function(done) { - Todo.create({ content: 'a' }, function(err, todo) { - Todo.updateOrCreate({ id: todo.id, content: 'b' }, function(err, data) { + Todo.create({content: 'a'}, function(err, todo) { + Todo.updateOrCreate({id: todo.id, content: 'b'}, function(err, data) { if (err) return done(err); should.exist(data); @@ -725,7 +729,7 @@ describe('manipulation', function() { }); it('throws error for queries with array input', function(done) { - Todo.updateOrCreate([{ content: 'a' }], function(err, data) { + Todo.updateOrCreate([{content: 'a'}], function(err, data) { should.exist(err); err.message.should.containEql('bulk'); should.not.exist(data); @@ -735,7 +739,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) { @@ -747,9 +751,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'); @@ -764,7 +768,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({ @@ -774,7 +778,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(); @@ -790,8 +794,8 @@ describe('manipulation', function() { it('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); @@ -821,7 +825,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); @@ -837,15 +841,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], - }, { forceId: false }); + }, {forceId: false}); 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); @@ -867,8 +871,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); @@ -889,7 +893,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(); @@ -919,14 +923,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); @@ -949,7 +953,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(); @@ -977,8 +981,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(); @@ -1006,7 +1010,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); @@ -1025,8 +1029,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'); @@ -1050,9 +1054,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); }); @@ -1062,7 +1066,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) { @@ -1074,10 +1078,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) { @@ -1091,7 +1095,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({ @@ -1100,8 +1104,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(); @@ -1117,13 +1121,13 @@ describe('manipulation', function() { it('updates specific instances when PK is not an auto-generated id', function(done) { Person.create([ - { name: 'nameA', city: 'cityA' }, - { name: 'nameB', city: 'cityB' }, + {name: 'nameA', city: 'cityA'}, + {name: 'nameB', city: 'cityB'}, ], function(err, instance) { if (err) return done(err); - Person.upsertWithWhere({ name: 'nameA' }, - { city: 'newCity' }, + Person.upsertWithWhere({name: 'nameA'}, + {city: 'newCity'}, function(err, instance) { if (err) return done(err); var result = instance.toObject(); @@ -1146,8 +1150,8 @@ describe('manipulation', function() { }); it('should allow save() of the created instance', function(done) { - Person.upsertWithWhere({ id: 999 }, - { name: 'a-name' }, + Person.upsertWithWhere({id: 999}, + {name: 'a-name'}, function(err, inst) { if (err) return done(err); inst.save(done); @@ -1155,8 +1159,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); @@ -1177,8 +1181,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); @@ -1199,13 +1203,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); @@ -1226,13 +1230,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); @@ -1253,8 +1257,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(); @@ -1262,7 +1266,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) { @@ -1278,11 +1282,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.' + @@ -1295,12 +1299,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); @@ -1323,8 +1327,8 @@ 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); @@ -1333,7 +1337,7 @@ describe('manipulation', function() { // TODO(bajtos) add API to lib/observer - remove observers for all hooks Post._observers = {}; 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(); @@ -1343,9 +1347,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'); @@ -1363,7 +1367,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) { @@ -1381,7 +1385,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); @@ -1395,7 +1399,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` @@ -1416,7 +1420,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) { if (err) return done(err); Post._warned.cannotOverwritePKInLoadedHook.should.equal(true); data.id.should.equal(postInstance.id); @@ -1428,7 +1432,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); @@ -1448,7 +1452,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); @@ -1468,7 +1472,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); @@ -1480,7 +1484,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'); @@ -1492,7 +1496,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'); @@ -1512,7 +1516,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); @@ -1526,8 +1530,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); @@ -1540,7 +1544,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); @@ -1558,8 +1562,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); @@ -1661,13 +1665,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(); @@ -1678,7 +1682,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) { @@ -1793,7 +1797,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'; @@ -1806,7 +1810,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); }); @@ -1830,7 +1834,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); }); @@ -1852,7 +1856,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); }); @@ -1874,7 +1878,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); }); @@ -1893,7 +1897,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); }); @@ -1912,7 +1916,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); }); @@ -1935,68 +1939,68 @@ 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')); @@ -2035,11 +2039,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(); @@ -2049,11 +2053,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'); @@ -2064,13 +2068,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(); @@ -2081,11 +2085,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'); @@ -2096,7 +2100,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(); @@ -2107,12 +2111,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([ diff --git a/test/memory.test.js b/test/memory.test.js index 3a829f38..0bd3ba2c 100644 --- a/test/memory.test.js +++ b/test/memory.test.js @@ -3,6 +3,7 @@ // 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; var path = require('path'); @@ -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); @@ -145,13 +146,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, @@ -167,7 +168,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(); @@ -175,7 +176,7 @@ describe('Memory connector', function() { }); it('should allow to find using like with regexp', function(done) { - User.find({ where: { name: { like: /.*St.*/ }}}, function(err, posts) { + User.find({where: {name: {like: /.*St.*/}}}, function(err, posts) { should.not.exist(err); posts.should.have.property('length', 2); done(); @@ -183,7 +184,7 @@ describe('Memory connector', function() { }); it('should support like for no match', function(done) { - User.find({ where: { name: { like: 'M%XY' }}}, function(err, posts) { + User.find({where: {name: {like: 'M%XY'}}}, function(err, posts) { should.not.exist(err); posts.should.have.property('length', 0); done(); @@ -191,7 +192,7 @@ describe('Memory connector', function() { }); it('should allow to find using nlike', function(done) { - User.find({ where: { name: { nlike: '%St%' }}}, function(err, posts) { + User.find({where: {name: {nlike: '%St%'}}}, function(err, posts) { should.not.exist(err); posts.should.have.property('length', 4); done(); @@ -199,7 +200,7 @@ describe('Memory connector', function() { }); it('should allow to find using nlike with regexp', function(done) { - User.find({ where: { name: { nlike: /.*St.*/ }}}, function(err, posts) { + User.find({where: {name: {nlike: /.*St.*/}}}, function(err, posts) { should.not.exist(err); posts.should.have.property('length', 4); done(); @@ -207,7 +208,7 @@ describe('Memory connector', function() { }); it('should support nlike for no match', function(done) { - User.find({ where: { name: { nlike: 'M%XY' }}}, function(err, posts) { + User.find({where: {name: {nlike: 'M%XY'}}}, function(err, posts) { should.not.exist(err); posts.should.have.property('length', 6); done(); @@ -215,56 +216,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'); @@ -273,7 +274,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(); @@ -281,7 +282,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'); @@ -290,9 +291,9 @@ describe('Memory connector', function() { }); it('should successfully extract 2 users using implied and & and', function(done) { - User.find({ where: { + 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); should(users[0].name).be.equal('John Lennon'); @@ -301,8 +302,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(); @@ -310,7 +311,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(); @@ -349,7 +350,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); @@ -360,7 +361,7 @@ describe('Memory connector', function() { it('should successfully extract 3 users with inq', function(done) { User.find({ - where: { seq: { inq: [0, 1, 5] }}, + where: {seq: {inq: [0, 1, 5]}}, }, function(err, users) { should.not.exist(err); users.length.should.be.equal(3); @@ -370,7 +371,7 @@ describe('Memory connector', function() { it('should successfully extract 4 users with nin', function(done) { User.find({ - where: { seq: { nin: [2, 3] }}, + where: {seq: {nin: [2, 3]}}, }, function(err, users) { should.not.exist(err); users.length.should.be.equal(4); @@ -379,7 +380,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(); @@ -387,7 +388,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); @@ -396,7 +397,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); @@ -406,14 +407,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++) { @@ -424,7 +425,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++) { @@ -437,7 +438,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++) { @@ -449,7 +450,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'); @@ -458,7 +459,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'); @@ -467,7 +468,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'); @@ -476,7 +477,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); @@ -486,7 +487,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++) { @@ -497,7 +498,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'); @@ -507,7 +508,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++) { @@ -518,7 +519,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); @@ -529,8 +530,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); @@ -557,9 +558,9 @@ describe('Memory connector', function() { zipCode: '95131', }, friends: [ - { name: 'Paul McCartney' }, - { name: 'George Harrison' }, - { name: 'Ringo Starr' }, + {name: 'Paul McCartney'}, + {name: 'George Harrison'}, + {name: 'Ringo Starr'}, ], children: ['Sean', 'Julian'], }, @@ -578,16 +579,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(); }); }); @@ -725,7 +726,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, }); @@ -734,8 +735,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); @@ -868,7 +869,7 @@ describe('Memory connector', function() { }); describe('Optimized connector', function() { - var ds = new DataSource({ connector: Memory }); + var ds = new DataSource({connector: Memory}); // optimized methods ds.connector.findOrCreate = function(model, query, data, callback) { @@ -880,23 +881,23 @@ describe('Optimized connector', function() { }.bind(this)); }; - require('./persistence-hooks.suite')(ds, should, { replaceOrCreateReportsNewInstance: true }); + require('./persistence-hooks.suite')(ds, should, {replaceOrCreateReportsNewInstance: true}); }); describe('Unoptimized connector', function() { - var ds = new DataSource({ connector: Memory }); + var ds = new DataSource({connector: Memory}); // disable optimized methods ds.connector.updateOrCreate = false; ds.connector.findOrCreate = false; - require('./persistence-hooks.suite')(ds, should, { replaceOrCreateReportsNewInstance: true }); + require('./persistence-hooks.suite')(ds, should, {replaceOrCreateReportsNewInstance: true}); }); describe('Memory connector with options', function() { var ds, savedOptions = {}, Post; before(function() { - ds = new DataSource({ connector: 'memory' }); + ds = new DataSource({connector: 'memory'}); ds.connector.create = function(model, data, options, cb) { savedOptions.create = options; process.nextTick(function() { @@ -907,14 +908,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'}]); }); }; @@ -925,15 +926,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); @@ -941,7 +942,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); @@ -949,16 +950,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); @@ -981,7 +982,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); @@ -1003,7 +1004,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(); diff --git a/test/mixins.test.js b/test/mixins.test.js index 045c6e7a..e3f028aa 100644 --- a/test/mixins.test.js +++ b/test/mixins.test.js @@ -4,6 +4,7 @@ // License text available at https://opensource.org/licenses/MIT // This test written in mocha+should.js +'use strict'; var should = require('./init.js'); var jdb = require('../'); @@ -16,8 +17,8 @@ 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) { @@ -64,45 +65,45 @@ 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 fail to apply an undefined mixin class', function() { - var memory = new DataSource('mem', { connector: Memory }, modelBuilder); + var memory = new DataSource('mem', {connector: Memory}, modelBuilder); function applyMixin() { - memory.createModel('Item', { name: 'string' }, { - mixins: { UndefinedMixin: true }, + memory.createModel('Item', {name: 'string'}, { + mixins: {UndefinedMixin: true}, }); } should.throws(applyMixin, 'failed to apply undefined mixin class'); }); 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 }, + 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; @@ -110,23 +111,23 @@ 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(); }); }); it('should fail to apply undefined mixin', function() { - 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'}); function applyMixin() { - Item.mixin('UndefinedMixin', { foo: 'bar' }); + Item.mixin('UndefinedMixin', {foo: 'bar'}); } should.throws(applyMixin, 'failed to apply undefined mixin'); }); @@ -137,12 +138,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() { diff --git a/test/mock-connectors.js b/test/mock-connectors.js index ce228b1e..6af4c887 100644 --- a/test/mock-connectors.js +++ b/test/mock-connectors.js @@ -3,6 +3,7 @@ // This file is licensed under the MIT License. // License text available at https://opensource.org/licenses/MIT +'use strict'; module.exports = { // connector which uses custom field settings @@ -19,7 +20,7 @@ module.exports = { required: false, // custom properties listed under a key matching the connector name - custom: { storage: 'quantum' }, + custom: {storage: 'quantum'}, }, ]); }, diff --git a/test/model-definition.test.js b/test/model-definition.test.js index 9a6b2d01..535c5f64 100644 --- a/test/model-definition.test.js +++ b/test/model-definition.test.js @@ -4,6 +4,7 @@ // License text available at https://opensource.org/licenses/MIT // This test written in mocha+should.js +'use strict'; var should = require('./init.js'); var assert = require('assert'); @@ -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) { @@ -67,7 +68,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); @@ -77,7 +78,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(); @@ -116,10 +117,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(); @@ -211,7 +212,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, @@ -228,8 +229,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, @@ -250,9 +251,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'); @@ -283,7 +284,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); @@ -292,7 +293,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); @@ -315,7 +316,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', @@ -324,7 +325,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'); @@ -355,7 +356,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', @@ -364,7 +365,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'); @@ -376,7 +377,7 @@ describe('ModelDefinition class', function() { }); it('should throw error for property names containing dot', function() { - (function() { memory.createModel('Dotted', { 'dot.name': String }); }) + (function() { memory.createModel('Dotted', {'dot.name': String}); }) .should .throw(/dot\(s\).*Dotted.*dot\.name/); }); @@ -385,7 +386,7 @@ describe('ModelDefinition class', function() { var message = 'deprecation not reported'; process.once('deprecation', function(err) { message = err.message; }); - memory.createModel('Ctor', { 'constructor': String }); + memory.createModel('Ctor', {'constructor': String}); message.should.match(/Property name should not be "constructor" in Model: Ctor/); }); @@ -393,7 +394,7 @@ describe('ModelDefinition class', function() { it('should throw error for dynamic property names containing dot', function(done) { var Model = memory.createModel('DynamicDotted'); - Model.create({ 'dot.name': 'dot.value' }, function(err) { + Model.create({'dot.name': 'dot.value'}, function(err) { err.should.be.instanceOf(Error); err.message.should.match(/dot\(s\).*DynamicDotted.*dot\.name/); done(); @@ -402,7 +403,7 @@ describe('ModelDefinition class', function() { it('should throw error for dynamic property named constructor', function(done) { var Model = memory.createModel('DynamicCtor'); - Model.create({ 'constructor': 'myCtor' }, function(err) { + Model.create({'constructor': 'myCtor'}, function(err) { assert.equal(err.message, 'Property name "constructor" is not allowed in DynamicCtor data'); done(); }); diff --git a/test/operation-hooks.suite/embeds-many-create.suite.js b/test/operation-hooks.suite/embeds-many-create.suite.js index 53973fe3..b6dfcdec 100644 --- a/test/operation-hooks.suite/embeds-many-create.suite.js +++ b/test/operation-hooks.suite/embeds-many-create.suite.js @@ -3,6 +3,8 @@ // This file is licensed under the MIT License. // License text available at https://opensource.org/licenses/MIT +'use strict'; + var ValidationError = require('../..').ValidationError; var contextTestHelpers = require('../helpers/context-test-helpers'); @@ -18,7 +20,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 +30,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 +57,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 +113,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']}); }); }); diff --git a/test/operation-hooks.suite/embeds-many-destroy.suite.js b/test/operation-hooks.suite/embeds-many-destroy.suite.js index e4d08dd9..10e2f79e 100644 --- a/test/operation-hooks.suite/embeds-many-destroy.suite.js +++ b/test/operation-hooks.suite/embeds-many-destroy.suite.js @@ -3,6 +3,8 @@ // 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 +20,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 +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', {}); @@ -46,14 +48,14 @@ module.exports = function(dataSource, should, connectorCapabilities) { } }); - var ownerInstance, existingInstance; + var ownerInstance, existingInstance, existingItem, 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; }); diff --git a/test/operation-hooks.suite/embeds-many-update-by-id.suite.js b/test/operation-hooks.suite/embeds-many-update-by-id.suite.js index 5efae691..cdb4fb2f 100644 --- a/test/operation-hooks.suite/embeds-many-update-by-id.suite.js +++ b/test/operation-hooks.suite/embeds-many-update-by-id.suite.js @@ -3,6 +3,8 @@ // 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 +20,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 +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', {}); @@ -53,7 +55,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 +70,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 +127,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']}); }); }); diff --git a/test/operation-hooks.suite/embeds-one-create.suite.js b/test/operation-hooks.suite/embeds-one-create.suite.js index e5329eb9..c0405b0f 100644 --- a/test/operation-hooks.suite/embeds-one-create.suite.js +++ b/test/operation-hooks.suite/embeds-one-create.suite.js @@ -3,6 +3,8 @@ // This file is licensed under the MIT License. // License text available at https://opensource.org/licenses/MIT +'use strict'; + var ValidationError = require('../..').ValidationError; var contextTestHelpers = require('../helpers/context-test-helpers'); @@ -18,7 +20,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 +30,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 +57,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 +108,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']}); }); }); diff --git a/test/operation-hooks.suite/embeds-one-destroy.suite.js b/test/operation-hooks.suite/embeds-one-destroy.suite.js index c024e815..a25ddc02 100644 --- a/test/operation-hooks.suite/embeds-one-destroy.suite.js +++ b/test/operation-hooks.suite/embeds-one-destroy.suite.js @@ -3,6 +3,8 @@ // This file is licensed under the MIT License. // License text available at https://opensource.org/licenses/MIT +'use strict'; + var ValidationError = require('../..').ValidationError; var contextTestHelpers = require('../helpers/context-test-helpers'); @@ -17,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'); }); @@ -26,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', {}); @@ -45,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.embeddedItem.create(item).then(function(it) { existingItem = it; }); diff --git a/test/operation-hooks.suite/embeds-one-update.suite.js b/test/operation-hooks.suite/embeds-one-update.suite.js index ec8d8e66..c9900554 100644 --- a/test/operation-hooks.suite/embeds-one-update.suite.js +++ b/test/operation-hooks.suite/embeds-one-update.suite.js @@ -3,6 +3,8 @@ // This file is licensed under the MIT License. // License text available at https://opensource.org/licenses/MIT +'use strict'; + var ValidationError = require('../..').ValidationError; var contextTestHelpers = require('../helpers/context-test-helpers'); @@ -17,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'); }); @@ -26,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', {}); @@ -52,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.embeddedItem.create(item).then(function(it) { existingItem = it; }); @@ -63,7 +65,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 +117,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']}); }); }); diff --git a/test/operation-hooks.suite/index.js b/test/operation-hooks.suite/index.js index 1b9fcab7..3f43346d 100644 --- a/test/operation-hooks.suite/index.js +++ b/test/operation-hooks.suite/index.js @@ -1,3 +1,5 @@ +'use strict'; + var debug = require('debug')('test'); var fs = require('fs'); var path = require('path'); diff --git a/test/optional-validation.test.js b/test/optional-validation.test.js index 854dd608..2dba8d80 100644 --- a/test/optional-validation.test.js +++ b/test/optional-validation.test.js @@ -4,6 +4,7 @@ // License text available at https://opensource.org/licenses/MIT // This test written in mocha+should.js +'use strict'; var async = require('async'); var should = require('./init.js'); var db, User, options, ModelWithForceId, whereCount = 0; @@ -12,8 +13,8 @@ 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() { @@ -21,17 +22,17 @@ describe('optional-validation', function() { 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); }); @@ -55,7 +56,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); @@ -72,7 +73,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); @@ -87,36 +88,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); }); }); @@ -124,9 +125,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(); @@ -140,19 +141,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) { @@ -167,25 +168,25 @@ 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 }, + 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 }, + User.findOrCreate(getNewWhere(), INVALID_DATA, {validate: false}, expectCreateSuccess(INVALID_DATA, done)); }); it('should NOT throw on findOrCreate with validate:true with valid data', function(done) { - User.findOrCreate(getNewWhere(), VALID_DATA, { validate: true }, + 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 }, + User.findOrCreate(getNewWhere(), VALID_DATA, {validate: false}, expectCreateSuccess(done)); }); @@ -201,25 +202,25 @@ describe('optional-validation', function() { describe('method updateOrCreate on existing data', function() { it('should throw on updateOrCreate(id) with validate:true with invalid data', function(done) { - callUpdateOrCreateWithExistingUserId(null, { validate: true }, + callUpdateOrCreateWithExistingUserId(null, {validate: true}, expectValidationError(done)); }); it('should NOT throw on updateOrCreate(id) with validate:false with invalid data', function(done) { - callUpdateOrCreateWithExistingUserId(null, { validate: false }, + callUpdateOrCreateWithExistingUserId(null, {validate: false}, expectChangeSuccess(INVALID_DATA, done)); }); it('should NOT throw on updateOrCreate(id) with validate:true with valid data', function(done) { - callUpdateOrCreateWithExistingUserId(NEW_NAME, { validate: true }, + 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 }, + callUpdateOrCreateWithExistingUserId(NEW_NAME, {validate: false}, expectChangeSuccess(done)); }); @@ -236,25 +237,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)); }); }); @@ -274,25 +275,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)); }); }); @@ -304,7 +305,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)); }); }); }); @@ -320,19 +321,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) { @@ -347,25 +348,25 @@ 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 }, + 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 }, + User.findOrCreate(getNewWhere(), INVALID_DATA, {validate: false}, expectCreateSuccess(INVALID_DATA, done)); }); it('should NOT throw on findOrCreate with validate:true with valid data', function(done) { - User.findOrCreate(getNewWhere(), VALID_DATA, { validate: true }, + 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 }, + User.findOrCreate(getNewWhere(), VALID_DATA, {validate: false}, expectCreateSuccess(done)); }); @@ -382,25 +383,25 @@ describe('optional-validation', function() { describe('method updateOrCreate on existing data', function() { it('should throw on updateOrCreate(id) with validate:true with invalid data', function(done) { - callUpdateOrCreateWithExistingUserId(null, { validate: true }, + callUpdateOrCreateWithExistingUserId(null, {validate: true}, expectValidationError(done)); }); it('should NOT throw on updateOrCreate(id) with validate:false with invalid data', function(done) { - callUpdateOrCreateWithExistingUserId(null, { validate: false }, + callUpdateOrCreateWithExistingUserId(null, {validate: false}, expectChangeSuccess(INVALID_DATA, done)); }); it('should NOT throw on updateOrCreate(id) with validate:true with valid data', function(done) { - callUpdateOrCreateWithExistingUserId(NEW_NAME, { validate: true }, + 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 }, + callUpdateOrCreateWithExistingUserId(NEW_NAME, {validate: false}, expectChangeSuccess(done)); }); @@ -416,25 +417,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)); }); }); @@ -462,19 +463,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) { @@ -489,25 +490,25 @@ 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 }, + 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 }, + User.findOrCreate(getNewWhere(), INVALID_DATA, {validate: false}, expectCreateSuccess(INVALID_DATA, done)); }); it('should NOT throw on findOrCreate with validate:true with valid data', function(done) { - User.findOrCreate(getNewWhere(), VALID_DATA, { validate: true }, + 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 }, + User.findOrCreate(getNewWhere(), VALID_DATA, {validate: false}, expectCreateSuccess(done)); }); @@ -523,25 +524,25 @@ describe('optional-validation', function() { describe('method updateOrCreate on existing data', function() { it('should throw on updateOrCreate(id) with validate:true with invalid data', function(done) { - callUpdateOrCreateWithExistingUserId(null, { validate: true }, + callUpdateOrCreateWithExistingUserId(null, {validate: true}, expectValidationError(done)); }); it('should NOT throw on updateOrCreate(id) with validate:false with invalid data', function(done) { - callUpdateOrCreateWithExistingUserId(null, { validate: false }, + callUpdateOrCreateWithExistingUserId(null, {validate: false}, expectChangeSuccess(INVALID_DATA, done)); }); it('should NOT throw on updateOrCreate(id) with validate:true with valid data', function(done) { - callUpdateOrCreateWithExistingUserId(NEW_NAME, { validate: true }, + 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 }, + callUpdateOrCreateWithExistingUserId(NEW_NAME, {validate: false}, expectChangeSuccess(done)); }); @@ -563,19 +564,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)); }); }); diff --git a/test/persistence-hooks.suite.js b/test/persistence-hooks.suite.js index 3e5cc48f..1c21720f 100644 --- a/test/persistence-hooks.suite.js +++ b/test/persistence-hooks.suite.js @@ -3,6 +3,7 @@ // This file is licensed under the MIT License. // License text available at https://opensource.org/licenses/MIT +'use strict'; var ValidationError = require('../').ValidationError; var contextTestHelpers = require('./helpers/context-test-helpers'); @@ -30,14 +31,14 @@ module.exports = function(dataSource, should, connectorCapabilities) { beforeEach(function setupDatabase(done) { ctxRecorder = new ContextRecorder('hook not called'); - hookMonitor = new HookMonitor({ includeModelName: false }); + hookMonitor = new HookMonitor({includeModelName: false}); expectedError = new Error('test error'); TestModel = dataSource.createModel('TestModel', { // 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}, }); uid.reset(); @@ -53,7 +54,7 @@ module.exports = function(dataSource, should, connectorCapabilities) { }); beforeEach(function createTestData(done) { - TestModel.create({ name: 'first' }, function(err, instance) { + TestModel.create({name: 'first'}, function(err, instance) { if (err) return done(err); // Look it up from DB so that default values are retrieved @@ -61,7 +62,7 @@ module.exports = function(dataSource, should, connectorCapabilities) { existingInstance = instance; undefinedValue = existingInstance.extra; - TestModel.create({ name: 'second' }, function(err) { + TestModel.create({name: 'second'}, function(err) { if (err) return done(err); done(); }); @@ -74,7 +75,7 @@ module.exports = function(dataSource, should, connectorCapabilities) { monitorHookExecution(); TestModel.find( - { where: { id: '1' }}, + {where: {id: '1'}}, function(err, list) { if (err) return done(err); @@ -89,8 +90,8 @@ module.exports = function(dataSource, should, connectorCapabilities) { it('should not trigger hooks, if notify is false', function(done) { monitorHookExecution(); TestModel.find( - { where: { id: '1' }}, - { notify: false }, + {where: {id: '1'}}, + {notify: false}, function(err, list) { if (err) return done(err); hookMonitor.names.should.be.empty(); @@ -103,8 +104,8 @@ module.exports = function(dataSource, should, connectorCapabilities) { monitorHookExecution(); TestModel.find( - { where: { geo: { near: '10,20' }}}, - { notify: false }, + {where: {geo: {near: '10,20'}}}, + {notify: false}, function(err, list) { if (err) return done(err); hookMonitor.names.should.be.empty(); @@ -114,11 +115,11 @@ module.exports = function(dataSource, should, connectorCapabilities) { it('should apply updates from `access` hook', function(done) { TestModel.observe('access', function(ctx, next) { - ctx.query = { where: { name: 'second' }}; + ctx.query = {where: {name: 'second'}}; next(); }); - TestModel.find({ name: 'first' }, function(err, list) { + TestModel.find({name: 'first'}, function(err, list) { if (err) return done(err); list.map(get('name')).should.eql(['second']); done(); @@ -128,10 +129,10 @@ module.exports = function(dataSource, should, connectorCapabilities) { it('triggers `access` hook', function(done) { TestModel.observe('access', ctxRecorder.recordAndNext()); - TestModel.find({ where: { id: '1' }}, function(err, list) { + TestModel.find({where: {id: '1'}}, function(err, list) { if (err) return done(err); ctxRecorder.records.should.eql(aCtxForModel(TestModel, { - query: { where: { id: '1' }}, + query: {where: {id: '1'}}, })); done(); }); @@ -148,7 +149,7 @@ module.exports = function(dataSource, should, connectorCapabilities) { it('applies updates from `access` hook', function(done) { TestModel.observe('access', function(ctx, next) { - ctx.query = { where: { id: existingInstance.id }}; + ctx.query = {where: {id: existingInstance.id}}; next(); }); @@ -162,10 +163,10 @@ module.exports = function(dataSource, should, connectorCapabilities) { it('triggers `access` hook for geo queries', function(done) { TestModel.observe('access', ctxRecorder.recordAndNext()); - TestModel.find({ where: { geo: { near: '10,20' }}}, function(err, list) { + TestModel.find({where: {geo: {near: '10,20'}}}, function(err, list) { if (err) return done(err); ctxRecorder.records.should.eql(aCtxForModel(TestModel, { - query: { where: { geo: { near: '10,20' }}}, + query: {where: {geo: {near: '10,20'}}}, })); done(); }); @@ -173,11 +174,11 @@ module.exports = function(dataSource, should, connectorCapabilities) { it('applies updates from `access` hook for geo queries', function(done) { TestModel.observe('access', function(ctx, next) { - ctx.query = { where: { id: existingInstance.id }}; + ctx.query = {where: {id: existingInstance.id}}; next(); }); - TestModel.find({ where: { geo: { near: '10,20' }}}, function(err, list) { + TestModel.find({where: {geo: {near: '10,20'}}}, function(err, list) { if (err) return done(err); list.map(get('name')).should.eql([existingInstance.name]); done(); @@ -190,7 +191,7 @@ module.exports = function(dataSource, should, connectorCapabilities) { })); TestModel.find( - { where: { id: 1 }}, + {where: {id: 1}}, function(err, list) { if (err) return done(err); @@ -212,7 +213,7 @@ module.exports = function(dataSource, should, connectorCapabilities) { it('emits error when `loaded` hook fails', function(done) { TestModel.observe('loaded', nextWithError(expectedError)); TestModel.find( - { where: { id: 1 }}, + {where: {id: 1}}, function(err, list) { [err].should.eql([expectedError]); done(); @@ -225,7 +226,7 @@ module.exports = function(dataSource, should, connectorCapabilities) { monitorHookExecution(); TestModel.create( - { name: 'created' }, + {name: 'created'}, function(err, record, created) { if (err) return done(err); @@ -242,7 +243,7 @@ module.exports = function(dataSource, should, connectorCapabilities) { it('triggers `before save` hook', function(done) { TestModel.observe('before save', ctxRecorder.recordAndNext()); - TestModel.create({ name: 'created' }, function(err, instance) { + TestModel.create({name: 'created'}, function(err, instance) { if (err) return done(err); ctxRecorder.records.should.eql(aCtxForModel(TestModel, { instance: { @@ -259,7 +260,7 @@ module.exports = function(dataSource, should, connectorCapabilities) { it('aborts when `before save` hook fails', function(done) { TestModel.observe('before save', nextWithError(expectedError)); - TestModel.create({ name: 'created' }, function(err, instance) { + TestModel.create({name: 'created'}, function(err, instance) { [err].should.eql([expectedError]); done(); }); @@ -272,7 +273,7 @@ module.exports = function(dataSource, should, connectorCapabilities) { next(); }); - TestModel.create({ id: uid.next(), name: 'a-name' }, function(err, instance) { + TestModel.create({id: uid.next(), name: 'a-name'}, function(err, instance) { if (err) return done(err); instance.should.have.property('extra', 'hook data'); done(); @@ -283,7 +284,7 @@ module.exports = function(dataSource, should, connectorCapabilities) { TestModel.observe('before save', ctxRecorder.recordAndNext()); TestModel.create( - [{ name: '1' }, { name: '2' }], + [{name: '1'}, {name: '2'}], function(err, list) { if (err) return done(err); // Creation of multiple instances is executed in parallel @@ -292,11 +293,11 @@ module.exports = function(dataSource, should, connectorCapabilities) { }); ctxRecorder.records.should.eql([ aCtxForModel(TestModel, { - instance: { id: list[0].id, name: '1', extra: undefined }, + instance: {id: list[0].id, name: '1', extra: undefined}, isNewInstance: true, }), aCtxForModel(TestModel, { - instance: { id: list[1].id, name: '2', extra: undefined }, + instance: {id: list[1].id, name: '2', extra: undefined}, isNewInstance: true, }), ]); @@ -307,9 +308,9 @@ module.exports = function(dataSource, should, connectorCapabilities) { it('validates model after `before save` hook', function(done) { TestModel.observe('before save', invalidateTestModel()); - TestModel.create({ name: 'created' }, function(err) { + TestModel.create({name: 'created'}, function(err) { (err || {}).should.be.instanceOf(ValidationError); - (err.details.codes || {}).should.eql({ name: ['presence'] }); + (err.details.codes || {}).should.eql({name: ['presence']}); done(); }); }); @@ -318,14 +319,14 @@ module.exports = function(dataSource, should, connectorCapabilities) { TestModel.observe('persist', ctxRecorder.recordAndNext()); TestModel.create( - { id: 'new-id', name: 'a name' }, + {id: 'new-id', name: 'a name'}, function(err, instance) { if (err) return done(err); ctxRecorder.records.should.eql(aCtxForModel(TestModel, { - data: { id: 'new-id', name: 'a name' }, + data: {id: 'new-id', name: 'a name'}, isNewInstance: true, - currentInstance: { extra: null, id: 'new-id', name: 'a name' }, + currentInstance: {extra: null, id: 'new-id', name: 'a name'}, })); done(); @@ -343,7 +344,7 @@ module.exports = function(dataSource, should, connectorCapabilities) { // which if set, will apply these changes to the model instance too. TestModel.settings.updateOnLoad = true; TestModel.create( - { id: 'new-id', name: 'a name' }, + {id: 'new-id', name: 'a name'}, function(err, instance) { if (err) return done(err); @@ -374,12 +375,12 @@ module.exports = function(dataSource, should, connectorCapabilities) { // which if set, will apply these changes to the model instance too. TestModel.settings.updateOnLoad = true; TestModel.create( - { id: 'new-id', name: 'a name' }, + {id: 'new-id', name: 'a name'}, function(err, instance) { if (err) return done(err); ctxRecorder.records.should.eql(aCtxForModel(TestModel, { - data: { id: 'new-id', name: 'a name' }, + data: {id: 'new-id', name: 'a name'}, isNewInstance: true, })); @@ -390,7 +391,7 @@ module.exports = function(dataSource, should, connectorCapabilities) { it('emits error when `loaded` hook fails', function(done) { TestModel.observe('loaded', nextWithError(expectedError)); TestModel.create( - { id: 'new-id', name: 'a name' }, + {id: 'new-id', name: 'a name'}, function(err, instance) { [err].should.eql([expectedError]); done(); @@ -408,7 +409,7 @@ module.exports = function(dataSource, should, connectorCapabilities) { // which if set, will apply these changes to the model instance too. TestModel.settings.updateOnLoad = true; TestModel.create( - { id: 'new-id', name: 'a name' }, + {id: 'new-id', name: 'a name'}, function(err, instance) { if (err) return done(err); @@ -420,7 +421,7 @@ module.exports = function(dataSource, should, connectorCapabilities) { it('triggers `after save` hook', function(done) { TestModel.observe('after save', ctxRecorder.recordAndNext()); - TestModel.create({ name: 'created' }, function(err, instance) { + TestModel.create({name: 'created'}, function(err, instance) { if (err) return done(err); ctxRecorder.records.should.eql(aCtxForModel(TestModel, { instance: { @@ -437,7 +438,7 @@ module.exports = function(dataSource, should, connectorCapabilities) { it('aborts when `after save` hook fails', function(done) { TestModel.observe('after save', nextWithError(expectedError)); - TestModel.create({ name: 'created' }, function(err, instance) { + TestModel.create({name: 'created'}, function(err, instance) { [err].should.eql([expectedError]); done(); }); @@ -450,7 +451,7 @@ module.exports = function(dataSource, should, connectorCapabilities) { next(); }); - TestModel.create({ name: 'a-name' }, function(err, instance) { + TestModel.create({name: 'a-name'}, function(err, instance) { if (err) return done(err); instance.should.have.property('extra', 'hook data'); done(); @@ -461,7 +462,7 @@ module.exports = function(dataSource, should, connectorCapabilities) { TestModel.observe('after save', ctxRecorder.recordAndNext()); TestModel.create( - [{ name: '1' }, { name: '2' }], + [{name: '1'}, {name: '2'}], function(err, list) { if (err) return done(err); // Creation of multiple instances is executed in parallel @@ -470,11 +471,11 @@ module.exports = function(dataSource, should, connectorCapabilities) { }); ctxRecorder.records.should.eql([ aCtxForModel(TestModel, { - instance: { id: list[0].id, name: '1', extra: undefined }, + instance: {id: list[0].id, name: '1', extra: undefined}, isNewInstance: true, }), aCtxForModel(TestModel, { - instance: { id: list[1].id, name: '2', extra: undefined }, + instance: {id: list[1].id, name: '2', extra: undefined}, isNewInstance: true, }), ]); @@ -493,7 +494,7 @@ module.exports = function(dataSource, should, connectorCapabilities) { TestModel.observe('after save', ctxRecorder.recordAndNext()); TestModel.create( - [{ name: 'ok' }, { name: 'fail' }], + [{name: 'ok'}, {name: 'fail'}], function(err, list) { (err || []).should.have.length(2); err[1].should.eql(expectedError); @@ -504,7 +505,7 @@ module.exports = function(dataSource, should, connectorCapabilities) { list.map(get('name')).should.eql(['ok', 'fail']); ctxRecorder.records.should.eql(aCtxForModel(TestModel, { - instance: { id: list[0].id, name: 'ok', extra: undefined }, + instance: {id: list[0].id, name: 'ok', extra: undefined}, isNewInstance: true, })); done(); @@ -517,12 +518,12 @@ module.exports = function(dataSource, should, connectorCapabilities) { TestModel.observe('access', ctxRecorder.recordAndNext()); TestModel.findOrCreate( - { where: { name: 'new-record' }}, - { name: 'new-record' }, + {where: {name: 'new-record'}}, + {name: 'new-record'}, function(err, record, created) { if (err) return done(err); - ctxRecorder.records.should.eql(aCtxForModel(TestModel, { query: { - where: { name: 'new-record' }, + ctxRecorder.records.should.eql(aCtxForModel(TestModel, {query: { + where: {name: 'new-record'}, limit: 1, offset: 0, skip: 0, @@ -536,8 +537,8 @@ module.exports = function(dataSource, should, connectorCapabilities) { TestModel.observe('before save', ctxRecorder.recordAndNext()); TestModel.findOrCreate( - { where: { name: existingInstance.name }}, - { name: existingInstance.name }, + {where: {name: existingInstance.name}}, + {name: existingInstance.name}, function(err, record, created) { if (err) return done(err); record.id.should.eql(existingInstance.id); @@ -558,8 +559,8 @@ module.exports = function(dataSource, should, connectorCapabilities) { TestModel.observe('before save', ctxRecorder.recordAndNext()); TestModel.findOrCreate( - { where: { name: 'new-record' }}, - { name: 'new-record' }, + {where: {name: 'new-record'}}, + {name: 'new-record'}, function(err, record, created) { if (err) return done(err); ctxRecorder.records.should.eql(aCtxForModel(TestModel, { @@ -578,11 +579,11 @@ module.exports = function(dataSource, should, connectorCapabilities) { TestModel.observe('before save', invalidateTestModel()); TestModel.findOrCreate( - { where: { name: 'new-record' }}, - { name: 'new-record' }, + {where: {name: 'new-record'}}, + {name: 'new-record'}, function(err) { (err || {}).should.be.instanceOf(ValidationError); - (err.details.codes || {}).should.eql({ name: ['presence'] }); + (err.details.codes || {}).should.eql({name: ['presence']}); done(); }); }); @@ -591,8 +592,8 @@ module.exports = function(dataSource, should, connectorCapabilities) { monitorHookExecution(); TestModel.findOrCreate( - { where: { name: 'new-record' }}, - { name: 'new-record' }, + {where: {name: 'new-record'}}, + {name: 'new-record'}, function(err, record, created) { if (err) return done(err); hookMonitor.names.should.eql([ @@ -610,8 +611,8 @@ module.exports = function(dataSource, should, connectorCapabilities) { monitorHookExecution(); TestModel.findOrCreate( - { where: { name: existingInstance.name }}, - { name: existingInstance.name }, + {where: {name: existingInstance.name}}, + {name: existingInstance.name}, function(err, record, created) { if (err) return done(err); @@ -636,8 +637,8 @@ module.exports = function(dataSource, should, connectorCapabilities) { TestModel.observe('access', nextWithError(expectedError)); TestModel.findOrCreate( - { where: { id: 'does-not-exist' }}, - { name: 'does-not-exist' }, + {where: {id: 'does-not-exist'}}, + {name: 'does-not-exist'}, function(err, instance) { [err].should.eql([expectedError]); done(); @@ -648,8 +649,8 @@ module.exports = function(dataSource, should, connectorCapabilities) { TestModel.observe('before save', nextWithError(expectedError)); TestModel.findOrCreate( - { where: { id: 'does-not-exist' }}, - { name: 'does-not-exist' }, + {where: {id: 'does-not-exist'}}, + {name: 'does-not-exist'}, function(err, instance) { [err].should.eql([expectedError]); done(); @@ -661,8 +662,8 @@ module.exports = function(dataSource, should, connectorCapabilities) { TestModel.observe('persist', ctxRecorder.recordAndNext()); TestModel.findOrCreate( - { where: { name: existingInstance.name }}, - { name: existingInstance.name }, + {where: {name: existingInstance.name}}, + {name: existingInstance.name}, function(err, record, created) { if (err) return done(err); @@ -685,7 +686,7 @@ module.exports = function(dataSource, should, connectorCapabilities) { name: record.name, extra: null, }, - where: { name: existingInstance.name }, + where: {name: existingInstance.name}, })); done(); @@ -697,8 +698,8 @@ module.exports = function(dataSource, should, connectorCapabilities) { TestModel.observe('persist', ctxRecorder.recordAndNext()); TestModel.findOrCreate( - { where: { name: 'new-record' }}, - { name: 'new-record' }, + {where: {name: 'new-record'}}, + {name: 'new-record'}, function(err, record, created) { if (err) return done(err); @@ -716,7 +717,7 @@ module.exports = function(dataSource, should, connectorCapabilities) { name: record.name, extra: null, }, - where: { name: 'new-record' }, + where: {name: 'new-record'}, })); } else { ctxRecorder.records.should.eql(aCtxForModel(TestModel, { @@ -725,7 +726,7 @@ module.exports = function(dataSource, should, connectorCapabilities) { name: 'new-record', }, isNewInstance: true, - currentInstance: { id: record.id, name: record.name, extra: null }, + currentInstance: {id: record.id, name: record.name, extra: null}, })); } done(); @@ -739,8 +740,8 @@ module.exports = function(dataSource, should, connectorCapabilities) { })); TestModel.findOrCreate( - { where: { name: existingInstance.name }}, - { name: existingInstance.name }, + {where: {name: existingInstance.name}}, + {name: existingInstance.name}, function(err, instance) { if (err) return done(err); @@ -772,8 +773,8 @@ module.exports = function(dataSource, should, connectorCapabilities) { })); TestModel.findOrCreate( - { where: { name: 'new-record' }}, - { name: 'new-record' }, + {where: {name: 'new-record'}}, + {name: 'new-record'}, function(err, instance) { if (err) return done(err); @@ -808,8 +809,8 @@ module.exports = function(dataSource, should, connectorCapabilities) { TestModel.observe('loaded', ctxRecorder.recordAndNext()); TestModel.findOrCreate( - { where: { name: existingInstance.name }}, - { name: existingInstance.name }, + {where: {name: existingInstance.name}}, + {name: existingInstance.name}, function(err, record, created) { if (err) return done(err); @@ -835,8 +836,8 @@ module.exports = function(dataSource, should, connectorCapabilities) { TestModel.observe('loaded', ctxRecorder.recordAndNext()); TestModel.findOrCreate( - { where: { name: 'new-record' }}, - { name: 'new-record' }, + {where: {name: 'new-record'}}, + {name: 'new-record'}, function(err, record, created) { if (err) return done(err); @@ -855,8 +856,8 @@ module.exports = function(dataSource, should, connectorCapabilities) { it('emits error when `loaded` hook fails', function(done) { TestModel.observe('loaded', nextWithError(expectedError)); TestModel.findOrCreate( - { where: { name: 'new-record' }}, - { name: 'new-record' }, + {where: {name: 'new-record'}}, + {name: 'new-record'}, function(err, instance) { [err].should.eql([expectedError]); done(); @@ -870,8 +871,8 @@ module.exports = function(dataSource, should, connectorCapabilities) { })); TestModel.findOrCreate( - { where: { name: existingInstance.name }}, - { name: existingInstance.name }, + {where: {name: existingInstance.name}}, + {name: existingInstance.name}, function(err, instance) { if (err) return done(err); @@ -896,8 +897,8 @@ module.exports = function(dataSource, should, connectorCapabilities) { // unoptimized connector. TestModel.settings.updateOnLoad = true; TestModel.findOrCreate( - { where: { name: 'new-record' }}, - { name: 'new-record' }, + {where: {name: 'new-record'}}, + {name: 'new-record'}, function(err, instance) { if (err) return done(err); @@ -910,8 +911,8 @@ module.exports = function(dataSource, should, connectorCapabilities) { TestModel.observe('after save', ctxRecorder.recordAndNext()); TestModel.findOrCreate( - { where: { name: 'new name' }}, - { name: 'new name' }, + {where: {name: 'new name'}}, + {name: 'new name'}, function(err, instance) { if (err) return done(err); ctxRecorder.records.should.eql(aCtxForModel(TestModel, { @@ -930,8 +931,8 @@ module.exports = function(dataSource, should, connectorCapabilities) { TestModel.observe('after save', ctxRecorder.recordAndNext()); TestModel.findOrCreate( - { where: { id: existingInstance.id }}, - { name: existingInstance.name }, + {where: {id: existingInstance.id}}, + {name: existingInstance.name}, function(err, instance) { if (err) return done(err); ctxRecorder.records.should.eql('hook not called'); @@ -944,10 +945,10 @@ module.exports = function(dataSource, should, connectorCapabilities) { it('triggers `access` hook', function(done) { TestModel.observe('access', ctxRecorder.recordAndNext()); - TestModel.count({ id: existingInstance.id }, function(err, count) { + TestModel.count({id: existingInstance.id}, function(err, count) { if (err) return done(err); - ctxRecorder.records.should.eql(aCtxForModel(TestModel, { query: { - where: { id: existingInstance.id }, + ctxRecorder.records.should.eql(aCtxForModel(TestModel, {query: { + where: {id: existingInstance.id}, }})); done(); }); @@ -955,7 +956,7 @@ module.exports = function(dataSource, should, connectorCapabilities) { it('applies updates from `access` hook', function(done) { TestModel.observe('access', function(ctx, next) { - ctx.query.where = { id: existingInstance.id }; + ctx.query.where = {id: existingInstance.id}; next(); }); @@ -990,11 +991,11 @@ module.exports = function(dataSource, should, connectorCapabilities) { existingInstance.name = 'changed'; existingInstance.save(function(err, instance) { if (err) return done(err); - ctxRecorder.records.should.eql(aCtxForModel(TestModel, { instance: { + ctxRecorder.records.should.eql(aCtxForModel(TestModel, {instance: { id: existingInstance.id, name: 'changed', extra: undefined, - }, options: { throws: false, validate: true }})); + }, options: {throws: false, validate: true}})); done(); }); }); @@ -1027,7 +1028,7 @@ module.exports = function(dataSource, should, connectorCapabilities) { existingInstance.save(function(err) { (err || {}).should.be.instanceOf(ValidationError); - (err.details.codes || {}).should.eql({ name: ['presence'] }); + (err.details.codes || {}).should.eql({name: ['presence']}); done(); }); }); @@ -1051,8 +1052,8 @@ module.exports = function(dataSource, should, connectorCapabilities) { id: existingInstance.id, name: 'changed', }, - where: { id: existingInstance.id }, - options: { throws: false, validate: true }, + where: {id: existingInstance.id}, + options: {throws: false, validate: true}, })); done(); @@ -1085,7 +1086,7 @@ module.exports = function(dataSource, should, connectorCapabilities) { extra: 'changed', }, isNewInstance: false, - options: { throws: false, validate: true }, + options: {throws: false, validate: true}, })); done(); @@ -1126,7 +1127,7 @@ module.exports = function(dataSource, should, connectorCapabilities) { extra: undefined, }, isNewInstance: false, - options: { throws: false, validate: true }, + options: {throws: false, validate: true}, })); done(); }); @@ -1139,8 +1140,8 @@ module.exports = function(dataSource, should, connectorCapabilities) { // made by DAO to determine whether the instance should be saved via // PersistedModel.create and force it to call connector.save() var instance = new TestModel( - { id: 'new-id', name: 'created' }, - { persisted: true }); + {id: 'new-id', name: 'created'}, + {persisted: true}); instance.save(function(err, instance) { if (err) return done(err); @@ -1151,7 +1152,7 @@ module.exports = function(dataSource, should, connectorCapabilities) { extra: undefined, }, isNewInstance: true, - options: { throws: false, validate: true }, + options: {throws: false, validate: true}, })); done(); }); @@ -1186,7 +1187,7 @@ module.exports = function(dataSource, should, connectorCapabilities) { monitorHookExecution(); existingInstance.updateAttributes( - { name: 'changed' }, + {name: 'changed'}, function(err, record, created) { if (err) return done(err); hookMonitor.names.should.eql([ @@ -1204,12 +1205,12 @@ module.exports = function(dataSource, should, connectorCapabilities) { var currentInstance = deepCloneToObject(existingInstance); - existingInstance.updateAttributes({ name: 'changed' }, function(err) { + existingInstance.updateAttributes({name: 'changed'}, function(err) { if (err) return done(err); existingInstance.name.should.equal('changed'); ctxRecorder.records.should.eql(aCtxForModel(TestModel, { - where: { id: existingInstance.id }, - data: { name: 'changed' }, + where: {id: existingInstance.id}, + data: {name: 'changed'}, currentInstance: currentInstance, })); done(); @@ -1219,7 +1220,7 @@ module.exports = function(dataSource, should, connectorCapabilities) { it('aborts when `before save` hook fails', function(done) { TestModel.observe('before save', nextWithError(expectedError)); - existingInstance.updateAttributes({ name: 'updated' }, function(err) { + existingInstance.updateAttributes({name: 'updated'}, function(err) { [err].should.eql([expectedError]); done(); }); @@ -1232,7 +1233,7 @@ module.exports = function(dataSource, should, connectorCapabilities) { next(); }); - existingInstance.updateAttributes({ name: 'updated' }, function(err) { + existingInstance.updateAttributes({name: 'updated'}, function(err) { if (err) return done(err); // We must query the database here because `updateAttributes` // returns effectively `this`, not the data from the datasource @@ -1252,21 +1253,21 @@ module.exports = function(dataSource, should, connectorCapabilities) { it('validates model after `before save` hook', function(done) { TestModel.observe('before save', invalidateTestModel()); - existingInstance.updateAttributes({ name: 'updated' }, function(err) { + existingInstance.updateAttributes({name: 'updated'}, function(err) { (err || {}).should.be.instanceOf(ValidationError); - (err.details.codes || {}).should.eql({ name: ['presence'] }); + (err.details.codes || {}).should.eql({name: ['presence']}); done(); }); }); it('triggers `persist` hook', function(done) { TestModel.observe('persist', ctxRecorder.recordAndNext()); - existingInstance.updateAttributes({ name: 'changed' }, function(err) { + existingInstance.updateAttributes({name: 'changed'}, function(err) { if (err) return done(err); ctxRecorder.records.should.eql(aCtxForModel(TestModel, { - where: { id: existingInstance.id }, - data: { name: 'changed' }, + where: {id: existingInstance.id}, + data: {name: 'changed'}, currentInstance: { id: existingInstance.id, name: 'changed', @@ -1289,7 +1290,7 @@ module.exports = function(dataSource, should, connectorCapabilities) { // backwards compatibility, we introduced a new setting updateOnLoad, // which if set, will apply these changes to the model instance too. TestModel.settings.updateOnLoad = true; - existingInstance.updateAttributes({ name: 'changed' }, function(err, instance) { + existingInstance.updateAttributes({name: 'changed'}, function(err, instance) { if (err) return done(err); instance.should.have.property('extra', 'hook data'); done(); @@ -1298,21 +1299,21 @@ module.exports = function(dataSource, should, connectorCapabilities) { it('applies updates from `persist` hook - for nested model instance', function(done) { var Address = dataSource.createModel('NestedAddress', { - id: { type: String, id: true, default: 1 }, - city: { type: String, required: true }, - country: { type: String, required: true }, + id: {type: String, id: true, default: 1}, + city: {type: String, required: true}, + country: {type: String, required: true}, }); var User = dataSource.createModel('UserWithAddress', { - id: { type: String, id: true, default: uid.next }, - name: { type: String, required: true }, - address: { type: Address, required: false }, - extra: { type: String }, + id: {type: String, id: true, default: uid.next}, + name: {type: String, required: true}, + address: {type: Address, required: false}, + extra: {type: String}, }); dataSource.automigrate(['UserWithAddress', 'NestedAddress'], function(err) { if (err) return done(err); - User.create({ name: 'Joe' }, function(err, instance) { + User.create({name: 'Joe'}, function(err, instance) { if (err) return done(err); var existingUser = instance; @@ -1331,7 +1332,7 @@ module.exports = function(dataSource, should, connectorCapabilities) { // which if set, will apply these changes to the model instance too. User.settings.updateOnLoad = true; existingUser.updateAttributes( - { address: new Address({ city: 'Springfield', country: 'USA' }) }, + {address: new Address({city: 'Springfield', country: 'USA'})}, function(err, inst) { if (err) return done(err); @@ -1342,7 +1343,7 @@ module.exports = function(dataSource, should, connectorCapabilities) { dbInstance.toObject(true).should.eql({ id: existingUser.id, name: existingUser.name, - address: { id: '1', city: 'Springfield', country: 'USA' }, + address: {id: '1', city: 'Springfield', country: 'USA'}, extra: 'hook data', }); done(); @@ -1354,11 +1355,11 @@ module.exports = function(dataSource, should, connectorCapabilities) { it('triggers `loaded` hook', function(done) { TestModel.observe('loaded', ctxRecorder.recordAndNext()); - existingInstance.updateAttributes({ name: 'changed' }, function(err) { + existingInstance.updateAttributes({name: 'changed'}, function(err) { if (err) return done(err); ctxRecorder.records.should.eql(aCtxForModel(TestModel, { - data: { name: 'changed' }, + data: {name: 'changed'}, })); done(); @@ -1368,7 +1369,7 @@ module.exports = function(dataSource, should, connectorCapabilities) { it('emits error when `loaded` hook fails', function(done) { TestModel.observe('loaded', nextWithError(expectedError)); existingInstance.updateAttributes( - { name: 'changed' }, + {name: 'changed'}, function(err, instance) { [err].should.eql([expectedError]); done(); @@ -1385,7 +1386,7 @@ module.exports = function(dataSource, should, connectorCapabilities) { // backwards compatibility, we introduced a new setting updateOnLoad, // which if set, will apply these changes to the model instance too. TestModel.settings.updateOnLoad = true; - existingInstance.updateAttributes({ name: 'changed' }, function(err, instance) { + existingInstance.updateAttributes({name: 'changed'}, function(err, instance) { if (err) return done(err); instance.should.have.property('extra', 'hook data'); done(); @@ -1396,7 +1397,7 @@ module.exports = function(dataSource, should, connectorCapabilities) { TestModel.observe('after save', ctxRecorder.recordAndNext()); existingInstance.name = 'changed'; - existingInstance.updateAttributes({ name: 'changed' }, function(err) { + existingInstance.updateAttributes({name: 'changed'}, function(err) { if (err) return done(err); ctxRecorder.records.should.eql(aCtxForModel(TestModel, { instance: { @@ -1413,7 +1414,7 @@ module.exports = function(dataSource, should, connectorCapabilities) { it('aborts when `after save` hook fails', function(done) { TestModel.observe('after save', nextWithError(expectedError)); - existingInstance.updateAttributes({ name: 'updated' }, function(err) { + existingInstance.updateAttributes({name: 'updated'}, function(err) { [err].should.eql([expectedError]); done(); }); @@ -1426,7 +1427,7 @@ module.exports = function(dataSource, should, connectorCapabilities) { next(); }); - existingInstance.updateAttributes({ name: 'updated' }, function(err, instance) { + existingInstance.updateAttributes({name: 'updated'}, function(err, instance) { if (err) return done(err); instance.should.have.property('extra', 'hook data'); done(); @@ -1442,7 +1443,7 @@ module.exports = function(dataSource, should, connectorCapabilities) { monitorHookExecution(); existingInstance.replaceAttributes( - { name: 'replaced' }, + {name: 'replaced'}, function(err, record, created) { if (err) return done(err); hookMonitor.names.should.eql([ @@ -1458,7 +1459,7 @@ module.exports = function(dataSource, should, connectorCapabilities) { it('triggers `before save` hook', function(done) { TestModel.observe('before save', ctxRecorder.recordAndNext()); - existingInstance.replaceAttributes({ name: 'changed' }, function(err) { + existingInstance.replaceAttributes({name: 'changed'}, function(err) { if (err) return done(err); ctxRecorder.records.should.eql(aCtxForModel(TestModel, { instance: { @@ -1475,7 +1476,7 @@ module.exports = function(dataSource, should, connectorCapabilities) { it('aborts when `before save` hook fails', function(done) { TestModel.observe('before save', nextWithError(expectedError)); - existingInstance.replaceAttributes({ name: 'replaced' }, function(err) { + existingInstance.replaceAttributes({name: 'replaced'}, function(err) { [err].should.eql([expectedError]); done(); }); @@ -1488,7 +1489,7 @@ module.exports = function(dataSource, should, connectorCapabilities) { next(); }); - existingInstance.replaceAttributes({ name: 'updated' }, function(err) { + existingInstance.replaceAttributes({name: 'updated'}, function(err) { if (err) return done(err); TestModel.findById(existingInstance.id, function(err, instance) { if (err) return done(err); @@ -1506,20 +1507,20 @@ module.exports = function(dataSource, should, connectorCapabilities) { it('validates model after `before save` hook', function(done) { TestModel.observe('before save', invalidateTestModel()); - existingInstance.replaceAttributes({ name: 'updated' }, function(err) { + existingInstance.replaceAttributes({name: 'updated'}, function(err) { (err || {}).should.be.instanceOf(ValidationError); - (err.details.codes || {}).should.eql({ name: ['presence'] }); + (err.details.codes || {}).should.eql({name: ['presence']}); done(); }); }); it('triggers `persist` hook', function(done) { TestModel.observe('persist', ctxRecorder.recordAndNext()); - existingInstance.replaceAttributes({ name: 'replacedName' }, function(err) { + existingInstance.replaceAttributes({name: 'replacedName'}, function(err) { if (err) return done(err); ctxRecorder.records.should.eql(aCtxForModel(TestModel, { - where: { id: existingInstance.id }, + where: {id: existingInstance.id}, data: { name: 'replacedName', id: existingInstance.id, @@ -1541,7 +1542,7 @@ module.exports = function(dataSource, should, connectorCapabilities) { delete ctx.data.extra; })); - existingInstance.replaceAttributes({ name: 'changed' }, function(err, instance) { + existingInstance.replaceAttributes({name: 'changed'}, function(err, instance) { if (err) return done(err); instance.should.not.have.property('extra', 'hook data'); done(); @@ -1550,21 +1551,21 @@ module.exports = function(dataSource, should, connectorCapabilities) { it('applies updates from `persist` hook - for nested model instance', function(done) { var Address = dataSource.createModel('NestedAddress', { - id: { type: String, id: true, default: 1 }, - city: { type: String, required: true }, - country: { type: String, required: true }, + id: {type: String, id: true, default: 1}, + city: {type: String, required: true}, + country: {type: String, required: true}, }); var User = dataSource.createModel('UserWithAddress', { - id: { type: String, id: true, default: uid.next }, - name: { type: String, required: true }, - address: { type: Address, required: false }, - extra: { type: String }, + id: {type: String, id: true, default: uid.next}, + name: {type: String, required: true}, + address: {type: Address, required: false}, + extra: {type: String}, }); dataSource.automigrate(['UserWithAddress', 'NestedAddress'], function(err) { if (err) return done(err); - User.create({ name: 'Joe' }, function(err, instance) { + User.create({name: 'Joe'}, function(err, instance) { if (err) return done(err); var existingUser = instance; @@ -1578,7 +1579,7 @@ module.exports = function(dataSource, should, connectorCapabilities) { })); existingUser.replaceAttributes( - { name: 'John', address: new Address({ city: 'Springfield', country: 'USA' }) }, + {name: 'John', address: new Address({city: 'Springfield', country: 'USA'})}, function(err, inst) { if (err) return done(err); @@ -1589,7 +1590,7 @@ module.exports = function(dataSource, should, connectorCapabilities) { dbInstance.toObject(true).should.eql({ id: existingUser.id, name: 'John', - address: { id: '1', city: 'Springfield', country: 'USA' }, + address: {id: '1', city: 'Springfield', country: 'USA'}, extra: 'hook data', }); done(); @@ -1601,7 +1602,7 @@ module.exports = function(dataSource, should, connectorCapabilities) { it('triggers `loaded` hook', function(done) { TestModel.observe('loaded', ctxRecorder.recordAndNext()); - existingInstance.replaceAttributes({ name: 'changed' }, function(err, data) { + existingInstance.replaceAttributes({name: 'changed'}, function(err, data) { if (err) return done(err); ctxRecorder.records.should.eql(aCtxForModel(TestModel, { @@ -1618,7 +1619,7 @@ module.exports = function(dataSource, should, connectorCapabilities) { it('emits error when `loaded` hook fails', function(done) { TestModel.observe('loaded', nextWithError(expectedError)); existingInstance.replaceAttributes( - { name: 'replaced' }, + {name: 'replaced'}, function(err, instance) { [err].should.eql([expectedError]); done(); @@ -1630,7 +1631,7 @@ module.exports = function(dataSource, should, connectorCapabilities) { ctx.data.name = 'changed in hook'; })); - existingInstance.replaceAttributes({ name: 'changed' }, function(err, instance) { + existingInstance.replaceAttributes({name: 'changed'}, function(err, instance) { if (err) return done(err); instance.should.have.property('name', 'changed in hook'); done(); @@ -1641,7 +1642,7 @@ module.exports = function(dataSource, should, connectorCapabilities) { TestModel.observe('after save', ctxRecorder.recordAndNext()); existingInstance.name = 'replaced'; - existingInstance.replaceAttributes({ name: 'replaced' }, function(err) { + existingInstance.replaceAttributes({name: 'replaced'}, function(err) { if (err) return done(err); ctxRecorder.records.should.eql(aCtxForModel(TestModel, { instance: { @@ -1658,7 +1659,7 @@ module.exports = function(dataSource, should, connectorCapabilities) { it('aborts when `after save` hook fails', function(done) { TestModel.observe('after save', nextWithError(expectedError)); - existingInstance.replaceAttributes({ name: 'replaced' }, function(err) { + existingInstance.replaceAttributes({name: 'replaced'}, function(err) { [err].should.eql([expectedError]); done(); }); @@ -1671,7 +1672,7 @@ module.exports = function(dataSource, should, connectorCapabilities) { next(); }); - existingInstance.replaceAttributes({ name: 'updated' }, function(err, instance) { + existingInstance.replaceAttributes({name: 'updated'}, function(err, instance) { if (err) return done(err); instance.should.have.property('extra', 'hook data'); done(); @@ -1685,7 +1686,7 @@ module.exports = function(dataSource, should, connectorCapabilities) { monitorHookExecution(); TestModel.updateOrCreate( - { id: 'not-found', name: 'not found' }, + {id: 'not-found', name: 'not found'}, function(err, record, created) { if (err) return done(err); hookMonitor.names.should.eql([ @@ -1703,7 +1704,7 @@ module.exports = function(dataSource, should, connectorCapabilities) { monitorHookExecution(); TestModel.updateOrCreate( - { id: existingInstance.id, name: 'new name' }, + {id: existingInstance.id, name: 'new name'}, function(err, record, created) { if (err) return done(err); hookMonitor.names.should.eql([ @@ -1721,11 +1722,11 @@ module.exports = function(dataSource, should, connectorCapabilities) { TestModel.observe('access', ctxRecorder.recordAndNext()); TestModel.updateOrCreate( - { id: 'not-found', name: 'not found' }, + {id: 'not-found', name: 'not found'}, function(err, instance) { if (err) return done(err); - ctxRecorder.records.should.eql(aCtxForModel(TestModel, { query: { - where: { id: 'not-found' }, + ctxRecorder.records.should.eql(aCtxForModel(TestModel, {query: { + where: {id: 'not-found'}, }})); done(); }); @@ -1735,11 +1736,11 @@ module.exports = function(dataSource, should, connectorCapabilities) { TestModel.observe('access', ctxRecorder.recordAndNext()); TestModel.updateOrCreate( - { id: existingInstance.id, name: 'new name' }, + {id: existingInstance.id, name: 'new name'}, function(err, instance) { if (err) return done(err); - ctxRecorder.records.should.eql(aCtxForModel(TestModel, { query: { - where: { id: existingInstance.id }, + ctxRecorder.records.should.eql(aCtxForModel(TestModel, {query: { + where: {id: existingInstance.id}, }})); done(); }); @@ -1749,7 +1750,7 @@ module.exports = function(dataSource, should, connectorCapabilities) { TestModel.observe('access', ctxRecorder.recordAndNext()); TestModel.updateOrCreate( - { name: 'new name' }, + {name: 'new name'}, function(err, instance) { if (err) return done(err); ctxRecorder.records.should.equal('hook not called'); @@ -1759,19 +1760,19 @@ module.exports = function(dataSource, should, connectorCapabilities) { it('applies updates from `access` hook when found', function(done) { TestModel.observe('access', function(ctx, next) { - ctx.query = { where: { id: { neq: existingInstance.id }}}; + ctx.query = {where: {id: {neq: existingInstance.id}}}; next(); }); TestModel.updateOrCreate( - { id: existingInstance.id, name: 'new name' }, + {id: existingInstance.id, name: 'new name'}, function(err, instance) { if (err) return done(err); - findTestModels({ fields: ['id', 'name'] }, function(err, list) { + findTestModels({fields: ['id', 'name']}, function(err, list) { if (err) return done(err); (list || []).map(toObject).should.eql([ - { id: existingInstance.id, name: existingInstance.name, extra: undefined }, - { id: instance.id, name: 'new name', extra: undefined }, + {id: existingInstance.id, name: existingInstance.name, extra: undefined}, + {id: instance.id, name: 'new name', extra: undefined}, ]); done(); }); @@ -1780,20 +1781,20 @@ module.exports = function(dataSource, should, connectorCapabilities) { it('applies updates from `access` hook when not found', function(done) { TestModel.observe('access', function(ctx, next) { - ctx.query = { where: { id: 'not-found' }}; + ctx.query = {where: {id: 'not-found'}}; next(); }); TestModel.updateOrCreate( - { id: existingInstance.id, name: 'new name' }, + {id: existingInstance.id, name: 'new name'}, function(err, instance) { if (err) return done(err); - findTestModels({ fields: ['id', 'name'] }, function(err, list) { + findTestModels({fields: ['id', 'name']}, function(err, list) { if (err) return done(err); (list || []).map(toObject).should.eql([ - { id: existingInstance.id, name: existingInstance.name, extra: undefined }, - { id: list[1].id, name: 'second', extra: undefined }, - { id: instance.id, name: 'new name', extra: undefined }, + {id: existingInstance.id, name: existingInstance.name, extra: undefined}, + {id: list[1].id, name: 'second', extra: undefined}, + {id: instance.id, name: 'new name', extra: undefined}, ]); done(); }); @@ -1804,12 +1805,12 @@ module.exports = function(dataSource, should, connectorCapabilities) { monitorHookExecution(['access', 'before save']); TestModel.observe('access', function(ctx, next) { - ctx.query = { where: { id: { neq: existingInstance.id }}}; + ctx.query = {where: {id: {neq: existingInstance.id}}}; next(); }); TestModel.updateOrCreate( - { id: 'ignored', name: 'new name' }, + {id: 'ignored', name: 'new name'}, function(err, instance) { if (err) return done(err); hookMonitor.names.should.eql(['access', 'before save']); @@ -1821,7 +1822,7 @@ module.exports = function(dataSource, should, connectorCapabilities) { TestModel.observe('before save', ctxRecorder.recordAndNext()); TestModel.updateOrCreate( - { id: existingInstance.id, name: 'updated name' }, + {id: existingInstance.id, name: 'updated name'}, function(err, instance) { if (err) return done(err); if (dataSource.connector.updateOrCreate) { @@ -1829,16 +1830,16 @@ module.exports = function(dataSource, should, connectorCapabilities) { // provide full instance as that depends on whether // UPDATE or CREATE will be triggered ctxRecorder.records.should.eql(aCtxForModel(TestModel, { - where: { id: existingInstance.id }, - data: { id: existingInstance.id, name: 'updated name' }, + where: {id: existingInstance.id}, + data: {id: existingInstance.id, name: 'updated name'}, })); } else { // currentInstance is set, because a non-atomic `updateOrCreate` // will use `prototype.updateAttributes` internally, which // exposes this to the context ctxRecorder.records.should.eql(aCtxForModel(TestModel, { - where: { id: existingInstance.id }, - data: { id: existingInstance.id, name: 'updated name' }, + where: {id: existingInstance.id}, + data: {id: existingInstance.id, name: 'updated name'}, currentInstance: existingInstance, })); } @@ -1850,7 +1851,7 @@ module.exports = function(dataSource, should, connectorCapabilities) { TestModel.observe('before save', ctxRecorder.recordAndNext()); TestModel.updateOrCreate( - { id: 'new-id', name: 'a name' }, + {id: 'new-id', name: 'a name'}, function(err, instance) { if (err) return done(err); @@ -1859,14 +1860,14 @@ module.exports = function(dataSource, should, connectorCapabilities) { // provide full instance as that depends on whether // UPDATE or CREATE will be triggered ctxRecorder.records.should.eql(aCtxForModel(TestModel, { - where: { id: 'new-id' }, - data: { id: 'new-id', name: 'a name' }, + where: {id: 'new-id'}, + data: {id: 'new-id', name: 'a name'}, })); } else { // The default unoptimized implementation runs // `instance.save` and thus a full instance is availalbe ctxRecorder.records.should.eql(aCtxForModel(TestModel, { - instance: { id: 'new-id', name: 'a name', extra: undefined }, + instance: {id: 'new-id', name: 'a name', extra: undefined}, isNewInstance: true, })); } @@ -1882,7 +1883,7 @@ module.exports = function(dataSource, should, connectorCapabilities) { }); TestModel.updateOrCreate( - { id: existingInstance.id, name: 'updated name' }, + {id: existingInstance.id, name: 'updated name'}, function(err, instance) { if (err) return done(err); instance.name.should.equal('hooked'); @@ -1901,7 +1902,7 @@ module.exports = function(dataSource, should, connectorCapabilities) { }); TestModel.updateOrCreate( - { id: 'new-id', name: 'new name' }, + {id: 'new-id', name: 'new name'}, function(err, instance) { if (err) return done(err); instance.name.should.equal('hooked'); @@ -1915,10 +1916,10 @@ module.exports = function(dataSource, should, connectorCapabilities) { TestModel.observe('before save', invalidateTestModel()); TestModel.updateOrCreate( - { id: existingInstance.id, name: 'updated name' }, + {id: existingInstance.id, name: 'updated name'}, function(err, instance) { (err || {}).should.be.instanceOf(ValidationError); - (err.details.codes || {}).should.eql({ name: ['presence'] }); + (err.details.codes || {}).should.eql({name: ['presence']}); done(); }); }); @@ -1929,10 +1930,10 @@ module.exports = function(dataSource, should, connectorCapabilities) { TestModel.observe('before save', invalidateTestModel()); TestModel.updateOrCreate( - { id: 'new-id', name: 'new name' }, + {id: 'new-id', name: 'new name'}, function(err, instance) { (err || {}).should.be.instanceOf(ValidationError); - (err.details.codes || {}).should.eql({ name: ['presence'] }); + (err.details.codes || {}).should.eql({name: ['presence']}); done(); }); }); @@ -1941,14 +1942,14 @@ module.exports = function(dataSource, should, connectorCapabilities) { TestModel.observe('persist', ctxRecorder.recordAndNext()); TestModel.updateOrCreate( - { id: 'new-id', name: 'a name' }, + {id: 'new-id', name: 'a name'}, function(err, instance) { if (err) return done(err); if (dataSource.connector.updateOrCreate) { ctxRecorder.records.should.eql(aCtxForModel(TestModel, { - where: { id: 'new-id' }, - data: { id: 'new-id', name: 'a name' }, + where: {id: 'new-id'}, + data: {id: 'new-id', name: 'a name'}, currentInstance: { id: 'new-id', name: 'a name', @@ -1977,12 +1978,12 @@ module.exports = function(dataSource, should, connectorCapabilities) { TestModel.observe('persist', ctxRecorder.recordAndNext()); TestModel.updateOrCreate( - { id: existingInstance.id, name: 'updated name' }, + {id: existingInstance.id, name: 'updated name'}, function(err, instance) { if (err) return done(err); var expectedContext = aCtxForModel(TestModel, { - where: { id: existingInstance.id }, + where: {id: existingInstance.id}, data: { id: existingInstance.id, name: 'updated name', @@ -2009,13 +2010,13 @@ module.exports = function(dataSource, should, connectorCapabilities) { TestModel.observe('loaded', ctxRecorder.recordAndNext()); TestModel.updateOrCreate( - { id: 'new-id', name: 'a name' }, + {id: 'new-id', name: 'a name'}, function(err, instance) { if (err) return done(err); if (dataSource.connector.updateOrCreate) { ctxRecorder.records.should.eql(aCtxForModel(TestModel, { - data: { id: 'new-id', name: 'a name' }, + data: {id: 'new-id', name: 'a name'}, isNewInstance: true, })); } else { @@ -2035,7 +2036,7 @@ module.exports = function(dataSource, should, connectorCapabilities) { TestModel.observe('loaded', ctxRecorder.recordAndNext()); TestModel.updateOrCreate( - { id: existingInstance.id, name: 'updated name' }, + {id: existingInstance.id, name: 'updated name'}, function(err, instance) { if (err) return done(err); @@ -2064,7 +2065,7 @@ module.exports = function(dataSource, should, connectorCapabilities) { it('emits error when `loaded` hook fails', function(done) { TestModel.observe('loaded', nextWithError(expectedError)); TestModel.updateOrCreate( - { id: 'new-id', name: 'a name' }, + {id: 'new-id', name: 'a name'}, function(err, instance) { [err].should.eql([expectedError]); done(); @@ -2075,7 +2076,7 @@ module.exports = function(dataSource, should, connectorCapabilities) { TestModel.observe('after save', ctxRecorder.recordAndNext()); TestModel.updateOrCreate( - { id: existingInstance.id, name: 'updated name' }, + {id: existingInstance.id, name: 'updated name'}, function(err, instance) { if (err) return done(err); ctxRecorder.records.should.eql(aCtxForModel(TestModel, { @@ -2094,7 +2095,7 @@ module.exports = function(dataSource, should, connectorCapabilities) { TestModel.observe('after save', ctxRecorder.recordAndNext()); TestModel.updateOrCreate( - { id: 'new-id', name: 'a name' }, + {id: 'new-id', name: 'a name'}, function(err, instance) { if (err) return done(err); ctxRecorder.records.should.eql(aCtxForModel(TestModel, { @@ -2118,7 +2119,7 @@ module.exports = function(dataSource, should, connectorCapabilities) { monitorHookExecution(); TestModel.replaceOrCreate( - { id: 'not-found', name: 'not found' }, + {id: 'not-found', name: 'not found'}, function(err, record, created) { if (err) return done(err); hookMonitor.names.should.eql([ @@ -2136,7 +2137,7 @@ module.exports = function(dataSource, should, connectorCapabilities) { monitorHookExecution(); TestModel.replaceOrCreate( - { id: existingInstance.id, name: 'new name' }, + {id: existingInstance.id, name: 'new name'}, function(err, record, created) { if (err) return done(err); hookMonitor.names.should.eql([ @@ -2154,11 +2155,11 @@ module.exports = function(dataSource, should, connectorCapabilities) { TestModel.observe('access', ctxRecorder.recordAndNext()); TestModel.replaceOrCreate( - { id: 'not-found', name: 'not found' }, + {id: 'not-found', name: 'not found'}, function(err, instance) { if (err) return done(err); - ctxRecorder.records.should.eql(aCtxForModel(TestModel, { query: { - where: { id: 'not-found' }, + ctxRecorder.records.should.eql(aCtxForModel(TestModel, {query: { + where: {id: 'not-found'}, }})); done(); }); @@ -2168,11 +2169,11 @@ module.exports = function(dataSource, should, connectorCapabilities) { TestModel.observe('access', ctxRecorder.recordAndNext()); TestModel.replaceOrCreate( - { id: existingInstance.id, name: 'new name' }, + {id: existingInstance.id, name: 'new name'}, function(err, instance) { if (err) return done(err); - ctxRecorder.records.should.eql(aCtxForModel(TestModel, { query: { - where: { id: existingInstance.id }, + ctxRecorder.records.should.eql(aCtxForModel(TestModel, {query: { + where: {id: existingInstance.id}, }})); done(); }); @@ -2182,7 +2183,7 @@ module.exports = function(dataSource, should, connectorCapabilities) { TestModel.observe('access', ctxRecorder.recordAndNext()); TestModel.replaceOrCreate( - { name: 'new name' }, + {name: 'new name'}, function(err, instance) { if (err) return done(err); ctxRecorder.records.should.equal('hook not called'); @@ -2192,19 +2193,19 @@ module.exports = function(dataSource, should, connectorCapabilities) { it('applies updates from `access` hook when found', function(done) { TestModel.observe('access', function(ctx, next) { - ctx.query = { where: { id: { neq: existingInstance.id }}}; + ctx.query = {where: {id: {neq: existingInstance.id}}}; next(); }); TestModel.replaceOrCreate( - { id: existingInstance.id, name: 'new name' }, + {id: existingInstance.id, name: 'new name'}, function(err, instance) { if (err) return done(err); - findTestModels({ fields: ['id', 'name'] }, function(err, list) { + findTestModels({fields: ['id', 'name']}, function(err, list) { if (err) return done(err); (list || []).map(toObject).should.eql([ - { id: existingInstance.id, name: existingInstance.name, extra: undefined }, - { id: instance.id, name: 'new name', extra: undefined }, + {id: existingInstance.id, name: existingInstance.name, extra: undefined}, + {id: instance.id, name: 'new name', extra: undefined}, ]); done(); }); @@ -2213,20 +2214,20 @@ module.exports = function(dataSource, should, connectorCapabilities) { it('applies updates from `access` hook when not found', function(done) { TestModel.observe('access', function(ctx, next) { - ctx.query = { where: { id: 'not-found' }}; + ctx.query = {where: {id: 'not-found'}}; next(); }); TestModel.replaceOrCreate( - { id: existingInstance.id, name: 'new name' }, + {id: existingInstance.id, name: 'new name'}, function(err, instance) { if (err) return done(err); - findTestModels({ fields: ['id', 'name'] }, function(err, list) { + findTestModels({fields: ['id', 'name']}, function(err, list) { if (err) return done(err); (list || []).map(toObject).should.eql([ - { id: existingInstance.id, name: existingInstance.name, extra: undefined }, - { id: list[1].id, name: 'second', extra: undefined }, - { id: instance.id, name: 'new name', extra: undefined }, + {id: existingInstance.id, name: existingInstance.name, extra: undefined}, + {id: list[1].id, name: 'second', extra: undefined}, + {id: instance.id, name: 'new name', extra: undefined}, ]); done(); }); @@ -2237,12 +2238,12 @@ module.exports = function(dataSource, should, connectorCapabilities) { monitorHookExecution(['access', 'before save']); TestModel.observe('access', function(ctx, next) { - ctx.query = { where: { id: { neq: existingInstance.id }}}; + ctx.query = {where: {id: {neq: existingInstance.id}}}; next(); }); TestModel.replaceOrCreate( - { id: 'ignored', name: 'new name' }, + {id: 'ignored', name: 'new name'}, function(err, instance) { if (err) return done(err); hookMonitor.names.should.eql(['access', 'before save']); @@ -2252,7 +2253,7 @@ module.exports = function(dataSource, should, connectorCapabilities) { it('triggers `before save` hookon create', function(done) { TestModel.observe('before save', ctxRecorder.recordAndNext()); - TestModel.replaceOrCreate({ id: existingInstance.id, name: 'new name' }, + TestModel.replaceOrCreate({id: existingInstance.id, name: 'new name'}, function(err, instance) { if (err) return done(err); @@ -2271,7 +2272,7 @@ module.exports = function(dataSource, should, connectorCapabilities) { it('triggers `before save` hook on replace', function(done) { TestModel.observe('before save', ctxRecorder.recordAndNext()); TestModel.replaceOrCreate( - { id: existingInstance.id, name: 'replaced name' }, + {id: existingInstance.id, name: 'replaced name'}, function(err, instance) { if (err) return done(err); @@ -2296,7 +2297,7 @@ module.exports = function(dataSource, should, connectorCapabilities) { TestModel.observe('before save', ctxRecorder.recordAndNext()); TestModel.replaceOrCreate( - { id: 'new-id', name: 'a name' }, + {id: 'new-id', name: 'a name'}, function(err, instance) { if (err) return done(err); @@ -2324,7 +2325,7 @@ module.exports = function(dataSource, should, connectorCapabilities) { }); TestModel.replaceOrCreate( - { id: 'new-id', name: 'new name' }, + {id: 'new-id', name: 'new name'}, function(err, instance) { if (err) return done(err); instance.name.should.equal('hooked'); @@ -2336,10 +2337,10 @@ module.exports = function(dataSource, should, connectorCapabilities) { TestModel.observe('before save', invalidateTestModel()); TestModel.replaceOrCreate( - { id: 'new-id', name: 'new name' }, + {id: 'new-id', name: 'new name'}, function(err, instance) { (err || {}).should.be.instanceOf(ValidationError); - (err.details.codes || {}).should.eql({ name: ['presence'] }); + (err.details.codes || {}).should.eql({name: ['presence']}); done(); }); }); @@ -2348,7 +2349,7 @@ module.exports = function(dataSource, should, connectorCapabilities) { TestModel.observe('persist', ctxRecorder.recordAndNext()); TestModel.replaceOrCreate( - { id: 'new-id', name: 'a name' }, + {id: 'new-id', name: 'a name'}, function(err, instance) { if (err) return done(err); @@ -2365,7 +2366,7 @@ module.exports = function(dataSource, should, connectorCapabilities) { }); if (dataSource.connector.replaceOrCreate) { - expectedContext.where = { id: 'new-id' }; + expectedContext.where = {id: 'new-id'}; } else { // non-atomic implementation does not provide ctx.where // because a new instance is being created, so there @@ -2381,12 +2382,12 @@ module.exports = function(dataSource, should, connectorCapabilities) { TestModel.observe('persist', ctxRecorder.recordAndNext()); TestModel.replaceOrCreate( - { id: existingInstance.id, name: 'replaced name' }, + {id: existingInstance.id, name: 'replaced name'}, function(err, instance) { if (err) return done(err); var expected = { - where: { id: existingInstance.id }, + where: {id: existingInstance.id}, data: { id: existingInstance.id, name: 'replaced name', @@ -2414,7 +2415,7 @@ module.exports = function(dataSource, should, connectorCapabilities) { TestModel.observe('loaded', ctxRecorder.recordAndNext()); TestModel.replaceOrCreate( - { id: 'new-id', name: 'a name' }, + {id: 'new-id', name: 'a name'}, function(err, instance) { if (err) return done(err); @@ -2438,7 +2439,7 @@ module.exports = function(dataSource, should, connectorCapabilities) { TestModel.observe('loaded', ctxRecorder.recordAndNext()); TestModel.replaceOrCreate( - { id: existingInstance.id, name: 'replaced name' }, + {id: existingInstance.id, name: 'replaced name'}, function(err, instance) { if (err) return done(err); @@ -2461,7 +2462,7 @@ module.exports = function(dataSource, should, connectorCapabilities) { it('emits error when `loaded` hook fails', function(done) { TestModel.observe('loaded', nextWithError(expectedError)); TestModel.replaceOrCreate( - { id: 'new-id', name: 'a name' }, + {id: 'new-id', name: 'a name'}, function(err, instance) { [err].should.eql([expectedError]); done(); @@ -2472,7 +2473,7 @@ module.exports = function(dataSource, should, connectorCapabilities) { TestModel.observe('after save', ctxRecorder.recordAndNext()); TestModel.replaceOrCreate( - { id: existingInstance.id, name: 'replaced name' }, + {id: existingInstance.id, name: 'replaced name'}, function(err, instance) { if (err) return done(err); @@ -2497,7 +2498,7 @@ module.exports = function(dataSource, should, connectorCapabilities) { TestModel.observe('after save', ctxRecorder.recordAndNext()); TestModel.replaceOrCreate( - { id: 'new-id', name: 'a name' }, + {id: 'new-id', name: 'a name'}, function(err, instance) { if (err) return done(err); @@ -2523,10 +2524,10 @@ module.exports = function(dataSource, should, connectorCapabilities) { it('triggers `access` hook with query', function(done) { TestModel.observe('access', ctxRecorder.recordAndNext()); - TestModel.deleteAll({ name: existingInstance.name }, function(err) { + TestModel.deleteAll({name: existingInstance.name}, function(err) { if (err) return done(err); ctxRecorder.records.should.eql(aCtxForModel(TestModel, { - query: { where: { name: existingInstance.name }}, + query: {where: {name: existingInstance.name}}, })); done(); }); @@ -2537,14 +2538,14 @@ module.exports = function(dataSource, should, connectorCapabilities) { TestModel.deleteAll(function(err) { if (err) return done(err); - ctxRecorder.records.should.eql(aCtxForModel(TestModel, { query: { where: {}}})); + ctxRecorder.records.should.eql(aCtxForModel(TestModel, {query: {where: {}}})); done(); }); }); it('applies updates from `access` hook', function(done) { TestModel.observe('access', function(ctx, next) { - ctx.query = { where: { id: { neq: existingInstance.id }}}; + ctx.query = {where: {id: {neq: existingInstance.id}}}; next(); }); @@ -2561,10 +2562,10 @@ module.exports = function(dataSource, should, connectorCapabilities) { it('triggers `before delete` hook with query', function(done) { TestModel.observe('before delete', ctxRecorder.recordAndNext()); - TestModel.deleteAll({ name: existingInstance.name }, function(err) { + TestModel.deleteAll({name: existingInstance.name}, function(err) { if (err) return done(err); ctxRecorder.records.should.eql(aCtxForModel(TestModel, { - where: { name: existingInstance.name }, + where: {name: existingInstance.name}, })); done(); }); @@ -2575,14 +2576,14 @@ module.exports = function(dataSource, should, connectorCapabilities) { TestModel.deleteAll(function(err) { if (err) return done(err); - ctxRecorder.records.should.eql(aCtxForModel(TestModel, { where: {}})); + ctxRecorder.records.should.eql(aCtxForModel(TestModel, {where: {}})); done(); }); }); it('applies updates from `before delete` hook', function(done) { TestModel.observe('before delete', function(ctx, next) { - ctx.where = { id: { neq: existingInstance.id }}; + ctx.where = {id: {neq: existingInstance.id}}; next(); }); @@ -2615,7 +2616,7 @@ module.exports = function(dataSource, should, connectorCapabilities) { TestModel.deleteAll(function(err) { if (err) return done(err); - ctxRecorder.records.should.eql(aCtxForModel(TestModel, { where: {}})); + ctxRecorder.records.should.eql(aCtxForModel(TestModel, {where: {}})); done(); }); }); @@ -2623,10 +2624,10 @@ module.exports = function(dataSource, should, connectorCapabilities) { it('triggers `after delete` hook without query', function(done) { TestModel.observe('after delete', ctxRecorder.recordAndNext()); - TestModel.deleteAll({ name: existingInstance.name }, function(err) { + TestModel.deleteAll({name: existingInstance.name}, function(err) { if (err) return done(err); ctxRecorder.records.should.eql(aCtxForModel(TestModel, { - where: { name: existingInstance.name }, + where: {name: existingInstance.name}, })); done(); }); @@ -2649,7 +2650,7 @@ module.exports = function(dataSource, should, connectorCapabilities) { existingInstance.delete(function(err) { if (err) return done(err); ctxRecorder.records.should.eql(aCtxForModel(TestModel, { - query: { where: { id: existingInstance.id }}, + query: {where: {id: existingInstance.id}}, })); done(); }); @@ -2657,7 +2658,7 @@ module.exports = function(dataSource, should, connectorCapabilities) { it('applies updated from `access` hook', function(done) { TestModel.observe('access', function(ctx, next) { - ctx.query = { where: { id: { neq: existingInstance.id }}}; + ctx.query = {where: {id: {neq: existingInstance.id}}}; next(); }); @@ -2677,7 +2678,7 @@ module.exports = function(dataSource, should, connectorCapabilities) { existingInstance.delete(function(err) { if (err) return done(err); ctxRecorder.records.should.eql(aCtxForModel(TestModel, { - where: { id: existingInstance.id }, + where: {id: existingInstance.id}, instance: existingInstance, })); done(); @@ -2686,7 +2687,7 @@ module.exports = function(dataSource, should, connectorCapabilities) { it('applies updated from `before delete` hook', function(done) { TestModel.observe('before delete', function(ctx, next) { - ctx.where = { id: { neq: existingInstance.id }}; + ctx.where = {id: {neq: existingInstance.id}}; next(); }); @@ -2720,7 +2721,7 @@ module.exports = function(dataSource, should, connectorCapabilities) { existingInstance.delete(function(err) { if (err) return done(err); ctxRecorder.records.should.eql(aCtxForModel(TestModel, { - where: { id: existingInstance.id }, + where: {id: existingInstance.id}, instance: existingInstance, })); done(); @@ -2730,10 +2731,10 @@ module.exports = function(dataSource, should, connectorCapabilities) { it('triggers `after delete` hook without query', function(done) { TestModel.observe('after delete', ctxRecorder.recordAndNext()); - TestModel.deleteAll({ name: existingInstance.name }, function(err) { + TestModel.deleteAll({name: existingInstance.name}, function(err) { if (err) return done(err); ctxRecorder.records.should.eql(aCtxForModel(TestModel, { - where: { name: existingInstance.name }, + where: {name: existingInstance.name}, })); done(); }); @@ -2761,13 +2762,13 @@ module.exports = function(dataSource, should, connectorCapabilities) { if (err) return done(err); ctxRecorder.records.should.eql([ aCtxForModel(TestModel, { - hookState: { foo: 'bar' }, - where: { id: '1' }, + hookState: {foo: 'bar'}, + where: {id: '1'}, instance: existingInstance, }), aCtxForModel(TestModel, { - hookState: { foo: 'BAR' }, - where: { id: '1' }, + hookState: {foo: 'BAR'}, + where: {id: '1'}, instance: existingInstance, }), ]); @@ -2778,7 +2779,7 @@ module.exports = function(dataSource, should, connectorCapabilities) { it('triggers hooks only once', function(done) { monitorHookExecution(); TestModel.observe('access', function(ctx, next) { - ctx.query = { where: { id: { neq: existingInstance.id }}}; + ctx.query = {where: {id: {neq: existingInstance.id}}}; next(); }); @@ -2795,12 +2796,12 @@ module.exports = function(dataSource, should, connectorCapabilities) { TestModel.observe('access', ctxRecorder.recordAndNext()); TestModel.updateAll( - { name: 'searched' }, - { name: 'updated' }, + {name: 'searched'}, + {name: 'updated'}, function(err, instance) { if (err) return done(err); - ctxRecorder.records.should.eql(aCtxForModel(TestModel, { query: { - where: { name: 'searched' }, + ctxRecorder.records.should.eql(aCtxForModel(TestModel, {query: { + where: {name: 'searched'}, }})); done(); }); @@ -2808,20 +2809,20 @@ module.exports = function(dataSource, should, connectorCapabilities) { it('applies updates from `access` hook', function(done) { TestModel.observe('access', function(ctx, next) { - ctx.query = { where: { id: { neq: existingInstance.id }}}; + ctx.query = {where: {id: {neq: existingInstance.id}}}; next(); }); TestModel.updateAll( - { id: existingInstance.id }, - { name: 'new name' }, + {id: existingInstance.id}, + {name: 'new name'}, function(err) { if (err) return done(err); - findTestModels({ fields: ['id', 'name'] }, function(err, list) { + findTestModels({fields: ['id', 'name']}, function(err, list) { if (err) return done(err); (list || []).map(toObject).should.eql([ - { id: existingInstance.id, name: existingInstance.name, extra: undefined }, - { id: '2', name: 'new name', extra: undefined }, + {id: existingInstance.id, name: existingInstance.name, extra: undefined}, + {id: '2', name: 'new name', extra: undefined}, ]); done(); }); @@ -2832,13 +2833,13 @@ module.exports = function(dataSource, should, connectorCapabilities) { TestModel.observe('before save', ctxRecorder.recordAndNext()); TestModel.updateAll( - { name: 'searched' }, - { name: 'updated' }, + {name: 'searched'}, + {name: 'updated'}, function(err, instance) { if (err) return done(err); ctxRecorder.records.should.eql(aCtxForModel(TestModel, { - where: { name: 'searched' }, - data: { name: 'updated' }, + where: {name: 'searched'}, + data: {name: 'updated'}, })); done(); }); @@ -2846,13 +2847,13 @@ module.exports = function(dataSource, should, connectorCapabilities) { it('applies updates from `before save` hook', function(done) { TestModel.observe('before save', function(ctx, next) { - ctx.data = { name: 'hooked', extra: 'added' }; + ctx.data = {name: 'hooked', extra: 'added'}; next(); }); TestModel.updateAll( - { id: existingInstance.id }, - { name: 'updated name' }, + {id: existingInstance.id}, + {name: 'updated name'}, function(err) { if (err) return done(err); loadTestModel(existingInstance.id, function(err, instance) { @@ -2868,14 +2869,14 @@ module.exports = function(dataSource, should, connectorCapabilities) { TestModel.observe('persist', ctxRecorder.recordAndNext()); TestModel.updateAll( - { name: existingInstance.name }, - { name: 'changed' }, + {name: existingInstance.name}, + {name: 'changed'}, function(err, instance) { if (err) return done(err); ctxRecorder.records.should.eql(aCtxForModel(TestModel, { - data: { name: 'changed' }, - where: { name: existingInstance.name }, + data: {name: 'changed'}, + where: {name: existingInstance.name}, })); done(); @@ -2888,8 +2889,8 @@ module.exports = function(dataSource, should, connectorCapabilities) { })); TestModel.updateAll( - { id: existingInstance.id }, - { name: 'changed' }, + {id: existingInstance.id}, + {name: 'changed'}, function(err) { if (err) return done(err); loadTestModel(existingInstance.id, function(err, instance) { @@ -2903,8 +2904,8 @@ module.exports = function(dataSource, should, connectorCapabilities) { TestModel.observe('loaded', ctxRecorder.recordAndNext()); TestModel.updateAll( - { id: existingInstance.id }, - { name: 'changed' }, + {id: existingInstance.id}, + {name: 'changed'}, function(err, instance) { if (err) return done(err); ctxRecorder.records.should.eql('hook not called'); @@ -2916,13 +2917,13 @@ module.exports = function(dataSource, should, connectorCapabilities) { TestModel.observe('after save', ctxRecorder.recordAndNext()); TestModel.updateAll( - { id: existingInstance.id }, - { name: 'updated name' }, + {id: existingInstance.id}, + {name: 'updated name'}, function(err) { if (err) return done(err); ctxRecorder.records.should.eql(aCtxForModel(TestModel, { - where: { id: existingInstance.id }, - data: { name: 'updated name' }, + where: {id: existingInstance.id}, + data: {name: 'updated name'}, })); done(); }); @@ -2932,9 +2933,9 @@ module.exports = function(dataSource, should, connectorCapabilities) { TestModel.observe('after save', ctxRecorder.recordAndNext()); TestModel.updateAll( - { id: existingInstance.id }, - { name: 'updated name' }, - { foo: 'bar' }, + {id: existingInstance.id}, + {name: 'updated name'}, + {foo: 'bar'}, function(err) { if (err) return done(err); ctxRecorder.records.options.should.eql({ @@ -2949,8 +2950,8 @@ module.exports = function(dataSource, should, connectorCapabilities) { describe('PersistedModel.upsertWithWhere', function() { it('triggers hooks in the correct order on create', function(done) { monitorHookExecution(); - TestModel.upsertWithWhere({ extra: 'not-found' }, - { id: 'not-found', name: 'not found', extra: 'not-found' }, + TestModel.upsertWithWhere({extra: 'not-found'}, + {id: 'not-found', name: 'not found', extra: 'not-found'}, function(err, record, created) { if (err) return done(err); hookMonitor.names.should.eql([ @@ -2971,8 +2972,8 @@ module.exports = function(dataSource, should, connectorCapabilities) { it('triggers hooks in the correct order on update', function(done) { monitorHookExecution(); - TestModel.upsertWithWhere({ id: existingInstance.id }, - { name: 'new name', extra: 'new extra' }, + TestModel.upsertWithWhere({id: existingInstance.id}, + {name: 'new name', extra: 'new extra'}, function(err, record, created) { if (err) return done(err); hookMonitor.names.should.eql([ @@ -2994,12 +2995,12 @@ module.exports = function(dataSource, should, connectorCapabilities) { it('triggers `access` hook on create', function(done) { TestModel.observe('access', ctxRecorder.recordAndNext()); - TestModel.upsertWithWhere({ extra: 'not-found' }, - { id: 'not-found', name: 'not found' }, + TestModel.upsertWithWhere({extra: 'not-found'}, + {id: 'not-found', name: 'not found'}, function(err, instance) { if (err) return done(err); - ctxRecorder.records.should.eql(aCtxForModel(TestModel, { query: { - where: { extra: 'not-found' }, + ctxRecorder.records.should.eql(aCtxForModel(TestModel, {query: { + where: {extra: 'not-found'}, }})); done(); }); @@ -3008,12 +3009,12 @@ module.exports = function(dataSource, should, connectorCapabilities) { it('triggers `access` hook on update', function(done) { TestModel.observe('access', ctxRecorder.recordAndNext()); - TestModel.upsertWithWhere({ id: existingInstance.id }, - { name: 'new name', extra: 'new extra' }, + TestModel.upsertWithWhere({id: existingInstance.id}, + {name: 'new name', extra: 'new extra'}, function(err, instance) { if (err) return done(err); - ctxRecorder.records.should.eql(aCtxForModel(TestModel, { query: { - where: { id: existingInstance.id }, + ctxRecorder.records.should.eql(aCtxForModel(TestModel, {query: { + where: {id: existingInstance.id}, }})); done(); }); @@ -3023,12 +3024,12 @@ module.exports = function(dataSource, should, connectorCapabilities) { monitorHookExecution(['access', 'before save']); TestModel.observe('access', function(ctx, next) { - ctx.query = { where: { id: { neq: existingInstance.id }}}; + ctx.query = {where: {id: {neq: existingInstance.id}}}; next(); }); - TestModel.upsertWithWhere({ id: existingInstance.id }, - { id: 'ignored', name: 'new name' }, + TestModel.upsertWithWhere({id: existingInstance.id}, + {id: 'ignored', name: 'new name'}, function(err, instance) { if (err) return done(err); hookMonitor.names.should.eql(['access', 'before save']); @@ -3038,19 +3039,19 @@ module.exports = function(dataSource, should, connectorCapabilities) { it('applies updates from `access` hook when found', function(done) { TestModel.observe('access', function(ctx, next) { - ctx.query = { where: { id: { neq: existingInstance.id }}}; + ctx.query = {where: {id: {neq: existingInstance.id}}}; next(); }); - TestModel.upsertWithWhere({ id: existingInstance.id }, - { name: 'new name' }, + TestModel.upsertWithWhere({id: existingInstance.id}, + {name: 'new name'}, function(err, instance) { if (err) return done(err); - findTestModels({ fields: ['id', 'name'] }, function(err, list) { + findTestModels({fields: ['id', 'name']}, function(err, list) { if (err) return done(err); (list || []).map(toObject).should.eql([ - { id: existingInstance.id, name: existingInstance.name, extra: undefined }, - { id: instance.id, name: 'new name', extra: undefined }, + {id: existingInstance.id, name: existingInstance.name, extra: undefined}, + {id: instance.id, name: 'new name', extra: undefined}, ]); done(); }); @@ -3059,20 +3060,20 @@ module.exports = function(dataSource, should, connectorCapabilities) { it('applies updates from `access` hook when not found', function(done) { TestModel.observe('access', function(ctx, next) { - ctx.query = { where: { id: 'not-found' }}; + ctx.query = {where: {id: 'not-found'}}; next(); }); - TestModel.upsertWithWhere({ id: existingInstance.id }, - { name: 'new name' }, + TestModel.upsertWithWhere({id: existingInstance.id}, + {name: 'new name'}, function(err, instance) { if (err) return done(err); - findTestModels({ fields: ['id', 'name'] }, function(err, list) { + findTestModels({fields: ['id', 'name']}, function(err, list) { if (err) return done(err); (list || []).map(toObject).should.eql([ - { id: existingInstance.id, name: existingInstance.name, extra: undefined }, - { id: list[1].id, name: 'second', extra: undefined }, - { id: instance.id, name: 'new name', extra: undefined }, + {id: existingInstance.id, name: existingInstance.name, extra: undefined}, + {id: list[1].id, name: 'second', extra: undefined}, + {id: instance.id, name: 'new name', extra: undefined}, ]); done(); }); @@ -3082,12 +3083,12 @@ module.exports = function(dataSource, should, connectorCapabilities) { it('triggers `before save` hook on update', function(done) { TestModel.observe('before save', ctxRecorder.recordAndNext()); - TestModel.upsertWithWhere({ id: existingInstance.id }, - { id: existingInstance.id, name: 'updated name' }, + TestModel.upsertWithWhere({id: existingInstance.id}, + {id: existingInstance.id, name: 'updated name'}, function(err, instance) { if (err) return done(err); var expectedContext = aCtxForModel(TestModel, { - where: { id: existingInstance.id }, + where: {id: existingInstance.id}, data: { id: existingInstance.id, name: 'updated name', @@ -3104,13 +3105,13 @@ module.exports = function(dataSource, should, connectorCapabilities) { it('triggers `before save` hook on create', function(done) { TestModel.observe('before save', ctxRecorder.recordAndNext()); - TestModel.upsertWithWhere({ id: 'new-id' }, - { id: 'new-id', name: 'a name' }, + TestModel.upsertWithWhere({id: 'new-id'}, + {id: 'new-id', name: 'a name'}, function(err, instance) { if (err) return done(err); var expectedContext = aCtxForModel(TestModel, { - where: { id: 'new-id' }, - data: { id: 'new-id', name: 'a name' }, + where: {id: 'new-id'}, + data: {id: 'new-id', name: 'a name'}, }); if (!dataSource.connector.upsertWithWhere) { ctxRecorder.records.should.eql(expectedContext.isNewInstance = true); @@ -3126,8 +3127,8 @@ module.exports = function(dataSource, should, connectorCapabilities) { next(); }); - TestModel.upsertWithWhere({ id: existingInstance.id }, - { name: 'updated name' }, + TestModel.upsertWithWhere({id: existingInstance.id}, + {name: 'updated name'}, function(err, instance) { if (err) return done(err); instance.name.should.equal('hooked'); @@ -3145,8 +3146,8 @@ module.exports = function(dataSource, should, connectorCapabilities) { next(); }); - TestModel.upsertWithWhere({ id: 'new-id' }, - { id: 'new-id', name: 'new name' }, + TestModel.upsertWithWhere({id: 'new-id'}, + {id: 'new-id', name: 'new name'}, function(err, instance) { if (err) return done(err); instance.name.should.equal('hooked'); @@ -3157,11 +3158,11 @@ module.exports = function(dataSource, should, connectorCapabilities) { it('validates model after `before save` hook on create', function(done) { TestModel.observe('before save', invalidateTestModel()); - TestModel.upsertWithWhere({ id: 'new-id' }, - { id: 'new-id', name: 'new name' }, + TestModel.upsertWithWhere({id: 'new-id'}, + {id: 'new-id', name: 'new name'}, function(err, instance) { (err || {}).should.be.instanceOf(ValidationError); - (err.details.codes || {}).should.eql({ name: ['presence'] }); + (err.details.codes || {}).should.eql({name: ['presence']}); done(); }); }); @@ -3169,11 +3170,11 @@ module.exports = function(dataSource, should, connectorCapabilities) { it('validates model after `before save` hook on update', function(done) { TestModel.observe('before save', invalidateTestModel()); - TestModel.upsertWithWhere({ id: existingInstance.id }, - { id: existingInstance.id, name: 'updated name' }, + TestModel.upsertWithWhere({id: existingInstance.id}, + {id: existingInstance.id, name: 'updated name'}, function(err, instance) { (err || {}).should.be.instanceOf(ValidationError); - (err.details.codes || {}).should.eql({ name: ['presence'] }); + (err.details.codes || {}).should.eql({name: ['presence']}); done(); }); }); @@ -3181,13 +3182,13 @@ module.exports = function(dataSource, should, connectorCapabilities) { it('triggers `persist` hook on create', function(done) { TestModel.observe('persist', ctxRecorder.recordAndNext()); - TestModel.upsertWithWhere({ id: 'new-id' }, - { id: 'new-id', name: 'a name' }, + TestModel.upsertWithWhere({id: 'new-id'}, + {id: 'new-id', name: 'a name'}, function(err, instance) { if (err) return done(err); ctxRecorder.records.should.eql(aCtxForModel(TestModel, { - where: { id: 'new-id' }, - data: { id: 'new-id', name: 'a name' }, + where: {id: 'new-id'}, + data: {id: 'new-id', name: 'a name'}, currentInstance: { id: 'new-id', name: 'a name', @@ -3201,12 +3202,12 @@ module.exports = function(dataSource, should, connectorCapabilities) { it('triggers persist hook on update', function(done) { TestModel.observe('persist', ctxRecorder.recordAndNext()); - TestModel.upsertWithWhere({ id: existingInstance.id }, - { id: existingInstance.id, name: 'updated name' }, + TestModel.upsertWithWhere({id: existingInstance.id}, + {id: existingInstance.id, name: 'updated name'}, function(err, instance) { if (err) return done(err); var expectedContext = aCtxForModel(TestModel, { - where: { id: existingInstance.id }, + where: {id: existingInstance.id}, data: { id: existingInstance.id, name: 'updated name', @@ -3228,12 +3229,12 @@ module.exports = function(dataSource, should, connectorCapabilities) { it('triggers `loaded` hook on create', function(done) { TestModel.observe('loaded', ctxRecorder.recordAndNext()); - TestModel.upsertWithWhere({ id: 'new-id' }, - { id: 'new-id', name: 'a name' }, + TestModel.upsertWithWhere({id: 'new-id'}, + {id: 'new-id', name: 'a name'}, function(err, instance) { if (err) return done(err); ctxRecorder.records.should.eql(aCtxForModel(TestModel, { - data: { id: 'new-id', name: 'a name' }, + data: {id: 'new-id', name: 'a name'}, isNewInstance: true, })); done(); @@ -3243,8 +3244,8 @@ module.exports = function(dataSource, should, connectorCapabilities) { it('triggers `loaded` hook on update', function(done) { TestModel.observe('loaded', ctxRecorder.recordAndNext()); - TestModel.upsertWithWhere({ id: existingInstance.id }, - { id: existingInstance.id, name: 'updated name' }, + TestModel.upsertWithWhere({id: existingInstance.id}, + {id: existingInstance.id, name: 'updated name'}, function(err, instance) { if (err) return done(err); ctxRecorder.records.should.eql(aCtxForModel(TestModel, { @@ -3260,8 +3261,8 @@ module.exports = function(dataSource, should, connectorCapabilities) { it('emits error when `loaded` hook fails', function(done) { TestModel.observe('loaded', nextWithError(expectedError)); - TestModel.upsertWithWhere({ id: 'new-id' }, - { id: 'new-id', name: 'a name' }, + TestModel.upsertWithWhere({id: 'new-id'}, + {id: 'new-id', name: 'a name'}, function(err, instance) { [err].should.eql([expectedError]); done(); @@ -3271,8 +3272,8 @@ module.exports = function(dataSource, should, connectorCapabilities) { it('triggers `after save` hook on update', function(done) { TestModel.observe('after save', ctxRecorder.recordAndNext()); - TestModel.upsertWithWhere({ id: existingInstance.id }, - { id: existingInstance.id, name: 'updated name' }, + TestModel.upsertWithWhere({id: existingInstance.id}, + {id: existingInstance.id, name: 'updated name'}, function(err, instance) { if (err) return done(err); ctxRecorder.records.should.eql(aCtxForModel(TestModel, { @@ -3290,8 +3291,8 @@ module.exports = function(dataSource, should, connectorCapabilities) { it('triggers `after save` hook on create', function(done) { TestModel.observe('after save', ctxRecorder.recordAndNext()); - TestModel.upsertWithWhere({ id: 'new-id' }, - { id: 'new-id', name: 'a name' }, function(err, instance) { + TestModel.upsertWithWhere({id: 'new-id'}, + {id: 'new-id', name: 'a name'}, function(err, instance) { if (err) return done(err); ctxRecorder.records.should.eql(aCtxForModel(TestModel, { instance: { @@ -3329,11 +3330,11 @@ module.exports = function(dataSource, should, connectorCapabilities) { query = null; } - TestModel.find(query, { notify: false }, cb); + TestModel.find(query, {notify: false}, cb); } function loadTestModel(id, cb) { - TestModel.findOne({ where: { id: id }}, { notify: false }, cb); + TestModel.findOne({where: {id: id}}, {notify: false}, cb); } function monitorHookExecution(hookNames) { diff --git a/test/relations.test.js b/test/relations.test.js index 510377e2..47a8ad4c 100644 --- a/test/relations.test.js +++ b/test/relations.test.js @@ -4,6 +4,7 @@ // License text available at https://opensource.org/licenses/MIT // This test written in mocha+should.js +'use strict'; var should = require('./init.js'); var jdb = require('../'); var DataSource = jdb.DataSource; @@ -31,19 +32,19 @@ describe('relations', function() { describe('hasMany', function() { before(function(done) { - Book = db.define('Book', { name: String, type: String }); - Chapter = db.define('Chapter', { name: { type: String, index: true }, - bookType: String }); - Author = db.define('Author', { name: String }); - Reader = db.define('Reader', { name: String }); + Book = db.define('Book', {name: String, type: String}); + Chapter = db.define('Chapter', {name: {type: String, index: true}, + bookType: String}); + Author = db.define('Author', {name: String}); + Reader = db.define('Reader', {name: String}); db.automigrate(['Book', 'Chapter', 'Author', 'Reader'], done); }); it('can be declared in different ways', function(done) { Book.hasMany(Chapter); - Book.hasMany(Reader, { as: 'users' }); - Book.hasMany(Author, { foreignKey: 'projectId' }); + Book.hasMany(Reader, {as: 'users'}); + Book.hasMany(Author, {foreignKey: 'projectId'}); var b = new Book; b.chapters.should.be.an.instanceOf(Function); b.users.should.be.an.instanceOf(Function); @@ -102,9 +103,9 @@ describe('relations', function() { it('should create a batch of records on scope', function(done) { var chapters = [ - { name: 'a' }, - { name: 'z' }, - { name: 'c' }, + {name: 'a'}, + {name: 'z'}, + {name: 'c'}, ]; Book.create(function(err, book) { book.chapters.create(chapters, function(err, chs) { @@ -121,9 +122,9 @@ describe('relations', function() { it('should create a batch of records on scope with promises', function(done) { var chapters = [ - { name: 'a' }, - { name: 'z' }, - { name: 'c' }, + {name: 'a'}, + {name: 'z'}, + {name: 'c'}, ]; Book.create(function(err, book) { book.chapters.create(chapters) @@ -140,9 +141,9 @@ describe('relations', function() { it('should fetch all scoped instances', function(done) { Book.create(function(err, book) { - book.chapters.create({ name: 'a' }, function() { - book.chapters.create({ name: 'z' }, function() { - book.chapters.create({ name: 'c' }, function() { + book.chapters.create({name: 'a'}, function() { + book.chapters.create({name: 'z'}, function() { + book.chapters.create({name: 'c'}, function() { verify(book); }); }); @@ -157,7 +158,7 @@ describe('relations', function() { var chapters = book.chapters(); chapters.should.eql(ch); - book.chapters({ order: 'name DESC' }, function(e, c) { + book.chapters({order: 'name DESC'}, function(e, c) { should.not.exist(e); should.exist(c); @@ -172,12 +173,12 @@ describe('relations', function() { it('should fetch all scoped instances with promises', function(done) { Book.create() .then(function(book) { - return book.chapters.create({ name: 'a' }) + return book.chapters.create({name: 'a'}) .then(function() { - return book.chapters.create({ name: 'z' }); + return book.chapters.create({name: 'z'}); }) .then(function() { - return book.chapters.create({ name: 'c' }); + return book.chapters.create({name: 'c'}); }) .then(function() { return verify(book); @@ -193,7 +194,7 @@ describe('relations', function() { var chapters = book.chapters(); chapters.should.eql(ch); - return book.chapters.getAsync({ order: 'name DESC' }) + return book.chapters.getAsync({order: 'name DESC'}) .then(function(c) { should.exist(c); @@ -207,9 +208,9 @@ describe('relations', function() { it('should fetch all scoped instances with getAsync with callback and condition', function(done) { Book.create(function(err, book) { - book.chapters.create({ name: 'a' }, function() { - book.chapters.create({ name: 'z' }, function() { - book.chapters.create({ name: 'c' }, function() { + book.chapters.create({name: 'a'}, function() { + book.chapters.create({name: 'z'}, function() { + book.chapters.create({name: 'c'}, function() { verify(book); }); }); @@ -224,7 +225,7 @@ describe('relations', function() { var chapters = book.chapters(); chapters.should.eql(ch); - book.chapters.getAsync({ order: 'name DESC' }, function(e, c) { + book.chapters.getAsync({order: 'name DESC'}, function(e, c) { should.not.exist(e); should.exist(c); @@ -238,9 +239,9 @@ describe('relations', function() { it('should fetch all scoped instances with getAsync with callback and no condition', function(done) { Book.create(function(err, book) { - book.chapters.create({ name: 'a' }, function() { - book.chapters.create({ name: 'z' }, function() { - book.chapters.create({ name: 'c' }, function() { + book.chapters.create({name: 'a'}, function() { + book.chapters.create({name: 'z'}, function() { + book.chapters.create({name: 'c'}, function() { verify(book); }); }); @@ -270,10 +271,10 @@ describe('relations', function() { it('should find scoped record', function(done) { var id; Book.create(function(err, book) { - book.chapters.create({ name: 'a' }, function(err, ch) { + book.chapters.create({name: 'a'}, function(err, ch) { id = ch.id; - book.chapters.create({ name: 'z' }, function() { - book.chapters.create({ name: 'c' }, function() { + book.chapters.create({name: 'z'}, function() { + book.chapters.create({name: 'c'}, function() { verify(book); }); }); @@ -294,13 +295,13 @@ describe('relations', function() { var id; Book.create() .then(function(book) { - return book.chapters.create({ name: 'a' }) + return book.chapters.create({name: 'a'}) .then(function(ch) { id = ch.id; - return book.chapters.create({ name: 'z' }); + return book.chapters.create({name: 'z'}); }) .then(function() { - return book.chapters.create({ name: 'c' }); + return book.chapters.create({name: 'c'}); }) .then(function() { return verify(book); @@ -319,9 +320,9 @@ describe('relations', function() { it('should count scoped records - all and filtered', function(done) { Book.create(function(err, book) { - book.chapters.create({ name: 'a' }, function(err, ch) { - book.chapters.create({ name: 'b' }, function() { - book.chapters.create({ name: 'c' }, function() { + book.chapters.create({name: 'a'}, function(err, ch) { + book.chapters.create({name: 'b'}, function() { + book.chapters.create({name: 'c'}, function() { verify(book); }); }); @@ -332,7 +333,7 @@ describe('relations', function() { book.chapters.count(function(err, count) { should.not.exist(err); count.should.equal(3); - book.chapters.count({ name: 'b' }, function(err, count) { + book.chapters.count({name: 'b'}, function(err, count) { should.not.exist(err); count.should.equal(1); done(); @@ -344,12 +345,12 @@ describe('relations', function() { it('should count scoped records - all and filtered with promises', function(done) { Book.create() .then(function(book) { - book.chapters.create({ name: 'a' }) + book.chapters.create({name: 'a'}) .then(function() { - return book.chapters.create({ name: 'b' }); + return book.chapters.create({name: 'b'}); }) .then(function() { - return book.chapters.create({ name: 'c' }); + return book.chapters.create({name: 'c'}); }) .then(function() { return verify(book); @@ -360,7 +361,7 @@ describe('relations', function() { return book.chapters.count() .then(function(count) { count.should.equal(3); - return book.chapters.count({ name: 'b' }); + return book.chapters.count({name: 'b'}); }) .then(function(count) { count.should.equal(1); @@ -376,9 +377,9 @@ describe('relations', function() { it('should update scoped record', function(done) { var id; Book.create(function(err, book) { - book.chapters.create({ name: 'a' }, function(err, ch) { + book.chapters.create({name: 'a'}, function(err, ch) { id = ch.id; - book.chapters.updateById(id, { name: 'aa' }, function(err, ch) { + book.chapters.updateById(id, {name: 'aa'}, function(err, ch) { verify(book); }); }); @@ -399,10 +400,10 @@ describe('relations', function() { var id; Book.create() .then(function(book) { - return book.chapters.create({ name: 'a' }) + return book.chapters.create({name: 'a'}) .then(function(ch) { id = ch.id; - return book.chapters.updateById(id, { name: 'aa' }); + return book.chapters.updateById(id, {name: 'aa'}); }) .then(function(ch) { return verify(book); @@ -424,7 +425,7 @@ describe('relations', function() { it('should destroy scoped record', function(done) { var id; Book.create(function(err, book) { - book.chapters.create({ name: 'a' }, function(err, ch) { + book.chapters.create({name: 'a'}, function(err, ch) { id = ch.id; book.chapters.destroy(id, function(err, ch) { verify(book); @@ -444,7 +445,7 @@ describe('relations', function() { var id; Book.create() .then(function(book) { - return book.chapters.create({ name: 'a' }) + return book.chapters.create({name: 'a'}) .then(function(ch) { id = ch.id; return book.chapters.destroy(id); @@ -467,10 +468,10 @@ describe('relations', function() { it('should check existence of a scoped record', function(done) { var id; Book.create(function(err, book) { - book.chapters.create({ name: 'a' }, function(err, ch) { + book.chapters.create({name: 'a'}, function(err, ch) { id = ch.id; - book.chapters.create({ name: 'z' }, function() { - book.chapters.create({ name: 'c' }, function() { + book.chapters.create({name: 'z'}, function() { + book.chapters.create({name: 'c'}, function() { verify(book); }); }); @@ -490,13 +491,13 @@ describe('relations', function() { var id; Book.create() .then(function(book) { - return book.chapters.create({ name: 'a' }) + return book.chapters.create({name: 'a'}) .then(function(ch) { id = ch.id; - return book.chapters.create({ name: 'z' }); + return book.chapters.create({name: 'z'}); }) .then(function() { - return book.chapters.create({ name: 'c' }); + return book.chapters.create({name: 'c'}); }) .then(function() { return verify(book); @@ -513,7 +514,7 @@ describe('relations', function() { }); it('should check ignore related data on creation - array', function(done) { - Book.create({ chapters: [] }, function(err, book) { + Book.create({chapters: []}, function(err, book) { should.not.exist(err); book.chapters.should.be.a.function; var obj = book.toObject(); @@ -523,7 +524,7 @@ describe('relations', function() { }); it('should check ignore related data on creation with promises - array', function(done) { - Book.create({ chapters: [] }) + Book.create({chapters: []}) .then(function(book) { book.chapters.should.be.a.function; var obj = book.toObject(); @@ -533,7 +534,7 @@ describe('relations', function() { }); it('should check ignore related data on creation - object', function(done) { - Book.create({ chapters: {}}, function(err, book) { + Book.create({chapters: {}}, function(err, book) { should.not.exist(err); book.chapters.should.be.a.function; var obj = book.toObject(); @@ -543,7 +544,7 @@ describe('relations', function() { }); it('should check ignore related data on creation with promises - object', function(done) { - Book.create({ chapters: {}}) + Book.create({chapters: {}}) .then(function(book) { book.chapters.should.be.a.function; var obj = book.toObject(); @@ -560,16 +561,16 @@ describe('relations', function() { before(function(done) { // db = getSchema(); - Physician = db.define('Physician', { name: String }); - Patient = db.define('Patient', { name: String }); - Appointment = db.define('Appointment', { date: { type: Date, + Physician = db.define('Physician', {name: String}); + Patient = db.define('Patient', {name: String}); + Appointment = db.define('Appointment', {date: {type: Date, default: function() { return new Date(); - } }}); - Address = db.define('Address', { name: String }); + }}}); + Address = db.define('Address', {name: String}); - Physician.hasMany(Patient, { through: Appointment }); - Patient.hasMany(Physician, { through: Appointment }); + Physician.hasMany(Patient, {through: Appointment}); + Patient.hasMany(Physician, {through: Appointment}); Patient.belongsTo(Address); Appointment.belongsTo(Patient); Appointment.belongsTo(Physician); @@ -590,7 +591,7 @@ describe('relations', function() { physician.patients.create(function(err, patient) { should.not.exist(err); should.exist(patient); - Appointment.find({ where: { physicianId: physician.id, patientId: patient.id }}, + Appointment.find({where: {physicianId: physician.id, patientId: patient.id}}, function(err, apps) { should.not.exist(err); apps.should.have.lengthOf(1); @@ -606,7 +607,7 @@ describe('relations', function() { return physician.patients.create() .then(function(patient) { should.exist(patient); - return Appointment.find({ where: { physicianId: physician.id, patientId: patient.id }}) + return Appointment.find({where: {physicianId: physician.id, patientId: patient.id}}) .then(function(apps) { apps.should.have.lengthOf(1); done(); @@ -623,7 +624,7 @@ describe('relations', function() { should.exist(patients); patients.should.have.lengthOf(2); function verifyPatient(patient, next) { - Appointment.find({ where: { + Appointment.find({where: { physicianId: physician.id, patientId: patient.id, }}, @@ -647,7 +648,7 @@ describe('relations', function() { should.exist(patients); patients.should.have.lengthOf(2); function verifyPatient(patient, next) { - Appointment.find({ where: { + Appointment.find({where: { physicianId: physician.id, patientId: patient.id, }}) @@ -663,9 +664,9 @@ describe('relations', function() { it('should fetch all scoped instances', function(done) { Physician.create(function(err, physician) { - physician.patients.create({ name: 'a' }, function() { - physician.patients.create({ name: 'z' }, function() { - physician.patients.create({ name: 'c' }, function() { + physician.patients.create({name: 'a'}, function() { + physician.patients.create({name: 'z'}, function() { + physician.patients.create({name: 'c'}, function() { verify(physician); }); }); @@ -688,12 +689,12 @@ describe('relations', function() { it('should fetch all scoped instances with promises', function(done) { Physician.create() .then(function(physician) { - return physician.patients.create({ name: 'a' }) + return physician.patients.create({name: 'a'}) .then(function() { - return physician.patients.create({ name: 'z' }); + return physician.patients.create({name: 'z'}); }) .then(function() { - return physician.patients.create({ name: 'c' }); + return physician.patients.create({name: 'c'}); }) .then(function() { return verify(physician); @@ -715,9 +716,9 @@ describe('relations', function() { it('should fetch scoped instances with paging filters', function(done) { Physician.create(function(err, physician) { - physician.patients.create({ name: 'a' }, function() { - physician.patients.create({ name: 'z' }, function() { - physician.patients.create({ name: 'c' }, function() { + physician.patients.create({name: 'a'}, function() { + physician.patients.create({name: 'z'}, function() { + physician.patients.create({name: 'c'}, function() { verify(physician); }); }); @@ -725,19 +726,19 @@ describe('relations', function() { }); function verify(physician) { //limit plus skip - physician.patients({ limit: 1, skip: 1 }, function(err, ch) { + physician.patients({limit: 1, skip: 1}, function(err, ch) { should.not.exist(err); should.exist(ch); ch.should.have.lengthOf(1); ch[0].name.should.eql('z'); //offset plus skip - physician.patients({ limit: 1, offset: 1 }, function(err1, ch1) { + physician.patients({limit: 1, offset: 1}, function(err1, ch1) { should.not.exist(err1); should.exist(ch1); ch1.should.have.lengthOf(1); ch1[0].name.should.eql('z'); //order - physician.patients({ order: 'patientId DESC' }, function(err2, ch2) { + physician.patients({order: 'patientId DESC'}, function(err2, ch2) { should.not.exist(err2); should.exist(ch2); ch2.should.have.lengthOf(3); @@ -752,10 +753,10 @@ describe('relations', function() { it('should find scoped record', function(done) { var id; Physician.create(function(err, physician) { - physician.patients.create({ name: 'a' }, function(err, ch) { + physician.patients.create({name: 'a'}, function(err, ch) { id = ch.id; - physician.patients.create({ name: 'z' }, function() { - physician.patients.create({ name: 'c' }, function() { + physician.patients.create({name: 'z'}, function() { + physician.patients.create({name: 'c'}, function() { verify(physician); }); }); @@ -776,13 +777,13 @@ describe('relations', function() { var id; Physician.create() .then(function(physician) { - return physician.patients.create({ name: 'a' }) + return physician.patients.create({name: 'a'}) .then(function(ch) { id = ch.id; - return physician.patients.create({ name: 'z' }); + return physician.patients.create({name: 'z'}); }) .then(function() { - return physician.patients.create({ name: 'c' }); + return physician.patients.create({name: 'c'}); }) .then(function() { return verify(physician); @@ -801,8 +802,8 @@ describe('relations', function() { it('should allow to use include syntax on related data', function(done) { Physician.create(function(err, physician) { - physician.patients.create({ name: 'a' }, function(err, patient) { - Address.create({ name: 'z' }, function(err, address) { + physician.patients.create({name: 'a'}, function(err, patient) { + Address.create({name: 'z'}, function(err, address) { should.not.exist(err); patient.address(address); patient.save(function() { @@ -812,7 +813,7 @@ describe('relations', function() { }); }); function verify(physician, addressId) { - physician.patients({ include: 'address' }, function(err, ch) { + physician.patients({include: 'address'}, function(err, ch) { should.not.exist(err); should.exist(ch); ch.should.have.lengthOf(1); @@ -829,9 +830,9 @@ describe('relations', function() { it('should allow to use include syntax on related data with promises', function(done) { Physician.create() .then(function(physician) { - return physician.patients.create({ name: 'a' }) + return physician.patients.create({name: 'a'}) .then(function(patient) { - return Address.create({ name: 'z' }) + return Address.create({name: 'z'}) .then(function(address) { patient.address(address); return patient.save() @@ -843,7 +844,7 @@ describe('relations', function() { }).catch(done); function verify(physician, addressId) { - return physician.patients.getAsync({ include: 'address' }) + return physician.patients.getAsync({include: 'address'}) .then(function(ch) { should.exist(ch); ch.should.have.lengthOf(1); @@ -864,9 +865,9 @@ describe('relations', function() { it('should update scoped record', function(done) { var id; Physician.create(function(err, physician) { - physician.patients.create({ name: 'a' }, function(err, ch) { + physician.patients.create({name: 'a'}, function(err, ch) { id = ch.id; - physician.patients.updateById(id, { name: 'aa' }, function(err, ch) { + physician.patients.updateById(id, {name: 'aa'}, function(err, ch) { verify(physician); }); }); @@ -887,10 +888,10 @@ describe('relations', function() { var id; Physician.create() .then(function(physician) { - return physician.patients.create({ name: 'a' }) + return physician.patients.create({name: 'a'}) .then(function(ch) { id = ch.id; - return physician.patients.updateById(id, { name: 'aa' }) + return physician.patients.updateById(id, {name: 'aa'}) .then(function(ch) { return verify(physician); }); @@ -911,7 +912,7 @@ describe('relations', function() { it('should destroy scoped record', function(done) { var id; Physician.create(function(err, physician) { - physician.patients.create({ name: 'a' }, function(err, ch) { + physician.patients.create({name: 'a'}, function(err, ch) { id = ch.id; physician.patients.destroy(id, function(err, ch) { verify(physician); @@ -931,7 +932,7 @@ describe('relations', function() { var id; Physician.create() .then(function(physician) { - return physician.patients.create({ name: 'a' }) + return physician.patients.create({name: 'a'}) .then(function(ch) { id = ch.id; return physician.patients.destroy(id) @@ -957,11 +958,11 @@ describe('relations', function() { it('should check existence of a scoped record', function(done) { var id; Physician.create(function(err, physician) { - physician.patients.create({ name: 'a' }, function(err, ch) { + physician.patients.create({name: 'a'}, function(err, ch) { should.not.exist(err); id = ch.id; - physician.patients.create({ name: 'z' }, function() { - physician.patients.create({ name: 'c' }, function() { + physician.patients.create({name: 'z'}, function() { + physician.patients.create({name: 'c'}, function() { verify(physician); }); }); @@ -981,13 +982,13 @@ describe('relations', function() { var id; Physician.create() .then(function(physician) { - return physician.patients.create({ name: 'a' }) + return physician.patients.create({name: 'a'}) .then(function(ch) { id = ch.id; - return physician.patients.create({ name: 'z' }); + return physician.patients.create({name: 'z'}); }) .then(function() { - return physician.patients.create({ name: 'c' }); + return physician.patients.create({name: 'c'}); }) .then(function() { return verify(physician); @@ -1004,8 +1005,8 @@ describe('relations', function() { }); it('should allow to add connection with instance', function(done) { - Physician.create({ name: 'ph1' }, function(e, physician) { - Patient.create({ name: 'pa1' }, function(e, patient) { + Physician.create({name: 'ph1'}, function(e, physician) { + Patient.create({name: 'pa1'}, function(e, patient) { physician.patients.add(patient, function(e, app) { should.not.exist(e); should.exist(app); @@ -1019,9 +1020,9 @@ describe('relations', function() { }); it('should allow to add connection with instance with promises', function(done) { - Physician.create({ name: 'ph1' }) + Physician.create({name: 'ph1'}) .then(function(physician) { - return Patient.create({ name: 'pa1' }) + return Patient.create({name: 'pa1'}) .then(function(patient) { return physician.patients.add(patient) .then(function(app) { @@ -1036,10 +1037,10 @@ describe('relations', function() { }); it('should allow to add connection with through data', function(done) { - Physician.create({ name: 'ph1' }, function(e, physician) { - Patient.create({ name: 'pa1' }, function(e, patient) { + Physician.create({name: 'ph1'}, function(e, physician) { + Patient.create({name: 'pa1'}, function(e, patient) { var now = Date.now(); - physician.patients.add(patient, { date: new Date(now) }, function(e, app) { + physician.patients.add(patient, {date: new Date(now)}, function(e, app) { should.not.exist(e); should.exist(app); app.should.be.an.instanceOf(Appointment); @@ -1054,12 +1055,12 @@ describe('relations', function() { }); it('should allow to add connection with through data with promises', function(done) { - Physician.create({ name: 'ph1' }) + Physician.create({name: 'ph1'}) .then(function(physician) { - return Patient.create({ name: 'pa1' }) + return Patient.create({name: 'pa1'}) .then(function(patient) { var now = Date.now(); - return physician.patients.add(patient, { date: new Date(now) }) + return physician.patients.add(patient, {date: new Date(now)}) .then(function(app) { should.exist(app); app.should.be.an.instanceOf(Appointment); @@ -1076,7 +1077,7 @@ describe('relations', function() { it('should allow to remove connection with instance', function(done) { var id; Physician.create(function(err, physician) { - physician.patients.create({ name: 'a' }, function(err, patient) { + physician.patients.create({name: 'a'}, function(err, patient) { id = patient.id; physician.patients.remove(id, function(err, ch) { verify(physician); @@ -1097,7 +1098,7 @@ describe('relations', function() { var id; Physician.create() .then(function(physician) { - return physician.patients.create({ name: 'a' }) + return physician.patients.create({name: 'a'}) .then(function(patient) { id = patient.id; return physician.patients.remove(id) @@ -1131,29 +1132,29 @@ describe('relations', function() { beforeEach(function(done) { // db = getSchema(); - Physician = db.define('Physician', { name: String }); - Patient = db.define('Patient', { name: String }); - Appointment = db.define('Appointment', { date: { type: Date, + Physician = db.define('Physician', {name: String}); + Patient = db.define('Patient', {name: String}); + Appointment = db.define('Appointment', {date: {type: Date, default: function() { return new Date(); - } }}); - Address = db.define('Address', { name: String }); + }}}); + Address = db.define('Address', {name: String}); db.automigrate(['Physician', 'Patient', 'Appointment', 'Address'], done); }); describe('with default options', function() { it('can determine the collect by modelTo\'s name as default', function() { - Physician.hasMany(Patient, { through: Appointment }); - Patient.hasMany(Physician, { through: Appointment, as: 'yyy' }); + Physician.hasMany(Patient, {through: Appointment}); + Patient.hasMany(Physician, {through: Appointment, as: 'yyy'}); Patient.belongsTo(Address); Appointment.belongsTo(Physician); Appointment.belongsTo(Patient); - var physician = new Physician({ id: 1 }); + var physician = new Physician({id: 1}); var scope1 = physician.patients._scope; scope1.should.have.property('collect', 'patient'); scope1.should.have.property('include', 'patient'); - var patient = new Patient({ id: 1 }); + var patient = new Patient({id: 1}); var scope2 = patient.yyy._scope; scope2.should.have.property('collect', 'physician'); scope2.should.have.property('include', 'physician'); @@ -1168,52 +1169,52 @@ describe('relations', function() { Patient.hasMany(Physician, { through: Appointment, foreignKey: 'barId', keyThrough: 'fooId', as: 'yyy', }); - Appointment.belongsTo(Physician, { as: 'foo' }); - Appointment.belongsTo(Patient, { as: 'bar' }); + Appointment.belongsTo(Physician, {as: 'foo'}); + Appointment.belongsTo(Patient, {as: 'bar'}); Patient.belongsTo(Address); // jam. - Appointment.belongsTo(Patient, { as: 'car' }); // jam. Should we complain in this case??? + Appointment.belongsTo(Patient, {as: 'car'}); // jam. Should we complain in this case??? - var physician = new Physician({ id: 1 }); + var physician = new Physician({id: 1}); var scope1 = physician.patients._scope; scope1.should.have.property('collect', 'bar'); scope1.should.have.property('include', 'bar'); - var patient = new Patient({ id: 1 }); + var patient = new Patient({id: 1}); var scope2 = patient.yyy._scope; scope2.should.have.property('collect', 'foo'); scope2.should.have.property('include', 'foo'); }); it('can determine the collect via modelTo name', function() { - Physician.hasMany(Patient, { through: Appointment }); - Patient.hasMany(Physician, { through: Appointment, as: 'yyy' }); - Appointment.belongsTo(Physician, { as: 'foo', foreignKey: 'physicianId' }); - Appointment.belongsTo(Patient, { as: 'bar', foreignKey: 'patientId' }); + Physician.hasMany(Patient, {through: Appointment}); + Patient.hasMany(Physician, {through: Appointment, as: 'yyy'}); + Appointment.belongsTo(Physician, {as: 'foo', foreignKey: 'physicianId'}); + Appointment.belongsTo(Patient, {as: 'bar', foreignKey: 'patientId'}); Patient.belongsTo(Address); // jam. - var physician = new Physician({ id: 1 }); + var physician = new Physician({id: 1}); var scope1 = physician.patients._scope; scope1.should.have.property('collect', 'bar'); scope1.should.have.property('include', 'bar'); - var patient = new Patient({ id: 1 }); + var patient = new Patient({id: 1}); var scope2 = patient.yyy._scope; scope2.should.have.property('collect', 'foo'); scope2.should.have.property('include', 'foo'); }); it('can determine the collect via modelTo name (with jams)', function() { - Physician.hasMany(Patient, { through: Appointment }); - Patient.hasMany(Physician, { through: Appointment, as: 'yyy' }); - Appointment.belongsTo(Physician, { as: 'foo', foreignKey: 'physicianId' }); - Appointment.belongsTo(Patient, { as: 'bar', foreignKey: 'patientId' }); + Physician.hasMany(Patient, {through: Appointment}); + Patient.hasMany(Physician, {through: Appointment, as: 'yyy'}); + Appointment.belongsTo(Physician, {as: 'foo', foreignKey: 'physicianId'}); + Appointment.belongsTo(Patient, {as: 'bar', foreignKey: 'patientId'}); Patient.belongsTo(Address); // jam. - Appointment.belongsTo(Physician, { as: 'goo', foreignKey: 'physicianId' }); // jam. Should we complain in this case??? - Appointment.belongsTo(Patient, { as: 'car', foreignKey: 'patientId' }); // jam. Should we complain in this case??? + Appointment.belongsTo(Physician, {as: 'goo', foreignKey: 'physicianId'}); // jam. Should we complain in this case??? + Appointment.belongsTo(Patient, {as: 'car', foreignKey: 'patientId'}); // jam. Should we complain in this case??? - var physician = new Physician({ id: 1 }); + var physician = new Physician({id: 1}); var scope1 = physician.patients._scope; scope1.should.have.property('collect', 'bar'); scope1.should.have.property('include', 'bar'); - var patient = new Patient({ id: 1 }); + var patient = new Patient({id: 1}); var scope2 = patient.yyy._scope; scope2.should.have.property('collect', 'foo'); // first matched relation scope2.should.have.property('include', 'foo'); // first matched relation @@ -1223,23 +1224,23 @@ describe('relations', function() { describe('when custom reverse belongsTo name for one side only', function() { beforeEach(function() { - Physician.hasMany(Patient, { as: 'xxx', through: Appointment, foreignKey: 'fooId' }); - Patient.hasMany(Physician, { as: 'yyy', through: Appointment, keyThrough: 'fooId' }); - Appointment.belongsTo(Physician, { as: 'foo' }); + Physician.hasMany(Patient, {as: 'xxx', through: Appointment, foreignKey: 'fooId'}); + Patient.hasMany(Physician, {as: 'yyy', through: Appointment, keyThrough: 'fooId'}); + Appointment.belongsTo(Physician, {as: 'foo'}); Appointment.belongsTo(Patient); Patient.belongsTo(Address); // jam. - Appointment.belongsTo(Physician, { as: 'bar' }); // jam. Should we complain in this case??? + Appointment.belongsTo(Physician, {as: 'bar'}); // jam. Should we complain in this case??? }); it('can determine the collect via model name', function() { - var physician = new Physician({ id: 1 }); + var physician = new Physician({id: 1}); var scope1 = physician.xxx._scope; scope1.should.have.property('collect', 'patient'); scope1.should.have.property('include', 'patient'); }); it('can determine the collect via keyThrough', function() { - var patient = new Patient({ id: 1 }); + var patient = new Patient({id: 1}); var scope2 = patient.yyy._scope; scope2.should.have.property('collect', 'foo'); scope2.should.have.property('include', 'foo'); @@ -1252,12 +1253,12 @@ describe('relations', function() { before(function(done) { // db = getSchema(); - User = db.define('User', { name: String }); - Follow = db.define('Follow', { date: { type: Date, + User = db.define('User', {name: String}); + Follow = db.define('Follow', {date: {type: Date, default: function() { return new Date(); - } }}); - Address = db.define('Address', { name: String }); + }}}); + Address = db.define('Address', {name: String}); User.hasMany(User, { as: 'followers', foreignKey: 'followeeId', keyThrough: 'followerId', through: Follow, @@ -1266,15 +1267,15 @@ describe('relations', function() { as: 'following', foreignKey: 'followerId', keyThrough: 'followeeId', through: Follow, }); User.belongsTo(Address); - Follow.belongsTo(User, { as: 'follower' }); - Follow.belongsTo(User, { as: 'followee' }); + Follow.belongsTo(User, {as: 'follower'}); + Follow.belongsTo(User, {as: 'followee'}); db.automigrate(['User', 'Follow'], done); }); it('should set foreignKeys of through model correctly in first relation', function(done) { - var follower = new User({ id: 1 }); - var followee = new User({ id: 2 }); + var follower = new User({id: 1}); + var followee = new User({id: 2}); followee.followers.add(follower, function(err, throughInst) { should.not.exist(err); should.exist(throughInst); @@ -1286,8 +1287,8 @@ describe('relations', function() { it('should set foreignKeys of through model correctly in second relation', function(done) { - var follower = new User({ id: 3 }); - var followee = new User({ id: 4 }); + var follower = new User({id: 3}); + var followee = new User({id: 4}); follower.following.add(followee, function(err, throughInst) { should.not.exist(err); should.exist(throughInst); @@ -1303,12 +1304,12 @@ describe('relations', function() { before(function(done) { // db = getSchema(); - User = db.define('User', { name: String }); - Follow = db.define('Follow', { date: { type: Date, + User = db.define('User', {name: String}); + Follow = db.define('Follow', {date: {type: Date, default: function() { return new Date(); - } }}); - Address = db.define('Address', { name: String }); + }}}); + Address = db.define('Address', {name: String}); User.hasMany(User, { as: 'followers', foreignKey: 'followeeId', keyThrough: 'followerId', through: Follow, @@ -1317,14 +1318,14 @@ describe('relations', function() { as: 'following', foreignKey: 'followerId', keyThrough: 'followeeId', through: Follow, }); User.belongsTo(Address); - Follow.belongsTo(User, { as: 'follower' }); - Follow.belongsTo(User, { as: 'followee' }); + Follow.belongsTo(User, {as: 'follower'}); + Follow.belongsTo(User, {as: 'followee'}); db.automigrate(['User', 'Follow', 'Address'], done); }); it('should set the keyThrough and the foreignKey', function(done) { - var user = new User({ id: 1 }); - var user2 = new User({ id: 2 }); + var user = new User({id: 1}); + var user2 = new User({id: 2}); user.following.add(user2, function(err, f) { should.not.exist(err); should.exist(f); @@ -1335,7 +1336,7 @@ describe('relations', function() { }); it('can determine the collect via keyThrough for each side', function() { - var user = new User({ id: 1 }); + var user = new User({id: 1}); var scope1 = user.followers._scope; scope1.should.have.property('collect', 'follower'); scope1.should.have.property('include', 'follower'); @@ -1347,12 +1348,12 @@ describe('relations', function() { describe('hasMany with properties', function() { it('can be declared with properties', function(done) { - Book.hasMany(Chapter, { properties: { type: 'bookType' }}); + Book.hasMany(Chapter, {properties: {type: 'bookType'}}); db.automigrate(['Book', 'Chapter'], done); }); it('should create record on scope', function(done) { - Book.create({ type: 'fiction' }, function(err, book) { + Book.create({type: 'fiction'}, function(err, book) { book.chapters.create(function(err, c) { should.not.exist(err); should.exist(c); @@ -1364,7 +1365,7 @@ describe('relations', function() { }); it('should create record on scope with promises', function(done) { - Book.create({ type: 'fiction' }) + Book.create({type: 'fiction'}) .then(function(book) { return book.chapters.create() .then(function(c) { @@ -1380,17 +1381,17 @@ describe('relations', function() { describe('hasMany with scope and properties', function() { it('can be declared with properties', function(done) { // db = getSchema(); - Category = db.define('Category', { name: String, jobType: String }); - Job = db.define('Job', { name: String, type: String }); + Category = db.define('Category', {name: String, jobType: String}); + Job = db.define('Job', {name: String, type: String}); Category.hasMany(Job, { properties: function(inst, target) { if (!inst.jobType) return; // skip - return { type: inst.jobType }; + return {type: inst.jobType}; }, scope: function(inst, filter) { var m = this.properties(inst); // re-use properties - if (m) return { where: m }; + if (m) return {where: m}; }, }); db.automigrate(['Category', 'Job'], done); @@ -1399,11 +1400,11 @@ describe('relations', function() { it('should create record on scope', function(done) { Category.create(function(err, c) { should.not.exists(err); - c.jobs.create({ type: 'book' }, function(err, p) { + c.jobs.create({type: 'book'}, function(err, p) { should.not.exists(err); p.categoryId.should.eql(c.id); p.type.should.equal('book'); - c.jobs.create({ type: 'widget' }, function(err, p) { + c.jobs.create({type: 'widget'}, function(err, p) { should.not.exists(err); p.categoryId.should.eql(c.id); p.type.should.equal('widget'); @@ -1416,11 +1417,11 @@ describe('relations', function() { it('should create record on scope with promises', function(done) { Category.create() .then(function(c) { - return c.jobs.create({ type: 'book' }) + return c.jobs.create({type: 'book'}) .then(function(p) { p.categoryId.should.eql(c.id); p.type.should.equal('book'); - return c.jobs.create({ type: 'widget' }) + return c.jobs.create({type: 'widget'}) .then(function(p) { p.categoryId.should.eql(c.id); p.type.should.equal('widget'); @@ -1456,7 +1457,7 @@ describe('relations', function() { it('should find record on scope - filtered', function(done) { Category.findOne(function(err, c) { should.not.exists(err); - c.jobs({ where: { type: 'book' }}, function(err, jobs) { + c.jobs({where: {type: 'book'}}, function(err, jobs) { should.not.exists(err); jobs.should.have.length(1); jobs[0].type.should.equal('book'); @@ -1468,7 +1469,7 @@ describe('relations', function() { it('should find record on scope with promises - filtered', function(done) { Category.findOne() .then(function(c) { - return c.jobs.getAsync({ where: { type: 'book' }}); + return c.jobs.getAsync({where: {type: 'book'}}); }) .then(function(jobs) { jobs.should.have.length(1); @@ -1574,24 +1575,24 @@ describe('relations', function() { describe('polymorphic hasOne', function() { before(function(done) { // db = getSchema(); - Picture = db.define('Picture', { name: String }); - Author = db.define('Author', { name: String }); - Reader = db.define('Reader', { name: String }); + Picture = db.define('Picture', {name: String}); + Author = db.define('Author', {name: String}); + Reader = db.define('Reader', {name: String}); db.automigrate(['Picture', 'Author', 'Reader'], done); }); it('can be declared', function(done) { - Author.hasOne(Picture, { as: 'avatar', polymorphic: 'imageable' }); - Reader.hasOne(Picture, { as: 'mugshot', polymorphic: 'imageable' }); - Picture.belongsTo('imageable', { polymorphic: true }); + Author.hasOne(Picture, {as: 'avatar', polymorphic: 'imageable'}); + Reader.hasOne(Picture, {as: 'mugshot', polymorphic: 'imageable'}); + Picture.belongsTo('imageable', {polymorphic: true}); db.automigrate(['Picture', 'Author', 'Reader'], done); }); it('should create polymorphic relation - author', function(done) { - Author.create({ name: 'Author 1' }, function(err, author) { + Author.create({name: 'Author 1'}, function(err, author) { should.not.exists(err); - author.avatar.create({ name: 'Avatar' }, function(err, p) { + author.avatar.create({name: 'Avatar'}, function(err, p) { should.not.exist(err); should.exist(p); p.imageableId.should.eql(author.id); @@ -1602,9 +1603,9 @@ describe('relations', function() { }); it('should create polymorphic relation with promises - author', function(done) { - Author.create({ name: 'Author 1' }) + Author.create({name: 'Author 1'}) .then(function(author) { - return author.avatar.create({ name: 'Avatar' }) + return author.avatar.create({name: 'Avatar'}) .then(function(p) { should.exist(p); p.imageableId.should.eql(author.id); @@ -1615,9 +1616,9 @@ describe('relations', function() { }); it('should create polymorphic relation - reader', function(done) { - Reader.create({ name: 'Reader 1' }, function(err, reader) { + Reader.create({name: 'Reader 1'}, function(err, reader) { should.not.exists(err); - reader.mugshot.create({ name: 'Mugshot' }, function(err, p) { + reader.mugshot.create({name: 'Mugshot'}, function(err, p) { should.not.exist(err); should.exist(p); p.imageableId.should.eql(reader.id); @@ -1658,7 +1659,7 @@ describe('relations', function() { }); it('should include polymorphic relation - author', function(done) { - Author.findOne({ include: 'avatar' }, function(err, author) { + Author.findOne({include: 'avatar'}, function(err, author) { should.not.exists(err); var avatar = author.avatar(); should.exist(avatar); @@ -1681,7 +1682,7 @@ describe('relations', function() { }); it('should find inverse polymorphic relation - author', function(done) { - Picture.findOne({ where: { name: 'Avatar' }}, function(err, p) { + Picture.findOne({where: {name: 'Avatar'}}, function(err, p) { should.not.exists(err); p.imageable(function(err, imageable) { should.not.exist(err); @@ -1693,7 +1694,7 @@ describe('relations', function() { }); it('should include inverse polymorphic relation - author', function(done) { - Picture.findOne({ where: { name: 'Avatar' }, include: 'imageable' }, + Picture.findOne({where: {name: 'Avatar'}, include: 'imageable'}, function(err, p) { should.not.exists(err); var imageable = p.imageable(); @@ -1705,7 +1706,7 @@ describe('relations', function() { }); it('should find inverse polymorphic relation - reader', function(done) { - Picture.findOne({ where: { name: 'Mugshot' }}, function(err, p) { + Picture.findOne({where: {name: 'Mugshot'}}, function(err, p) { should.not.exists(err); p.imageable(function(err, imageable) { should.not.exist(err); @@ -1721,13 +1722,13 @@ describe('relations', function() { describe('polymorphic hasOne with non standard ids', function() { before(function(done) { // db = getSchema(); - Picture = db.define('Picture', { name: String }); + Picture = db.define('Picture', {name: String}); Author = db.define('Author', { - username: { type: String, id: true, generated: true }, + username: {type: String, id: true, generated: true}, name: String, }); Reader = db.define('Reader', { - username: { type: String, id: true, generated: true }, + username: {type: String, id: true, generated: true}, name: String, }); @@ -1761,9 +1762,9 @@ describe('relations', function() { }); it('should create polymorphic relation - author', function(done) { - Author.create({ name: 'Author 1' }, function(err, author) { + Author.create({name: 'Author 1'}, function(err, author) { should.not.exists(err); - author.avatar.create({ name: 'Avatar' }, function(err, p) { + author.avatar.create({name: 'Avatar'}, function(err, p) { should.not.exist(err); should.exist(p); p.oid.toString().should.equal(author.username.toString()); @@ -1774,9 +1775,9 @@ describe('relations', function() { }); it('should create polymorphic relation with promises - author', function(done) { - Author.create({ name: 'Author 1' }) + Author.create({name: 'Author 1'}) .then(function(author) { - return author.avatar.create({ name: 'Avatar' }) + return author.avatar.create({name: 'Avatar'}) .then(function(p) { should.exist(p); p.oid.toString().should.equal(author.username.toString()); @@ -1787,9 +1788,9 @@ describe('relations', function() { }); it('should create polymorphic relation - reader', function(done) { - Reader.create({ name: 'Reader 1' }, function(err, reader) { + Reader.create({name: 'Reader 1'}, function(err, reader) { should.not.exists(err); - reader.mugshot.create({ name: 'Mugshot' }, function(err, p) { + reader.mugshot.create({name: 'Mugshot'}, function(err, p) { should.not.exist(err); should.exist(p); p.oid.toString().should.equal(reader.username.toString()); @@ -1830,7 +1831,7 @@ describe('relations', function() { }); it('should find inverse polymorphic relation - author', function(done) { - Picture.findOne({ where: { name: 'Avatar' }}, function(err, p) { + Picture.findOne({where: {name: 'Avatar'}}, function(err, p) { should.not.exists(err); p.owner(function(err, owner) { should.not.exist(err); @@ -1842,7 +1843,7 @@ describe('relations', function() { }); it('should find inverse polymorphic relation - reader', function(done) { - Picture.findOne({ where: { name: 'Mugshot' }}, function(err, p) { + Picture.findOne({where: {name: 'Mugshot'}}, function(err, p) { should.not.exists(err); p.owner(function(err, owner) { should.not.exist(err); @@ -1854,7 +1855,7 @@ describe('relations', function() { }); it('should include polymorphic relation - reader', function(done) { - Reader.findOne({ include: 'mugshot' }, + Reader.findOne({include: 'mugshot'}, function(err, reader) { should.not.exists(err); var mugshot = reader.mugshot(); @@ -1865,7 +1866,7 @@ describe('relations', function() { }); it('should include inverse polymorphic relation - reader', function(done) { - Picture.findOne({ where: { name: 'Mugshot' }, include: 'owner' }, + Picture.findOne({where: {name: 'Mugshot'}, include: 'owner'}, function(err, p) { should.not.exists(err); var owner = p.owner(); @@ -1880,20 +1881,20 @@ describe('relations', function() { describe('polymorphic hasMany', function() { before(function(done) { // db = getSchema(); - Picture = db.define('Picture', { name: String }); - Author = db.define('Author', { name: String }); - Reader = db.define('Reader', { name: String }); + Picture = db.define('Picture', {name: String}); + Author = db.define('Author', {name: String}); + Reader = db.define('Reader', {name: String}); db.automigrate(['Picture', 'Author', 'Reader'], done); }); it('can be declared', function(done) { - Author.hasMany(Picture, { polymorphic: 'imageable' }); - Reader.hasMany(Picture, { polymorphic: { // alt syntax + Author.hasMany(Picture, {polymorphic: 'imageable'}); + Reader.hasMany(Picture, {polymorphic: { // alt syntax as: 'imageable', foreignKey: 'imageableId', discriminator: 'imageableType', }}); - Picture.belongsTo('imageable', { polymorphic: true }); + Picture.belongsTo('imageable', {polymorphic: true}); Author.relations['pictures'].toJSON().should.eql({ name: 'pictures', @@ -1929,9 +1930,9 @@ describe('relations', function() { }); it('should create polymorphic relation - author', function(done) { - Author.create({ name: 'Author 1' }, function(err, author) { + Author.create({name: 'Author 1'}, function(err, author) { should.not.exists(err); - author.pictures.create({ name: 'Author Pic' }, function(err, p) { + author.pictures.create({name: 'Author Pic'}, function(err, p) { should.not.exist(err); should.exist(p); p.imageableId.should.eql(author.id); @@ -1942,9 +1943,9 @@ describe('relations', function() { }); it('should create polymorphic relation - reader', function(done) { - Reader.create({ name: 'Reader 1' }, function(err, reader) { + Reader.create({name: 'Reader 1'}, function(err, reader) { should.not.exists(err); - reader.pictures.create({ name: 'Reader Pic' }, function(err, p) { + reader.pictures.create({name: 'Reader Pic'}, function(err, p) { should.not.exist(err); should.exist(p); p.imageableId.should.eql(reader.id); @@ -1983,7 +1984,7 @@ describe('relations', function() { }); it('should find the inverse of polymorphic relation - author', function(done) { - Picture.findOne({ where: { name: 'Author Pic' }}, function(err, p) { + Picture.findOne({where: {name: 'Author Pic'}}, function(err, p) { should.not.exist(err); p.imageableType.should.equal('Author'); p.imageable(function(err, imageable) { @@ -1996,7 +1997,7 @@ describe('relations', function() { }); it('should find the inverse of polymorphic relation - reader', function(done) { - Picture.findOne({ where: { name: 'Reader Pic' }}, function(err, p) { + Picture.findOne({where: {name: 'Reader Pic'}}, function(err, p) { should.not.exist(err); p.imageableType.should.equal('Reader'); p.imageable(function(err, imageable) { @@ -2009,7 +2010,7 @@ describe('relations', function() { }); it('should include the inverse of polymorphic relation', function(done) { - Picture.find({ include: 'imageable' }, function(err, pics) { + Picture.find({include: 'imageable'}, function(err, pics) { should.not.exist(err); pics.should.have.length(2); pics[0].name.should.equal('Author Pic'); @@ -2021,9 +2022,9 @@ describe('relations', function() { }); it('should assign a polymorphic relation', function(done) { - Author.create({ name: 'Author 2' }, function(err, author) { + Author.create({name: 'Author 2'}, function(err, author) { should.not.exists(err); - var p = new Picture({ name: 'Sample' }); + var p = new Picture({name: 'Sample'}); p.imageable(author); // assign p.imageableId.should.eql(author.id); p.imageableType.should.equal('Author'); @@ -2032,7 +2033,7 @@ describe('relations', function() { }); it('should find polymorphic items - author', function(done) { - Author.findOne({ where: { name: 'Author 2' }}, function(err, author) { + Author.findOne({where: {name: 'Author 2'}}, function(err, author) { should.not.exists(err); author.pictures(function(err, pics) { should.not.exist(err); @@ -2044,7 +2045,7 @@ describe('relations', function() { }); it('should find the inverse of polymorphic relation - author', function(done) { - Picture.findOne({ where: { name: 'Sample' }}, function(err, p) { + Picture.findOne({where: {name: 'Sample'}}, function(err, p) { should.not.exist(err); p.imageableType.should.equal('Author'); p.imageable(function(err, imageable) { @@ -2058,7 +2059,7 @@ describe('relations', function() { it('should include the inverse of polymorphic relation - author', function(done) { - Picture.findOne({ where: { name: 'Sample' }, include: 'imageable' }, + Picture.findOne({where: {name: 'Sample'}, include: 'imageable'}, function(err, p) { should.not.exist(err); var imageable = p.imageable(); @@ -2074,38 +2075,38 @@ describe('relations', function() { describe('polymorphic hasAndBelongsToMany through', function() { before(function(done) { // db = getSchema(); - Picture = db.define('Picture', { name: String }); - Author = db.define('Author', { name: String }); - Reader = db.define('Reader', { name: String }); + Picture = db.define('Picture', {name: String}); + Author = db.define('Author', {name: String}); + Reader = db.define('Reader', {name: String}); PictureLink = db.define('PictureLink', {}); db.automigrate(['Picture', 'Author', 'Reader', 'PictureLink'], done); }); it('can be declared', function(done) { - Author.hasAndBelongsToMany(Picture, { through: PictureLink, polymorphic: 'imageable' }); - Reader.hasAndBelongsToMany(Picture, { through: PictureLink, polymorphic: 'imageable' }); + Author.hasAndBelongsToMany(Picture, {through: PictureLink, polymorphic: 'imageable'}); + Reader.hasAndBelongsToMany(Picture, {through: PictureLink, polymorphic: 'imageable'}); // Optionally, define inverse relations: - Picture.hasMany(Author, { through: PictureLink, polymorphic: 'imageable', invert: true }); - Picture.hasMany(Reader, { through: PictureLink, polymorphic: 'imageable', invert: true }); + Picture.hasMany(Author, {through: PictureLink, polymorphic: 'imageable', invert: true}); + Picture.hasMany(Reader, {through: PictureLink, polymorphic: 'imageable', invert: true}); db.automigrate(['Picture', 'Author', 'Reader', 'PictureLink'], done); }); it('can determine the collect via modelTo name', function() { - Author.hasAndBelongsToMany(Picture, { through: PictureLink, polymorphic: 'imageable' }); - Reader.hasAndBelongsToMany(Picture, { through: PictureLink, polymorphic: 'imageable' }); + Author.hasAndBelongsToMany(Picture, {through: PictureLink, polymorphic: 'imageable'}); + Reader.hasAndBelongsToMany(Picture, {through: PictureLink, polymorphic: 'imageable'}); // Optionally, define inverse relations: - Picture.hasMany(Author, { through: PictureLink, polymorphic: 'imageable', invert: true }); - Picture.hasMany(Reader, { through: PictureLink, polymorphic: 'imageable', invert: true }); - var author = new Author({ id: 1 }); + Picture.hasMany(Author, {through: PictureLink, polymorphic: 'imageable', invert: true}); + Picture.hasMany(Reader, {through: PictureLink, polymorphic: 'imageable', invert: true}); + var author = new Author({id: 1}); var scope1 = author.pictures._scope; scope1.should.have.property('collect', 'picture'); scope1.should.have.property('include', 'picture'); - var reader = new Reader({ id: 1 }); + var reader = new Reader({id: 1}); var scope2 = reader.pictures._scope; scope2.should.have.property('collect', 'picture'); scope2.should.have.property('include', 'picture'); - var picture = new Picture({ id: 1 }); + var picture = new Picture({id: 1}); var scope3 = picture.authors._scope; scope3.should.have.property('collect', 'imageable'); scope3.should.have.property('include', 'imageable'); @@ -2116,13 +2117,13 @@ describe('relations', function() { var author, reader, pictures = []; it('should create polymorphic relation - author', function(done) { - Author.create({ name: 'Author 1' }, function(err, a) { + Author.create({name: 'Author 1'}, function(err, a) { should.not.exist(err); author = a; - author.pictures.create({ name: 'Author Pic 1' }, function(err, p) { + author.pictures.create({name: 'Author Pic 1'}, function(err, p) { should.not.exist(err); pictures.push(p); - author.pictures.create({ name: 'Author Pic 2' }, function(err, p) { + author.pictures.create({name: 'Author Pic 2'}, function(err, p) { should.not.exist(err); pictures.push(p); done(); @@ -2132,10 +2133,10 @@ describe('relations', function() { }); it('should create polymorphic relation - reader', function(done) { - Reader.create({ name: 'Reader 1' }, function(err, r) { + Reader.create({name: 'Reader 1'}, function(err, r) { should.not.exist(err); reader = r; - reader.pictures.create({ name: 'Reader Pic 1' }, function(err, p) { + reader.pictures.create({name: 'Reader Pic 1'}, function(err, p) { should.not.exist(err); pictures.push(p); done(); @@ -2185,7 +2186,7 @@ describe('relations', function() { }); it('should include polymorphic items', function(done) { - Author.find({ include: 'pictures' }, function(err, authors) { + Author.find({include: 'pictures'}, function(err, authors) { authors.should.have.length(1); authors[0].pictures(function(err, pics) { pics.should.have.length(2); @@ -2199,7 +2200,7 @@ describe('relations', function() { var anotherPicture; it('should add to a polymorphic relation - author', function(done) { Author.findById(author.id, function(err, author) { - Picture.create({ name: 'Example' }, function(err, p) { + Picture.create({name: 'Example'}, function(err, p) { should.not.exist(err); pictures.push(p); anotherPicture = p; @@ -2215,7 +2216,7 @@ describe('relations', function() { }); it('should create polymorphic through model', function(done) { - PictureLink.findOne({ where: { pictureId: anotherPicture.id, imageableType: 'Author' }}, + PictureLink.findOne({where: {pictureId: anotherPicture.id, imageableType: 'Author'}}, function(err, link) { should.not.exist(err); link.pictureId.should.eql(anotherPicture.id); @@ -2227,7 +2228,7 @@ describe('relations', function() { var anotherAuthor, anotherReader; it('should add to a polymorphic relation - author', function(done) { - Author.create({ name: 'Author 2' }, function(err, author) { + Author.create({name: 'Author 2'}, function(err, author) { should.not.exist(err); anotherAuthor = author; author.pictures.add(anotherPicture.id, function(err, p) { @@ -2238,7 +2239,7 @@ describe('relations', function() { }); it('should add to a polymorphic relation - author', function(done) { - Reader.create({ name: 'Reader 2' }, function(err, reader) { + Reader.create({name: 'Reader 2'}, function(err, reader) { should.not.exist(err); anotherReader = reader; reader.pictures.add(anotherPicture.id, function(err, p) { @@ -2321,7 +2322,7 @@ describe('relations', function() { it('should create polymorphic item through relation scope', function(done) { Picture.findById(anotherPicture.id, function(err, p) { - p.authors.create({ name: 'Author 3' }, function(err, a) { + p.authors.create({name: 'Author 3'}, function(err, a) { should.not.exist(err); author = a; author.name.should.equal('Author 3'); @@ -2331,7 +2332,7 @@ describe('relations', function() { }); it('should create polymorphic through model - new author', function(done) { - PictureLink.findOne({ where: { + PictureLink.findOne({where: { pictureId: anotherPicture.id, imageableId: author.id, imageableType: 'Author', }}, function(err, link) { should.not.exist(err); @@ -2361,8 +2362,8 @@ describe('relations', function() { var listId, itemId; it('can be declared in different ways', function() { - List = db.define('List', { name: String }); - Item = db.define('Item', { name: String }); + List = db.define('List', {name: String}); + Item = db.define('Item', {name: String}); Fear = db.define('Fear'); Mind = db.define('Mind'); @@ -2373,7 +2374,7 @@ describe('relations', function() { // syntax 2 (new) Fear.belongsTo('mind', { - methods: { check: function() { return true; } }, + methods: {check: function() { return true; }}, }); Object.keys((new Fear).toObject()).should.containEql('mindId'); @@ -2397,13 +2398,13 @@ describe('relations', function() { }); it('can be used to query data', function(done) { - List.hasMany('todos', { model: Item }); + List.hasMany('todos', {model: Item}); db.automigrate(['List', 'Item', 'Fear', 'Mind'], function() { - List.create({ name: 'List 1' }, function(e, list) { + List.create({name: 'List 1'}, function(e, list) { listId = list.id; should.not.exist(e); should.exist(list); - list.todos.create({ name: 'Item 1' }, function(err, todo) { + list.todos.create({name: 'Item 1'}, function(err, todo) { itemId = todo.id; todo.list(function(e, l) { should.not.exist(e); @@ -2419,13 +2420,13 @@ describe('relations', function() { }); it('can be used to query data with getAsync with callback', function(done) { - List.hasMany('todos', { model: Item }); + List.hasMany('todos', {model: Item}); db.automigrate(['List', 'Item', 'Fear', 'Find'], function() { - List.create({ name: 'List 1' }, function(e, list) { + List.create({name: 'List 1'}, function(e, list) { listId = list.id; should.not.exist(e); should.exist(list); - list.todos.create({ name: 'Item 1' }, function(err, todo) { + list.todos.create({name: 'Item 1'}, function(err, todo) { itemId = todo.id; todo.list.getAsync(function(e, l) { should.not.exist(e); @@ -2441,13 +2442,13 @@ describe('relations', function() { }); it('can be used to query data with promises', function(done) { - List.hasMany('todos', { model: Item }); + List.hasMany('todos', {model: Item}); db.automigrate(['List', 'Item', 'Fear', 'Find'], function() { - List.create({ name: 'List 1' }) + List.create({name: 'List 1'}) .then(function(list) { listId = list.id; should.exist(list); - return list.todos.create({ name: 'Item 1' }); + return list.todos.create({name: 'Item 1'}); }) .then(function(todo) { itemId = todo.id; @@ -2468,7 +2469,7 @@ describe('relations', function() { List.create(function(e, list) { should.not.exist(e); should.exist(list); - Item.create({ list: list }, function(err, item) { + Item.create({list: list}, function(err, item) { should.not.exist(err); should.exist(item); should.exist(item.listId); @@ -2481,7 +2482,7 @@ describe('relations', function() { it('should update related item on scope', function(done) { Item.findById(itemId, function(e, todo) { - todo.list.update({ name: 'List A' }, function(err, list) { + todo.list.update({name: 'List A'}, function(err, list) { should.not.exist(err); should.exist(list); list.name.should.equal('List A'); @@ -2569,19 +2570,19 @@ describe('relations', function() { var Person, Passport; it('can be declared with scope and properties', function(done) { - Person = db.define('Person', { name: String, age: Number, passportNotes: String }); - Passport = db.define('Passport', { name: String, notes: String }); + Person = db.define('Person', {name: String, age: Number, passportNotes: String}); + Passport = db.define('Passport', {name: String, notes: String}); Passport.belongsTo(Person, { - properties: { notes: 'passportNotes' }, - scope: { fields: { id: true, name: true }}, + properties: {notes: 'passportNotes'}, + scope: {fields: {id: true, name: true}}, }); db.automigrate(['Person', 'Passport'], done); }); var personCreated; it('should create record on scope', function(done) { - var p = new Passport({ name: 'Passport', notes: 'Some notes...' }); - p.person.create({ name: 'Fred', age: 36 }, function(err, person) { + var p = new Passport({name: 'Passport', notes: 'Some notes...'}); + p.person.create({name: 'Fred', age: 36}, function(err, person) { personCreated = person; p.personId.should.equal(person.id); person.name.should.equal('Fred'); @@ -2606,8 +2607,8 @@ describe('relations', function() { }); it('should create record on scope with promises', function(done) { - var p = new Passport({ name: 'Passport', notes: 'Some notes...' }); - p.person.create({ name: 'Fred', age: 36 }) + var p = new Passport({name: 'Passport', notes: 'Some notes...'}); + p.person.create({name: 'Fred', age: 36}) .then(function(person) { p.personId.should.equal(person.id); person.name.should.equal('Fred'); @@ -2644,18 +2645,18 @@ describe('relations', function() { var Person, Passport; it('can be declared with embed and properties', function(done) { - Person = db.define('Person', { name: String, age: Number }); - Passport = db.define('Passport', { name: String, notes: String }); + Person = db.define('Person', {name: String, age: Number}); + Passport = db.define('Passport', {name: String, notes: String}); Passport.belongsTo(Person, { properties: ['name'], - options: { embedsProperties: true, invertProperties: true }, + options: {embedsProperties: true, invertProperties: true}, }); db.automigrate(['Person', 'Passport'], done); }); it('should create record with embedded data', function(done) { - Person.create({ name: 'Fred', age: 36 }, function(err, person) { - var p = new Passport({ name: 'Passport', notes: 'Some notes...' }); + Person.create({name: 'Fred', age: 36}, function(err, person) { + var p = new Passport({name: 'Passport', notes: 'Some notes...'}); p.person(person); p.personId.should.equal(person.id); var data = p.toObject(true); @@ -2695,14 +2696,14 @@ describe('relations', function() { before(function() { // db = getSchema(); - Supplier = db.define('Supplier', { name: String }); - Account = db.define('Account', { accountNo: String, supplierName: String }); + Supplier = db.define('Supplier', {name: String}); + Account = db.define('Account', {accountNo: String, supplierName: String}); }); it('can be declared using hasOne method', function() { Supplier.hasOne(Account, { - properties: { name: 'supplierName' }, - methods: { check: function() { return true; } }, + properties: {name: 'supplierName'}, + methods: {check: function() { return true; }}, }); Object.keys((new Account()).toObject()).should.containEql('supplierId'); (new Supplier()).account.should.be.an.instanceOf(Function); @@ -2725,11 +2726,11 @@ describe('relations', function() { it('can be used to query data', function(done) { db.automigrate(['Supplier', 'Account'], function() { - Supplier.create({ name: 'Supplier 1' }, function(e, supplier) { + Supplier.create({name: 'Supplier 1'}, function(e, supplier) { supplierId = supplier.id; should.not.exist(e); should.exist(supplier); - supplier.account.create({ accountNo: 'a01' }, function(err, account) { + supplier.account.create({accountNo: 'a01'}, function(err, account) { supplier.account(function(e, act) { accountId = act.id; should.not.exist(e); @@ -2746,11 +2747,11 @@ describe('relations', function() { it('can be used to query data with getAsync with callback', function(done) { db.automigrate(['Supplier', 'Account'], function() { - Supplier.create({ name: 'Supplier 1' }, function(e, supplier) { + Supplier.create({name: 'Supplier 1'}, function(e, supplier) { supplierId = supplier.id; should.not.exist(e); should.exist(supplier); - supplier.account.create({ accountNo: 'a01' }, function(err, account) { + supplier.account.create({accountNo: 'a01'}, function(err, account) { supplier.account.getAsync(function(e, act) { accountId = act.id; should.not.exist(e); @@ -2767,11 +2768,11 @@ describe('relations', function() { it('can be used to query data with promises', function(done) { db.automigrate(['Supplier', 'Account'], function() { - Supplier.create({ name: 'Supplier 1' }) + Supplier.create({name: 'Supplier 1'}) .then(function(supplier) { supplierId = supplier.id; should.exist(supplier); - return supplier.account.create({ accountNo: 'a01' }) + return supplier.account.create({accountNo: 'a01'}) .then(function(account) { return supplier.account.getAsync(); }) @@ -2796,7 +2797,7 @@ describe('relations', function() { Supplier.findById(supplierId, function(e, supplier) { should.not.exist(e); should.exist(supplier); - supplier.account.update({ supplierName: 'Supplier A' }, function(err, act) { + supplier.account.update({supplierName: 'Supplier A'}, function(err, act) { should.not.exist(e); act.supplierName.should.equal('Supplier A'); done(); @@ -2808,7 +2809,7 @@ describe('relations', function() { Supplier.findById(supplierId) .then(function(supplier) { should.exist(supplier); - return supplier.account.update({ supplierName: 'Supplier B' }); + return supplier.account.update({supplierName: 'Supplier B'}); }) .then(function(act) { act.supplierName.should.equal('Supplier B'); @@ -2818,13 +2819,13 @@ describe('relations', function() { }); it('should ignore the foreign key in the update', function(done) { - Supplier.create({ name: 'Supplier 2' }, function(e, supplier) { + Supplier.create({name: 'Supplier 2'}, function(e, supplier) { var sid = supplier.id; Supplier.findById(supplierId, function(e, supplier) { should.not.exist(e); should.exist(supplier); - supplier.account.update({ supplierName: 'Supplier A', - supplierId: sid }, + supplier.account.update({supplierName: 'Supplier A', + supplierId: sid}, function(err, act) { should.not.exist(e); act.supplierName.should.equal('Supplier A'); @@ -2877,7 +2878,7 @@ describe('relations', function() { Supplier.findById(supplierId) .then(function(supplier) { should.exist(supplier); - return supplier.account.create({ accountNo: 'a01' }) + return supplier.account.create({accountNo: 'a01'}) .then(function(account) { return supplier.account.destroy(); }) @@ -2930,18 +2931,18 @@ describe('relations', function() { before(function() { // db = getSchema(); - Supplier = db.define('Supplier', { name: String }); - Account = db.define('Account', { accountNo: String, supplierName: String, block: Boolean }); - Supplier.hasOne(Account, { scope: { where: { block: false }}, properties: { name: 'supplierName' }}); + Supplier = db.define('Supplier', {name: String}); + Account = db.define('Account', {accountNo: String, supplierName: String, block: Boolean}); + Supplier.hasOne(Account, {scope: {where: {block: false}}, properties: {name: 'supplierName'}}); }); it('can be used to query data', function(done) { db.automigrate(['Supplier', 'Account'], function() { - Supplier.create({ name: 'Supplier 1' }, function(e, supplier) { + Supplier.create({name: 'Supplier 1'}, function(e, supplier) { supplierId = supplier.id; should.not.exist(e); should.exist(supplier); - supplier.account.create({ accountNo: 'a01', block: false }, function(err, account) { + supplier.account.create({accountNo: 'a01', block: false}, function(err, account) { supplier.account(function(e, act) { accountId = act.id; should.not.exist(e); @@ -2959,7 +2960,7 @@ describe('relations', function() { }); it('should include record that matches scope', function(done) { - Supplier.findById(supplierId, { include: 'account' }, function(err, supplier) { + Supplier.findById(supplierId, {include: 'account'}, function(err, supplier) { should.exists(supplier.toJSON().account); supplier.account(function(err, account) { should.exists(account); @@ -2969,7 +2970,7 @@ describe('relations', function() { }); it('should not find record that does not match scope', function(done) { - Account.updateAll({ block: true }, function(err) { + Account.updateAll({block: true}, function(err) { Supplier.findById(supplierId, function(err, supplier) { supplier.account(function(err, account) { should.not.exists(account); @@ -2980,8 +2981,8 @@ describe('relations', function() { }); it('should not include record that does not match scope', function(done) { - Account.updateAll({ block: true }, function(err) { - Supplier.findById(supplierId, { include: 'account' }, function(err, supplier) { + Account.updateAll({block: true}, function(err) { + Supplier.findById(supplierId, {include: 'account'}, function(err, supplier) { should.not.exists(supplier.toJSON().account); supplier.account(function(err, account) { should.not.exists(account); @@ -2993,11 +2994,11 @@ describe('relations', function() { it('can be used to query data with promises', function(done) { db.automigrate(['Supplier', 'Account'], function() { - Supplier.create({ name: 'Supplier 1' }) + Supplier.create({name: 'Supplier 1'}) .then(function(supplier) { supplierId = supplier.id; should.exist(supplier); - return supplier.account.create({ accountNo: 'a01', block: false }) + return supplier.account.create({accountNo: 'a01', block: false}) .then(function(account) { return supplier.account.getAsync(); }) @@ -3017,7 +3018,7 @@ describe('relations', function() { }); it('should find record that match scope with promises', function(done) { - Account.updateAll({ block: true }) + Account.updateAll({block: true}) .then(function() { return Supplier.findById(supplierId); }) @@ -3059,7 +3060,7 @@ describe('relations', function() { it('can be declared with non standard foreignKey', function() { Supplier.hasOne(Account, { - properties: { name: 'supplierName' }, + properties: {name: 'supplierName'}, foreignKey: 'sid', }); Object.keys((new Account()).toObject()).should.containEql('sid'); @@ -3068,11 +3069,11 @@ describe('relations', function() { it('can be used to query data', function(done) { db.automigrate(['Supplier', 'Account'], function() { - Supplier.create({ name: 'Supplier 1' }, function(e, supplier) { + Supplier.create({name: 'Supplier 1'}, function(e, supplier) { supplierId = supplier.sid; should.not.exist(e); should.exist(supplier); - supplier.account.create({ accid: 'a01' }, function(err, account) { + supplier.account.create({accid: 'a01'}, function(err, account) { supplier.account(function(e, act) { accountId = act.accid; should.not.exist(e); @@ -3131,7 +3132,7 @@ describe('relations', function() { companyId: String, }); Boss = db.define('Boss', { - id: { type: String, id: true, generated: false }, + id: {type: String, id: true, generated: false}, boardMembersNumber: Number, companyId: String, }); @@ -3139,7 +3140,7 @@ describe('relations', function() { it('relation can be declared with primaryKey', function() { CompanyBoard.hasOne(Boss, { - properties: { membersNumber: 'boardMembersNumber' }, + properties: {membersNumber: 'boardMembersNumber'}, primaryKey: 'companyId', foreignKey: 'companyId', }); @@ -3149,11 +3150,11 @@ describe('relations', function() { it('can be used to query data', function(done) { db.automigrate(['CompanyBoard', 'Boss'], function() { - CompanyBoard.create({ membersNumber: 7, companyId: 'Company1' }, function(e, companyBoard) { + CompanyBoard.create({membersNumber: 7, companyId: 'Company1'}, function(e, companyBoard) { companyBoardId = companyBoard.id; should.not.exist(e); should.exist(companyBoard); - companyBoard.boss.create({ id: 'a01' }, function(err, account) { + companyBoard.boss.create({id: 'a01'}, function(err, account) { companyBoard.boss(function(e, boss) { bossId = boss.id; should.not.exist(e); @@ -3199,8 +3200,8 @@ describe('relations', function() { before(function() { db = getSchema(); - Employee = db.define('Employee', { name: String, companyId: String }); - Boss = db.define('Boss', { address: String, companyId: String }); + Employee = db.define('Employee', {name: String, companyId: String}); + Boss = db.define('Boss', {address: String, companyId: String}); }); it('relation can be declared with primaryKey', function() { @@ -3213,11 +3214,11 @@ describe('relations', function() { it('can be used to query employees for boss', function() { return db.automigrate(['Employee', 'Boss']).then(function() { - return Boss.create({ address: 'testAddress', companyId: COMPANY_ID }) + return Boss.create({address: 'testAddress', companyId: COMPANY_ID}) .then(function(boss) { should.exist(boss); should.exist(boss.employees); - return boss.employees.create([{ name: 'a01' }, { name: 'a02' }]) + return boss.employees.create([{name: 'a01'}, {name: 'a02'}]) .then(function(employees) { should.exists(employees); return boss.employees(); @@ -3235,9 +3236,9 @@ describe('relations', function() { it('can be used to query employees for boss2', function() { return db.automigrate(['Employee', 'Boss']).then(function() { - return Boss.create({ address: 'testAddress', companyId: COMPANY_ID }) + return Boss.create({address: 'testAddress', companyId: COMPANY_ID}) .then(function(boss) { - return Employee.create({ name: 'a01', companyId: COMPANY_ID }) + return Employee.create({name: 'a01', companyId: COMPANY_ID}) .then(function(employee) { should.exist(employee); return boss.employees.getAsync(); @@ -3257,8 +3258,8 @@ describe('relations', function() { before(function() { db = getSchema(); - Employee = db.define('Employee', { name: String, companyId: String }); - Boss = db.define('Boss', { address: String, companyId: String }); + Employee = db.define('Employee', {name: String, companyId: String}); + Boss = db.define('Boss', {address: String, companyId: String}); }); it('relation can be declared with primaryKey', function() { @@ -3271,10 +3272,10 @@ describe('relations', function() { it('can be used to query data', function() { return db.automigrate(['Employee', 'Boss']).then(function() { - return Boss.create({ address: 'testAddress', companyId: COMPANY_ID }) + return Boss.create({address: 'testAddress', companyId: COMPANY_ID}) .then(function(boss) { bossId = boss.id; - return Employee.create({ name: 'a', companyId: COMPANY_ID }); + return Employee.create({name: 'a', companyId: COMPANY_ID}); }) .then(function(employee) { should.exists(employee); @@ -3291,8 +3292,8 @@ describe('relations', function() { describe('hasAndBelongsToMany', function() { var Article, TagName, ArticleTag; it('can be declared', function(done) { - Article = db.define('Article', { title: String }); - TagName = db.define('TagName', { name: String, flag: String }); + Article = db.define('Article', {title: String}); + TagName = db.define('TagName', {name: String, flag: String}); Article.hasAndBelongsToMany('tagNames'); ArticleTag = db.models.ArticleTagName; db.automigrate(['Article', 'TagName', 'ArticleTagName'], done); @@ -3300,7 +3301,7 @@ describe('relations', function() { it('should allow to create instances on scope', function(done) { Article.create(function(e, article) { - article.tagNames.create({ name: 'popular' }, function(e, t) { + article.tagNames.create({name: 'popular'}, function(e, t) { t.should.be.an.instanceOf(TagName); ArticleTag.findOne(function(e, at) { should.exist(at); @@ -3327,7 +3328,7 @@ describe('relations', function() { it('should allow to add connection with instance', function(done) { Article.findOne(function(e, article) { - TagName.create({ name: 'awesome' }, function(e, tag) { + TagName.create({name: 'awesome'}, function(e, tag) { article.tagNames.add(tag, function(e, at) { should.not.exist(e); should.exist(at); @@ -3360,7 +3361,7 @@ describe('relations', function() { db.automigrate(['Article', 'TagName', 'ArticleTagName'], function() { Article.create() .then(function(article) { - return article.tagNames.create({ name: 'popular' }) + return article.tagNames.create({name: 'popular'}) .then(function(t) { t.should.be.an.instanceOf(TagName); return ArticleTag.findOne() @@ -3390,7 +3391,7 @@ describe('relations', function() { it('should allow to add connection with instance with promises', function(done) { Article.findOne() .then(function(article) { - return TagName.create({ name: 'awesome' }) + return TagName.create({name: 'awesome'}) .then(function(tag) { return article.tagNames.add(tag) .then(function(at) { @@ -3430,13 +3431,13 @@ describe('relations', function() { }); it('should apply inclusion fields to the target model', function(done) { - Article.create({ title: 'a1' }, function(e, article) { + Article.create({title: 'a1'}, function(e, article) { should.not.exist(e); - article.tagNames.create({ name: 't1', flag: '1' }, function(e, t) { + article.tagNames.create({name: 't1', flag: '1'}, function(e, t) { should.not.exist(e); Article.find({ - where: { id: article.id }, - include: { relation: 'tagNames', scope: { fields: ['name'] }}}, + where: {id: article.id}, + include: {relation: 'tagNames', scope: {fields: ['name']}}}, function(e, articles) { should.not.exist(e); articles.should.have.property('length', 1); @@ -3455,14 +3456,14 @@ describe('relations', function() { }); it('should apply inclusion where to the target model', function(done) { - Article.create({ title: 'a2' }, function(e, article) { + Article.create({title: 'a2'}, function(e, article) { should.not.exist(e); - article.tagNames.create({ name: 't2', flag: '2' }, function(e, t2) { + article.tagNames.create({name: 't2', flag: '2'}, function(e, t2) { should.not.exist(e); - article.tagNames.create({ name: 't3', flag: '3' }, function(e, t3) { + article.tagNames.create({name: 't3', flag: '3'}, function(e, t3) { Article.find({ - where: { id: article.id }, - include: { relation: 'tagNames', scope: { where: { flag: '2' }}}}, + where: {id: article.id}, + include: {relation: 'tagNames', scope: {where: {flag: '2'}}}}, function(e, articles) { should.not.exist(e); articles.should.have.property('length', 1); @@ -3491,19 +3492,19 @@ describe('relations', function() { before(function() { tmp = getTransientDataSource(); // db = getSchema(); - Person = db.define('Person', { name: String }); + Person = db.define('Person', {name: String}); Passport = tmp.define('Passport', - { name: { type: 'string', required: true }}, - { idInjection: false } + {name: {type: 'string', required: true}}, + {idInjection: false} ); - Address = tmp.define('Address', { street: String }, { idInjection: false }); - Other = db.define('Other', { name: String }); + Address = tmp.define('Address', {street: String}, {idInjection: false}); + Other = db.define('Other', {name: String}); }); it('can be declared using embedsOne method', function(done) { Person.embedsOne(Passport, { - default: { name: 'Anonymous' }, // a bit contrived - methods: { check: function() { return true; } }, + default: {name: 'Anonymous'}, // a bit contrived + methods: {check: function() { return true; }}, }); Person.embedsOne(Address); // all by default db.automigrate(['Person'], done); @@ -3548,7 +3549,7 @@ describe('relations', function() { it('should return an instance with default values', function() { var p = new Person(); - p.passport.toObject().should.eql({ name: 'Anonymous' }); + p.passport.toObject().should.eql({name: 'Anonymous'}); p.passportItem().should.equal(p.passport); p.passportItem(function(err, passport) { should.not.exist(err); @@ -3558,26 +3559,26 @@ describe('relations', function() { it('should embed a model instance', function() { var p = new Person(); - p.passportItem(new Passport({ name: 'Fred' })); - p.passport.toObject().should.eql({ name: 'Fred' }); + p.passportItem(new Passport({name: 'Fred'})); + p.passport.toObject().should.eql({name: 'Fred'}); p.passport.should.be.an.instanceOf(Passport); }); it('should not embed an invalid model type', function() { var p = new Person(); p.passportItem(new Other()); - p.passport.toObject().should.eql({ name: 'Anonymous' }); + p.passport.toObject().should.eql({name: 'Anonymous'}); p.passport.should.be.an.instanceOf(Passport); }); var personId; it('should create an embedded item on scope', function(done) { - Person.create({ name: 'Fred' }, function(err, p) { + Person.create({name: 'Fred'}, function(err, p) { should.not.exist(err); personId = p.id; - p.passportItem.create({ name: 'Fredric' }, function(err, passport) { + p.passportItem.create({name: 'Fredric'}, function(err, passport) { should.not.exist(err); - p.passport.toObject().should.eql({ name: 'Fredric' }); + p.passport.toObject().should.eql({name: 'Fredric'}); p.passport.should.be.an.instanceOf(Passport); done(); }); @@ -3588,7 +3589,7 @@ describe('relations', function() { Person.findById(personId, function(err, p) { should.not.exist(err); var passport = p.passportItem(); - passport.toObject().should.eql({ name: 'Fredric' }); + passport.toObject().should.eql({name: 'Fredric'}); passport.should.be.an.instanceOf(Passport); passport.should.equal(p.passport); passport.should.equal(p.passportItem.value()); @@ -3597,7 +3598,7 @@ describe('relations', function() { }); it('should validate an embedded item on scope - on creation', function(done) { - var p = new Person({ name: 'Fred' }); + var p = new Person({name: 'Fred'}); p.passportItem.create({}, function(err, passport) { should.exist(err); err.name.should.equal('ValidationError'); @@ -3622,10 +3623,10 @@ describe('relations', function() { it('should update an embedded item on scope', function(done) { Person.findById(personId, function(err, p) { - p.passportItem.update({ name: 'Freddy' }, function(err, passport) { + p.passportItem.update({name: 'Freddy'}, function(err, passport) { should.not.exist(err); var passport = p.passportItem(); - passport.toObject().should.eql({ name: 'Freddy' }); + passport.toObject().should.eql({name: 'Freddy'}); passport.should.be.an.instanceOf(Passport); passport.should.equal(p.passport); done(); @@ -3637,7 +3638,7 @@ describe('relations', function() { Person.findById(personId, function(err, p) { should.not.exist(err); var passport = p.passportItem(); - passport.toObject().should.eql({ name: 'Freddy' }); + passport.toObject().should.eql({name: 'Freddy'}); done(); }); }); @@ -3661,9 +3662,9 @@ describe('relations', function() { }); it('should save an unsaved model', function(done) { - var p = new Person({ name: 'Fred' }); + var p = new Person({name: 'Fred'}); p.isNewRecord().should.be.true; - p.passportItem.create({ name: 'Fredric' }, function(err, passport) { + p.passportItem.create({name: 'Fredric'}, function(err, passport) { should.not.exist(err); p.passport.should.equal(passport); p.isNewRecord().should.be.false; @@ -3672,12 +3673,12 @@ describe('relations', function() { }); it('should create an embedded item on scope with promises', function(done) { - Person.create({ name: 'Fred' }) + Person.create({name: 'Fred'}) .then(function(p) { personId = p.id; - p.passportItem.create({ name: 'Fredric' }) + p.passportItem.create({name: 'Fredric'}) .then(function(passport) { - p.passport.toObject().should.eql({ name: 'Fredric' }); + p.passport.toObject().should.eql({name: 'Fredric'}); p.passport.should.be.an.instanceOf(Passport); done(); }); @@ -3688,7 +3689,7 @@ describe('relations', function() { Person.findById(personId) .then(function(p) { var passport = p.passportItem(); - passport.toObject().should.eql({ name: 'Fredric' }); + passport.toObject().should.eql({name: 'Fredric'}); passport.should.be.an.instanceOf(Passport); passport.should.equal(p.passport); passport.should.equal(p.passportItem.value()); @@ -3697,7 +3698,7 @@ describe('relations', function() { }); it('should validate an embedded item on scope with promises - on creation', function(done) { - var p = new Person({ name: 'Fred' }); + var p = new Person({name: 'Fred'}); p.passportItem.create({}) .then(function(passport) { should.not.exist(passport); @@ -3734,10 +3735,10 @@ describe('relations', function() { it('should update an embedded item on scope with promises', function(done) { Person.findById(personId) .then(function(p) { - return p.passportItem.update({ name: 'Jason' }) + return p.passportItem.update({name: 'Jason'}) .then(function(passport) { var passport = p.passportItem(); - passport.toObject().should.eql({ name: 'Jason' }); + passport.toObject().should.eql({name: 'Jason'}); passport.should.be.an.instanceOf(Passport); passport.should.equal(p.passport); done(); @@ -3749,7 +3750,7 @@ describe('relations', function() { Person.findById(personId) .then(function(p) { var passport = p.passportItem(); - passport.toObject().should.eql({ name: 'Jason' }); + passport.toObject().should.eql({name: 'Jason'}); done(); }).catch(done); }); @@ -3779,7 +3780,7 @@ describe('relations', function() { Passport.definition.hasPK = function() { return true; }; Person.findById(personId) .then(function(p) { - return p.passportItem.create({ name: 'Mitsos' }); + return p.passportItem.create({name: 'Mitsos'}); }) .then(function(passport) { passport.name = 'Jim'; @@ -3789,7 +3790,7 @@ describe('relations', function() { return Person.findById(personId); }) .then(function(person) { - person.passportItem().toObject().should.eql({ name: 'Jim' }); + person.passportItem().toObject().should.eql({name: 'Jim'}); // restore original hasPk Passport.definition.hasPK = originalHasPK; done(); @@ -3826,24 +3827,24 @@ describe('relations', function() { // This test spefically uses the Memory connector // in order to test the use of the auto-generated // id, in the sequence of the related model. - + var Passport; before(function() { db = getMemoryDataSource(); - Person = db.define('Person', { name: String }); + Person = db.define('Person', {name: String}); Passport = db.define('Passport', - { name: { type: 'string', required: true }} + {name: {type: 'string', required: true}} ); }); it('can be declared using embedsOne method', function(done) { Person.embedsOne(Passport, { - options: { persistent: true }, + options: {persistent: true}, }); db.automigrate(['Person', 'Passport'], done); }); it('should create an item - to offset id', function(done) { - Passport.create({ name: 'Wilma' }, function(err, p) { + Passport.create({name: 'Wilma'}, function(err, p) { should.not.exist(err); p.id.should.equal(1); p.name.should.equal('Wilma'); @@ -3852,9 +3853,9 @@ describe('relations', function() { }); it('should create an embedded item on scope', function(done) { - Person.create({ name: 'Fred' }, function(err, p) { + Person.create({name: 'Fred'}, function(err, p) { should.not.exist(err); - p.passportItem.create({ name: 'Fredric' }, function(err, passport) { + p.passportItem.create({name: 'Fredric'}, function(err, passport) { should.not.exist(err); p.passport.id.should.eql(2); p.passport.name.should.equal('Fredric'); @@ -3864,9 +3865,9 @@ describe('relations', function() { }); it('should create an embedded item on scope with promises', function(done) { - Person.create({ name: 'Barney' }) + Person.create({name: 'Barney'}) .then(function(p) { - return p.passportItem.create({ name: 'Barnabus' }) + return p.passportItem.create({name: 'Barnabus'}) .then(function(passport) { p.passport.id.should.eql(3); p.passport.name.should.equal('Barnabus'); @@ -3878,15 +3879,15 @@ describe('relations', function() { }); describe('embedsOne - generated id', function() { - + var Passport; before(function() { tmp = getTransientDataSource(); // db = getSchema(); - Person = db.define('Person', { name: String }); + Person = db.define('Person', {name: String}); Passport = tmp.define('Passport', { - id: { type: 'string', id: true, generated: true }, - name: { type: 'string', required: true }, + id: {type: 'string', id: true, generated: true}, + name: {type: 'string', required: true}, } ); }); @@ -3897,9 +3898,9 @@ describe('relations', function() { }); it('should create an embedded item on scope', function(done) { - Person.create({ name: 'Fred' }, function(err, p) { + Person.create({name: 'Fred'}, function(err, p) { should.not.exist(err); - p.passportItem.create({ name: 'Fredric' }, function(err, passport) { + p.passportItem.create({name: 'Fredric'}, function(err, passport) { should.not.exist(err); passport.id.should.match(/^[0-9a-fA-F]{24}$/); p.passport.name.should.equal('Fredric'); @@ -3915,10 +3916,10 @@ describe('relations', function() { var address1, address2; before(function(done) { - tmp = getTransientDataSource({ defaultIdType: Number }); + tmp = getTransientDataSource({defaultIdType: Number}); // db = getSchema(); - Person = db.define('Person', { name: String }); - Address = tmp.define('Address', { street: String }); + Person = db.define('Person', {name: String}); + Address = tmp.define('Address', {street: String}); Address.validatesPresenceOf('street'); db.automigrate(['Person'], done); @@ -3930,7 +3931,7 @@ describe('relations', function() { }); it('should have setup embedded accessor/scope', function() { - var p = new Person({ name: 'Fred' }); + var p = new Person({name: 'Fred'}); p.addresses.should.be.an.array; p.addresses.should.have.length(0); p.addressList.should.be.a.function; @@ -3943,8 +3944,8 @@ describe('relations', function() { }); it('should create embedded items on scope', function(done) { - Person.create({ name: 'Fred' }, function(err, p) { - p.addressList.create({ street: 'Street 1' }, function(err, address) { + Person.create({name: 'Fred'}, function(err, p) { + p.addressList.create({street: 'Street 1'}, function(err, address) { should.not.exist(err); address1 = address; should.exist(address1.id); @@ -3956,7 +3957,7 @@ describe('relations', function() { it('should create embedded items on scope', function(done) { Person.findOne(function(err, p) { - p.addressList.create({ street: 'Street 2' }, function(err, address) { + p.addressList.create({street: 'Street 2'}, function(err, address) { should.not.exist(err); address2 = address; should.exist(address2.id); @@ -3989,7 +3990,7 @@ describe('relations', function() { it('should filter embedded items on scope', function(done) { Person.findOne(function(err, p) { - p.addressList({ where: { street: 'Street 2' }}, function(err, addresses) { + p.addressList({where: {street: 'Street 2'}}, function(err, addresses) { should.not.exist(err); addresses.should.have.length(1); addresses[0].id.should.eql(address2.id); @@ -4034,7 +4035,7 @@ describe('relations', function() { it('should update embedded items by id', function(done) { Person.findOne(function(err, p) { - p.addressList.updateById(address2.id, { street: 'New Street' }, function(err, address) { + p.addressList.updateById(address2.id, {street: 'New Street'}, function(err, address) { address.should.be.instanceof(Address); address.id.should.eql(address2.id); address.street.should.equal('New Street'); @@ -4045,7 +4046,7 @@ describe('relations', function() { it('should validate the update of embedded items', function(done) { Person.findOne(function(err, p) { - p.addressList.updateById(address2.id, { street: null }, function(err, address) { + p.addressList.updateById(address2.id, {street: null}, function(err, address) { err.name.should.equal('ValidationError'); err.details.codes.street.should.eql(['presence']); done(); @@ -4068,11 +4069,11 @@ describe('relations', function() { Person.findOne(function(err, p) { p.addressList.at(0).id.should.equal(address1.id); p.addressList.get(address1.id).id.should.equal(address1.id); - p.addressList.set(address1.id, { street: 'Changed 1' }); + p.addressList.set(address1.id, {street: 'Changed 1'}); p.addresses[0].street.should.equal('Changed 1'); p.addressList.at(1).id.should.equal(address2.id); p.addressList.get(address2.id).id.should.equal(address2.id); - p.addressList.set(address2.id, { street: 'Changed 2' }); + p.addressList.set(address2.id, {street: 'Changed 2'}); p.addresses[1].street.should.equal('Changed 2'); done(); }); @@ -4098,7 +4099,7 @@ describe('relations', function() { it('should create embedded items on scope', function(done) { Person.findOne(function(err, p) { - p.addressList.create({ street: 'Street 3' }, function(err, address) { + p.addressList.create({street: 'Street 3'}, function(err, address) { should.not.exist(err); address.street.should.equal('Street 3'); done(); @@ -4109,7 +4110,7 @@ describe('relations', function() { it('should remove embedded items - filtered', function(done) { Person.findOne(function(err, p) { p.addresses.should.have.length(2); - p.addressList.destroyAll({ street: 'Street 3' }, function(err) { + p.addressList.destroyAll({street: 'Street 3'}, function(err) { should.not.exist(err); p.addresses.should.have.length(1); done(); @@ -4136,9 +4137,9 @@ describe('relations', function() { }); it('should save an unsaved model', function(done) { - var p = new Person({ name: 'Fred' }); + var p = new Person({name: 'Fred'}); p.isNewRecord().should.be.true; - p.addressList.create({ street: 'Street 4' }, function(err, address) { + p.addressList.create({street: 'Street 4'}, function(err, address) { should.not.exist(err); address.street.should.equal('Street 4'); p.isNewRecord().should.be.false; @@ -4153,9 +4154,9 @@ describe('relations', function() { before(function(done) { tmp = getTransientDataSource(); // db = getSchema(); - Person = db.define('Person', { name: String }); + Person = db.define('Person', {name: String}); Address = tmp.define('Address', { - id: { type: Number, id: true }, + id: {type: Number, id: true}, street: String, }); @@ -4163,18 +4164,18 @@ describe('relations', function() { }); it('can be declared', function(done) { - Person.embedsMany(Address, { options: { forceId: true }}); + Person.embedsMany(Address, {options: {forceId: true}}); db.automigrate(['Person'], done); }); it('should create embedded items on scope', function(done) { - Person.create({ name: 'Fred' }, function(err, p) { - p.addressList.create({ street: 'Street 1' }, function(err, address) { + Person.create({name: 'Fred'}, function(err, p) { + p.addressList.create({street: 'Street 1'}, function(err, address) { should.not.exist(err); address.id.should.equal(1); - p.addressList.create({ street: 'Street 2' }, function(err, address) { + p.addressList.create({street: 'Street 2'}, function(err, address) { address.id.should.equal(2); - p.addressList.create({ id: 12345, street: 'Street 3' }, function(err, address) { + p.addressList.create({id: 12345, street: 'Street 3'}, function(err, address) { address.id.should.equal(3); done(); }); @@ -4189,8 +4190,8 @@ describe('relations', function() { before(function(done) { tmp = getTransientDataSource(); // db = getSchema(); - Person = db.define('Person', { name: String }); - Address = tmp.define('Address', { street: String }, { forceId: false }); + Person = db.define('Person', {name: String}); + Address = tmp.define('Address', {street: String}, {forceId: false}); Address.validatesPresenceOf('street'); db.automigrate(['Person'], done); @@ -4202,10 +4203,10 @@ describe('relations', function() { }); it('should create embedded items on scope', function(done) { - Person.create({ name: 'Fred' }, function(err, p) { - p.addressList.create({ id: 'home', street: 'Street 1' }, function(err, address) { + Person.create({name: 'Fred'}, function(err, p) { + p.addressList.create({id: 'home', street: 'Street 1'}, function(err, address) { should.not.exist(err); - p.addressList.create({ id: 'work', street: 'Work Street 2' }, function(err, address) { + p.addressList.create({id: 'work', street: 'Work Street 2'}, function(err, address) { should.not.exist(err); address.id.should.equal('work'); address.street.should.equal('Work Street 2'); @@ -4228,7 +4229,7 @@ describe('relations', function() { it('should check for duplicate ids', function(done) { Person.findOne(function(err, p) { - p.addressList.create({ id: 'home', street: 'Invalid' }, function(err, addresses) { + p.addressList.create({id: 'home', street: 'Invalid'}, function(err, addresses) { should.exist(err); err.name.should.equal('ValidationError'); err.details.codes.addresses.should.eql(['uniqueness']); @@ -4239,7 +4240,7 @@ describe('relations', function() { it('should update embedded items by id', function(done) { Person.findOne(function(err, p) { - p.addressList.updateById('home', { street: 'New Street' }, function(err, address) { + p.addressList.updateById('home', {street: 'New Street'}, function(err, address) { address.should.be.instanceof(Address); address.id.should.equal('home'); address.street.should.equal('New Street'); @@ -4268,9 +4269,9 @@ describe('relations', function() { it('should validate all embedded items', function(done) { var addresses = []; - addresses.push({ id: 'home', street: 'Home Street' }); - addresses.push({ id: 'work', street: '' }); - Person.create({ name: 'Wilma', addresses: addresses }, function(err, p) { + addresses.push({id: 'home', street: 'Home Street'}); + addresses.push({id: 'work', street: ''}); + Person.create({name: 'Wilma', addresses: addresses}, function(err, p) { err.name.should.equal('ValidationError'); err.details.messages.addresses.should.eql([ 'contains invalid item: `work` (`street` can\'t be blank)', @@ -4280,9 +4281,9 @@ describe('relations', function() { }); it('should build embedded items', function(done) { - Person.create({ name: 'Wilma' }, function(err, p) { - p.addressList.build({ id: 'home', street: 'Home' }); - p.addressList.build({ id: 'work', street: 'Work' }); + Person.create({name: 'Wilma'}, function(err, p) { + p.addressList.build({id: 'home', street: 'Home'}); + p.addressList.build({id: 'work', street: 'Work'}); p.addresses.should.have.length(2); p.save(function(err, p) { done(); @@ -4291,7 +4292,7 @@ describe('relations', function() { }); it('should have embedded items - verify', function(done) { - Person.findOne({ where: { name: 'Wilma' }}, function(err, p) { + Person.findOne({where: {name: 'Wilma'}}, function(err, p) { p.name.should.equal('Wilma'); p.addresses.should.have.length(2); p.addresses[0].id.should.equal('home'); @@ -4303,25 +4304,25 @@ describe('relations', function() { }); it('should have accessors: at, get, set', function(done) { - Person.findOne({ where: { name: 'Wilma' }}, function(err, p) { + Person.findOne({where: {name: 'Wilma'}}, function(err, p) { p.name.should.equal('Wilma'); p.addresses.should.have.length(2); p.addressList.at(0).id.should.equal('home'); p.addressList.get('home').id.should.equal('home'); - p.addressList.set('home', { id: 'den' }).id.should.equal('den'); + p.addressList.set('home', {id: 'den'}).id.should.equal('den'); p.addressList.at(1).id.should.equal('work'); p.addressList.get('work').id.should.equal('work'); - p.addressList.set('work', { id: 'factory' }).id.should.equal('factory'); + p.addressList.set('work', {id: 'factory'}).id.should.equal('factory'); done(); }); }); it('should create embedded from attributes - property name', function(done) { var addresses = [ - { id: 'home', street: 'Home Street' }, - { id: 'work', street: 'Work Street' }, + {id: 'home', street: 'Home Street'}, + {id: 'work', street: 'Work Street'}, ]; - Person.create({ name: 'Wilma', addresses: addresses }, function(err, p) { + Person.create({name: 'Wilma', addresses: addresses}, function(err, p) { should.not.exist(err); p.addressList.at(0).id.should.equal('home'); p.addressList.at(1).id.should.equal('work'); @@ -4331,10 +4332,10 @@ describe('relations', function() { it('should not create embedded from attributes - relation name', function(done) { var addresses = [ - { id: 'home', street: 'Home Street' }, - { id: 'work', street: 'Work Street' }, + {id: 'home', street: 'Home Street'}, + {id: 'work', street: 'Work Street'}, ]; - Person.create({ name: 'Wilma', addressList: addresses }, function(err, p) { + Person.create({name: 'Wilma', addressList: addresses}, function(err, p) { should.not.exist(err); p.addresses.should.have.length(0); done(); @@ -4342,8 +4343,8 @@ describe('relations', function() { }); it('should create embedded items with auto-generated id', function(done) { - Person.create({ name: 'Wilma' }, function(err, p) { - p.addressList.create({ street: 'Home Street 1' }, function(err, address) { + Person.create({name: 'Wilma'}, function(err, p) { + p.addressList.create({street: 'Home Street 1'}, function(err, address) { should.not.exist(err); address.id.should.match(/^[0-9a-fA-F]{24}$/); address.street.should.equal('Home Street 1'); @@ -4365,8 +4366,8 @@ describe('relations', function() { before(function(done) { db = getMemoryDataSource(); - Person = db.define('Person', { name: String }); - Address = db.define('Address', { street: String }); + Person = db.define('Person', {name: String}); + Address = db.define('Address', {street: String}); Address.validatesPresenceOf('street'); db.automigrate(['Person', 'Address'], done); @@ -4376,14 +4377,14 @@ describe('relations', function() { // to save related model itself, set // persistent: true Person.embedsMany(Address, { - scope: { order: 'street' }, - options: { persistent: true }, + scope: {order: 'street'}, + options: {persistent: true}, }); db.automigrate(['Person', 'Address'], done); }); it('should create individual items (0)', function(done) { - Address.create({ street: 'Street 0' }, function(err, inst) { + Address.create({street: 'Street 0'}, function(err, inst) { inst.id.should.equal(1); // offset sequence address0 = inst; done(); @@ -4391,7 +4392,7 @@ describe('relations', function() { }); it('should create individual items (1)', function(done) { - Address.create({ street: 'Street 1' }, function(err, inst) { + Address.create({street: 'Street 1'}, function(err, inst) { inst.id.should.equal(2); address1 = inst; done(); @@ -4399,7 +4400,7 @@ describe('relations', function() { }); it('should create individual items (2)', function(done) { - Address.create({ street: 'Street 2' }, function(err, inst) { + Address.create({street: 'Street 2'}, function(err, inst) { inst.id.should.equal(3); address2 = inst; done(); @@ -4407,14 +4408,14 @@ describe('relations', function() { }); it('should create individual items (3)', function(done) { - Address.create({ street: 'Street 3' }, function(err, inst) { + Address.create({street: 'Street 3'}, function(err, inst) { inst.id.should.equal(4); // offset sequence done(); }); }); it('should add embedded items on scope', function(done) { - Person.create({ name: 'Fred' }, function(err, p) { + Person.create({name: 'Fred'}, function(err, p) { person = p; p.addressList.create(address1.toObject(), function(err, address) { should.not.exist(err); @@ -4432,7 +4433,7 @@ describe('relations', function() { it('should create embedded items on scope', function(done) { Person.findById(person.id, function(err, p) { - p.addressList.create({ street: 'Street 4' }, function(err, address) { + p.addressList.create({street: 'Street 4'}, function(err, address) { should.not.exist(err); address.id.should.equal(5); // in Address sequence, correct offset address.street.should.equal('Street 4'); @@ -4455,8 +4456,8 @@ describe('relations', function() { }); it('should validate embedded items on scope - id', function(done) { - Person.create({ name: 'Wilma' }, function(err, p) { - p.addressList.create({ id: null, street: 'Street 1' }, function(err, address) { + Person.create({name: 'Wilma'}, function(err, p) { + p.addressList.create({id: null, street: 'Street 1'}, function(err, address) { should.not.exist(err); address.street.should.equal('Street 1'); done(); @@ -4465,8 +4466,8 @@ describe('relations', function() { }); it('should validate embedded items on scope - street', function(done) { - Person.create({ name: 'Wilma' }, function(err, p) { - p.addressList.create({ id: 1234 }, function(err, address) { + Person.create({name: 'Wilma'}, function(err, p) { + p.addressList.create({id: 1234}, function(err, address) { should.exist(err); err.name.should.equal('ValidationError'); err.details.codes.street.should.eql(['presence']); @@ -4486,35 +4487,35 @@ describe('relations', function() { before(function() { // db = getSchema(); - Category = db.define('Category', { name: String }); - Job = db.define('Job', { name: String }); - Link = db.define('Link', { name: String, notes: String }, { forceId: false }); + Category = db.define('Category', {name: String}); + Job = db.define('Job', {name: String}); + Link = db.define('Link', {name: String, notes: String}, {forceId: false}); }); it('can be declared', function(done) { Category.embedsMany(Link, { as: 'items', // rename - scope: { include: 'job' }, // always include - options: { belongsTo: 'job' }, // optional, for add()/remove() + scope: {include: 'job'}, // always include + options: {belongsTo: 'job'}, // optional, for add()/remove() }); Link.belongsTo(Job, { foreignKey: 'id', // re-use the actual job id - properties: { id: 'id', name: 'name' }, // denormalize, transfer id - options: { invertProperties: true }, + properties: {id: 'id', name: 'name'}, // denormalize, transfer id + options: {invertProperties: true}, }); db.automigrate(['Category', 'Job', 'Link'], function() { - Job.create({ name: 'Job 0' }, done); // offset ids for tests + Job.create({name: 'Job 0'}, done); // offset ids for tests }); }); it('should setup related items', function(done) { - Job.create({ name: 'Job 1' }, function(err, p) { + Job.create({name: 'Job 1'}, function(err, p) { if (err) return done(err); job1 = p; - Job.create({ name: 'Job 2' }, function(err, p) { + Job.create({name: 'Job 2'}, function(err, p) { if (err) return done(err); job2 = p; - Job.create({ name: 'Job 3' }, function(err, p) { + Job.create({name: 'Job 3'}, function(err, p) { if (err) return done(err); job3 = p; done(); @@ -4524,7 +4525,7 @@ describe('relations', function() { }); it('should associate items on scope', function(done) { - Category.create({ name: 'Category A' }, function(err, cat) { + Category.create({name: 'Category A'}, function(err, cat) { if (err) return done(err); var link = cat.items.build(); link.job(job1); @@ -4658,11 +4659,11 @@ describe('relations', function() { var jobId; it('should create items on scope', function(done) { - Category.create({ name: 'Category B' }, function(err, cat) { + Category.create({name: 'Category B'}, function(err, cat) { if (err) return done(err); category = cat; - var link = cat.items.build({ notes: 'Some notes...' }); - link.job.create({ name: 'Job 1' }, function(err, p) { + var link = cat.items.build({notes: 'Some notes...'}); + link.job.create({name: 'Job 1'}, function(err, p) { if (err) return done(err); jobId = p.id; cat.links[0].id.should.eql(p.id); @@ -4679,7 +4680,7 @@ describe('relations', function() { if (err) return done(err); cat.name.should.equal('Category B'); cat.links.toObject().should.eql([ - { id: jobId, name: 'Job 1', notes: 'Some notes...' }, + {id: jobId, name: 'Job 1', notes: 'Some notes...'}, ]); cat.items.at(0).should.equal(cat.links[0]); cat.items(function(err, items) { // alternative access @@ -4698,7 +4699,7 @@ describe('relations', function() { Category.findById(category.id, function(err, cat) { if (err) return done(err); var link = cat.items.at(0); - link.updateAttributes({ notes: 'Updated notes...' }, function(err, link) { + link.updateAttributes({notes: 'Updated notes...'}, function(err, link) { if (err) return done(err); link.notes.should.equal('Updated notes...'); done(); @@ -4711,7 +4712,7 @@ describe('relations', function() { if (err) return done(err); cat.name.should.equal('Category B'); cat.links.toObject().should.eql([ - { id: jobId, name: 'Job 1', notes: 'Updated notes...' }, + {id: jobId, name: 'Job 1', notes: 'Updated notes...'}, ]); done(); }); @@ -4747,12 +4748,12 @@ describe('relations', function() { // db = getSchema(); tmp = getTransientDataSource(); - Book = db.define('Book', { name: String }); - Author = db.define('Author', { name: String }); - Reader = db.define('Reader', { name: String }); + Book = db.define('Book', {name: String}); + Author = db.define('Author', {name: String}); + Reader = db.define('Reader', {name: String}); Link = tmp.define('Link', { - id: { type: Number, id: true }, + id: {type: Number, id: true}, name: String, notes: String, }); // generic model Link.validatesPresenceOf('linkedId'); @@ -4764,22 +4765,22 @@ describe('relations', function() { it('can be declared', function(done) { var idType = db.connector.getDefaultIdType(); - Book.embedsMany(Link, { as: 'people', + Book.embedsMany(Link, {as: 'people', polymorphic: 'linked', - scope: { include: 'linked' }, + scope: {include: 'linked'}, }); Link.belongsTo('linked', { - polymorphic: { idType: idType }, // native type - properties: { name: 'name' }, // denormalized - options: { invertProperties: true }, + polymorphic: {idType: idType}, // native type + properties: {name: 'name'}, // denormalized + options: {invertProperties: true}, }); db.automigrate(['Book', 'Author', 'Reader'], done); }); it('should setup related items', function(done) { - Author.create({ name: 'Author 1' }, function(err, p) { + Author.create({name: 'Author 1'}, function(err, p) { person1 = p; - Reader.create({ name: 'Reader 1' }, function(err, p) { + Reader.create({name: 'Reader 1'}, function(err, p) { person2 = p; done(); }); @@ -4787,8 +4788,8 @@ describe('relations', function() { }); it('should create items on scope', function(done) { - Book.create({ name: 'Book' }, function(err, book) { - var link = book.people.build({ notes: 'Something ...' }); + Book.create({name: 'Book'}, function(err, book) { + var link = book.people.build({notes: 'Something ...'}); link.linked(person1); var link = book.people.build(); link.linked(person2); @@ -4852,7 +4853,7 @@ describe('relations', function() { // to sort this out (delete links, keep people). // In loopback, an afterRemote filter could do this as well. - Book.find({ include: 'people' }, function(err, books) { + Book.find({include: 'people'}, function(err, books) { var obj = books[0].toObject(); obj.should.have.property('links'); @@ -4882,8 +4883,8 @@ describe('relations', function() { before(function(done) { // db = getSchema(); - Category = db.define('Category', { name: String }); - Job = db.define('Job', { name: String }); + Category = db.define('Category', {name: String}); + Job = db.define('Job', {name: String}); db.automigrate(['Job', 'Category'], done); }); @@ -4901,9 +4902,9 @@ describe('relations', function() { }; reverse.shared = true; // remoting - reverse.http = { verb: 'put', path: '/jobs/reverse' }; + reverse.http = {verb: 'put', path: '/jobs/reverse'}; - Category.referencesMany(Job, { scopeMethods: { + Category.referencesMany(Job, {scopeMethods: { reverse: reverse, }}); @@ -4915,9 +4916,9 @@ describe('relations', function() { }); it('should setup test records', function(done) { - Job.create({ name: 'Job 1' }, function(err, p) { + Job.create({name: 'Job 1'}, function(err, p) { job1 = p; - Job.create({ name: 'Job 3' }, function(err, p) { + Job.create({name: 'Job 3'}, function(err, p) { job3 = p; done(); }); @@ -4925,10 +4926,10 @@ describe('relations', function() { }); it('should create record on scope', function(done) { - Category.create({ name: 'Category A' }, function(err, cat) { + Category.create({name: 'Category A'}, function(err, cat) { cat.jobIds.should.be.an.array; cat.jobIds.should.have.length(0); - cat.jobs.create({ name: 'Job 2' }, function(err, p) { + cat.jobs.create({name: 'Job 2'}, function(err, p) { should.not.exist(err); cat.jobIds.should.have.length(1); cat.jobIds.should.eql([p.id]); @@ -4989,7 +4990,7 @@ describe('relations', function() { it('should update a record on scope', function(done) { Category.findOne(function(err, cat) { - var attrs = { name: 'Job 2 - edit' }; + var attrs = {name: 'Job 2 - edit'}; cat.jobs.updateById(job2.id, attrs, function(err, p) { should.not.exist(err); p.name.should.equal(attrs.name); @@ -5048,7 +5049,7 @@ describe('relations', function() { it('should find items on scope - filter', function(done) { Category.findOne(function(err, cat) { - var filter = { where: { name: 'Job 1' }}; + var filter = {where: {name: 'Job 1'}}; cat.jobs(filter, function(err, jobs) { should.not.exist(err); jobs.should.have.length(1); @@ -5089,7 +5090,7 @@ describe('relations', function() { it('should find items on scope and ordered them by name DESC', function(done) { Category.find(function(err, categories) { categories.should.have.length(1); - categories[0].jobs({ order: 'name DESC' }, function(err, jobs) { + categories[0].jobs({order: 'name DESC'}, function(err, jobs) { should.not.exist(err); jobs.should.have.length(2); jobs[0].id.should.eql(job3.id); @@ -5111,7 +5112,7 @@ describe('relations', function() { }); it('should include related items from scope', function(done) { - Category.find({ include: 'jobs' }, function(err, categories) { + Category.find({include: 'jobs'}, function(err, categories) { categories.should.have.length(1); var cat = categories[0].toObject(); cat.name.should.equal('Category A'); @@ -5153,10 +5154,10 @@ describe('relations', function() { it('should setup test records with promises', function(done) { db.automigrate(['Job', 'Category'], function() { - return Job.create({ name: 'Job 1' }) + return Job.create({name: 'Job 1'}) .then(function(p) { job1 = p; - return Job.create({ name: 'Job 3' }); + return Job.create({name: 'Job 3'}); }) .then(function(p) { job3 = p; @@ -5166,11 +5167,11 @@ describe('relations', function() { }); it('should create record on scope with promises', function(done) { - Category.create({ name: 'Category A' }) + Category.create({name: 'Category A'}) .then(function(cat) { cat.jobIds.should.be.an.array; cat.jobIds.should.have.length(0); - return cat.jobs.create({ name: 'Job 2' }) + return cat.jobs.create({name: 'Job 2'}) .then(function(p) { cat.jobIds.should.have.length(1); cat.jobIds.should.eql([p.id]); @@ -5240,7 +5241,7 @@ describe('relations', function() { it('should update a record on scope with promises', function(done) { Category.findOne() .then(function(cat) { - var attrs = { name: 'Job 2 - edit' }; + var attrs = {name: 'Job 2 - edit'}; return cat.jobs.updateById(job2.id, attrs) .then(function(p) { p.name.should.equal(attrs.name); @@ -5309,7 +5310,7 @@ describe('relations', function() { it('should find items on scope with promises - filter', function(done) { Category.findOne() .then(function(cat) { - var filter = { where: { name: 'Job 1' }}; + var filter = {where: {name: 'Job 1'}}; return cat.jobs.getAsync(filter); }) .then(function(jobs) { @@ -5356,7 +5357,7 @@ describe('relations', function() { Category.find() .then(function(categories) { categories.should.have.length(1); - return categories[0].jobs.getAsync({ order: 'name DESC' }); + return categories[0].jobs.getAsync({order: 'name DESC'}); }) .then(function(jobs) { jobs.should.have.length(2); @@ -5382,7 +5383,7 @@ describe('relations', function() { }); it('should include related items from scope with promises', function(done) { - Category.find({ include: 'jobs' }) + Category.find({include: 'jobs'}) .then(function(categories) { categories.should.have.length(1); var cat = categories[0].toObject(); @@ -5433,8 +5434,8 @@ describe('relations', function() { before(function(done) { // db = getSchema(); - Category = db.define('Category', { name: String }); - Job = db.define('Job', { name: String }); + Category = db.define('Category', {name: String}); + Job = db.define('Job', {name: String}); db.automigrate(['Job', 'Category'], done); }); @@ -5458,7 +5459,7 @@ describe('relations', function() { }; summarize.shared = true; // remoting - summarize.http = { verb: 'get', path: '/jobs/summary' }; + summarize.http = {verb: 'get', path: '/jobs/summary'}; relation.defineMethod('summarize', summarize); @@ -5470,10 +5471,10 @@ describe('relations', function() { }); it('should setup test records', function(done) { - Category.create({ name: 'Category A' }, function(err, cat) { + Category.create({name: 'Category A'}, function(err, cat) { categoryId = cat.id; - cat.jobs.create({ name: 'Job 1' }, function(err, p) { - cat.jobs.create({ name: 'Job 2' }, function(err, p) { + cat.jobs.create({name: 'Job 1'}, function(err, p) { + cat.jobs.create({name: 'Job 2'}, function(err, p) { done(); }); }); @@ -5482,8 +5483,8 @@ describe('relations', function() { it('should allow custom scope methods - summarize', function(done) { var expected = [ - { name: 'Job 1', categoryId: categoryId, categoryName: 'Category A' }, - { name: 'Job 2', categoryId: categoryId, categoryName: 'Category A' }, + {name: 'Job 1', categoryId: categoryId, categoryName: 'Category A'}, + {name: 'Job 2', categoryId: categoryId, categoryName: 'Category A'}, ]; Category.findOne(function(err, cat) { @@ -5501,8 +5502,8 @@ describe('relations', function() { it('should allow custom scope methods with promises - summarize', function(done) { var expected = [ - { name: 'Job 1', categoryId: categoryId, categoryName: 'Category A' }, - { name: 'Job 2', categoryId: categoryId, categoryName: 'Category A' }, + {name: 'Job 1', categoryId: categoryId, categoryName: 'Category A'}, + {name: 'Job 2', categoryId: categoryId, categoryName: 'Category A'}, ]; Category.findOne() diff --git a/test/schema.test.js b/test/schema.test.js index d4497d70..92982176 100644 --- a/test/schema.test.js +++ b/test/schema.test.js @@ -4,6 +4,7 @@ // License text available at https://opensource.org/licenses/MIT // This test written in mocha+should.js +'use strict'; var should = require('./init.js'); var db = getSchema(), slave = getSchema(), Model, SlaveModel; diff --git a/test/scope.test.js b/test/scope.test.js index 6071bcc7..543cf37b 100644 --- a/test/scope.test.js +++ b/test/scope.test.js @@ -4,6 +4,7 @@ // License text available at https://opensource.org/licenses/MIT // This test written in mocha+should.js +'use strict'; var should = require('./init.js'); var db, Railway, Station; @@ -13,7 +14,7 @@ describe('scope', function() { before(function() { db = getSchema(); Railway = db.define('Railway', { - URID: { type: String, index: true }, + URID: {type: String, index: true}, }, { scopes: { highSpeed: { @@ -24,11 +25,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}, }); }); @@ -44,7 +45,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); @@ -56,8 +57,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); @@ -68,9 +69,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) { @@ -82,7 +83,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; @@ -110,10 +111,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) { @@ -121,15 +122,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) { @@ -145,7 +146,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'); @@ -165,15 +166,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) { @@ -181,22 +182,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) { @@ -220,7 +221,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(); @@ -260,7 +261,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(); @@ -268,7 +269,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(); @@ -276,7 +277,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(); @@ -292,7 +293,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(); @@ -308,7 +309,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(); }); @@ -333,15 +334,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) { @@ -353,27 +354,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) { @@ -387,7 +388,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) { @@ -401,7 +402,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() { @@ -419,16 +420,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); }); }); diff --git a/test/spec_helper.js b/test/spec_helper.js index 27a75c61..9be024d2 100644 --- a/test/spec_helper.js +++ b/test/spec_helper.js @@ -13,6 +13,8 @@ } */ +'use strict'; + var group_name = false, EXT_EXP; function it(should, test_case) { check_external_exports(); diff --git a/test/transient.test.js b/test/transient.test.js index 6d9745bc..92dd3ed2 100644 --- a/test/transient.test.js +++ b/test/transient.test.js @@ -3,6 +3,7 @@ // 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; var assert = require('assert'); @@ -19,14 +20,14 @@ 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, }); }); @@ -34,9 +35,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); @@ -52,7 +53,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'); @@ -71,7 +72,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'); diff --git a/test/util.test.js b/test/util.test.js index 30799839..a8c8f8d1 100644 --- a/test/util.test.js +++ b/test/util.test.js @@ -3,6 +3,7 @@ // 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'); var fieldsToArray = utils.fieldsToArray; @@ -30,10 +31,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() { @@ -43,23 +44,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); @@ -68,14 +69,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/); }); @@ -146,71 +147,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'); }); @@ -219,12 +220,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() { @@ -259,8 +260,8 @@ describe('util.mergeIncludes', function() { var baseInclude = 'relation1'; var updateInclude = 'relation2'; var expectedInclude = [ - { relation2: true }, - { relation1: true }, + {relation2: true}, + {relation1: true}, ]; checkInputOutput(baseInclude, updateInclude, expectedInclude); }); @@ -269,18 +270,18 @@ describe('util.mergeIncludes', function() { var baseInclude = 'relation1'; var updateInclude = ['relation2']; var expectedInclude = [ - { relation2: true }, - { relation1: true }, + {relation2: true}, + {relation1: true}, ]; checkInputOutput(baseInclude, updateInclude, expectedInclude); }); it('Merge string & object values to object', function() { var baseInclude = ['relation1']; - var updateInclude = { relation2: 'relation2Include' }; + var updateInclude = {relation2: 'relation2Include'}; var expectedInclude = [ - { relation2: 'relation2Include' }, - { relation1: true }, + {relation2: 'relation2Include'}, + {relation1: true}, ]; checkInputOutput(baseInclude, updateInclude, expectedInclude); }); @@ -289,37 +290,37 @@ describe('util.mergeIncludes', function() { var baseInclude = ['relation1']; var updateInclude = ['relation2']; var expectedInclude = [ - { relation2: true }, - { relation1: true }, + {relation2: true}, + {relation1: true}, ]; checkInputOutput(baseInclude, updateInclude, expectedInclude); }); it('Merge array & object values to object', function() { var baseInclude = ['relation1']; - var updateInclude = { relation2: 'relation2Include' }; + var updateInclude = {relation2: 'relation2Include'}; var expectedInclude = [ - { relation2: 'relation2Include' }, - { relation1: true }, + {relation2: 'relation2Include'}, + {relation1: true}, ]; checkInputOutput(baseInclude, updateInclude, expectedInclude); }); it('Merge object & object values to object', function() { - var baseInclude = { relation1: 'relation1Include' }; - var updateInclude = { relation2: 'relation2Include' }; + var baseInclude = {relation1: 'relation1Include'}; + var updateInclude = {relation2: 'relation2Include'}; var expectedInclude = [ - { relation2: 'relation2Include' }, - { relation1: 'relation1Include' }, + {relation2: 'relation2Include'}, + {relation1: 'relation1Include'}, ]; checkInputOutput(baseInclude, updateInclude, expectedInclude); }); it('Override property collision with update value', function() { - var baseInclude = { relation1: 'baseValue' }; - var updateInclude = { relation1: 'updateValue' }; + var baseInclude = {relation1: 'baseValue'}; + var updateInclude = {relation1: 'updateValue'}; var expectedInclude = [ - { relation1: 'updateValue' }, + {relation1: 'updateValue'}, ]; checkInputOutput(baseInclude, updateInclude, expectedInclude); }); @@ -327,9 +328,9 @@ describe('util.mergeIncludes', function() { it('Merge string includes & include with relation syntax properly', function() { var baseInclude = 'relation1'; - var updateInclude = { relation: 'relation1' }; + var updateInclude = {relation: 'relation1'}; var expectedInclude = [ - { relation: 'relation1' }, + {relation: 'relation1'}, ]; checkInputOutput(baseInclude, updateInclude, expectedInclude); }); @@ -338,10 +339,10 @@ describe('util.mergeIncludes', function() { var baseInclude = 'relation1'; var updateInclude = { relation: 'relation1', - scope: { include: 'relation2' }, + scope: {include: 'relation2'}, }; var expectedInclude = [ - { relation: 'relation1', scope: { include: 'relation2' }}, + {relation: 'relation1', scope: {include: 'relation2'}}, ]; checkInputOutput(baseInclude, updateInclude, expectedInclude); }); @@ -352,39 +353,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); }); }); diff --git a/test/validations.test.js b/test/validations.test.js index 28e15705..daed9985 100644 --- a/test/validations.test.js +++ b/test/validations.test.js @@ -4,6 +4,7 @@ // License text available at https://opensource.org/licenses/MIT // This test written in mocha+should.js +'use strict'; var should = require('./init.js'); var async = require('async'); @@ -42,8 +43,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); @@ -65,7 +66,7 @@ describe('validations', 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; @@ -75,7 +76,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; @@ -85,7 +86,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; @@ -95,7 +96,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; @@ -112,7 +113,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) { @@ -126,7 +127,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) { @@ -140,7 +141,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) { @@ -154,7 +155,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) { @@ -173,7 +174,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(); }); @@ -183,7 +184,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); @@ -201,7 +202,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) { @@ -215,7 +216,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); }); }); @@ -225,7 +226,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(); @@ -280,7 +281,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; @@ -293,12 +294,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(); }); @@ -309,7 +310,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); @@ -327,7 +328,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(); }); @@ -339,7 +340,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(); }); @@ -353,8 +354,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; @@ -383,7 +384,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; @@ -401,12 +402,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; }); @@ -415,11 +416,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(); @@ -430,7 +431,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() { @@ -450,23 +451,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(); @@ -482,11 +483,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(); @@ -500,7 +501,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(); @@ -508,8 +509,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(); @@ -532,26 +533,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; }); }); @@ -576,10 +577,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() { @@ -589,10 +590,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) { @@ -602,7 +603,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(); @@ -629,26 +630,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] } ]).'); });