diff --git a/examples/app-noschema.js b/examples/app-noschema.js index 95ce3c98..0d9d4e92 100644 --- a/examples/app-noschema.js +++ b/examples/app-noschema.js @@ -10,14 +10,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 +33,7 @@ var application = { 'interval': 300, }, }}, - ] }; + ]}; console.log(new Application(application).toObject()); @@ -59,8 +59,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 +69,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..8f0bf98f 100644 --- a/examples/app.js +++ b/examples/app.js @@ -7,13 +7,13 @@ 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 +25,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..5e60173a 100644 --- a/examples/datasource-app.js +++ b/examples/datasource-app.js @@ -9,13 +9,13 @@ var ds = new DataSource('memory'); // define models var Post = ds.define('Post', { - title: { type: String, length: 255 }, - content: { type: DataSource.Text }, - date: { type: Date, default: function() { + title: {type: String, length: 255}, + content: {type: DataSource.Text}, + date: {type: Date, default: function() { return new Date; - } }, - timestamp: { type: Number, default: Date.now }, - published: { type: Boolean, default: false, index: true }, + }}, + timestamp: {type: Number, default: Date.now}, + published: {type: Boolean, default: false, index: true}, }); // simplier way to describe model @@ -27,28 +27,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 +56,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 +112,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..f51a362d 100644 --- a/examples/inclusion.js +++ b/examples/inclusion.js @@ -9,31 +9,31 @@ var User, Post, Passport, City, Street, Building; var nbSchemaRequests = 0; setup(function() { - Passport.find({ include: 'owner' }, function(err, passports) { + Passport.find({include: 'owner'}, function(err, passports) { console.log('passports.owner', passports); }); - User.find({ include: 'posts' }, function(err, users) { + User.find({include: 'posts'}, function(err, users) { console.log('users.posts', users); }); - Passport.find({ include: { owner: 'posts' }}, function(err, passports) { + Passport.find({include: {owner: 'posts'}}, function(err, passports) { console.log('passports.owner.posts', passports); }); Passport.find({ - include: { owner: { posts: 'author' }}, + include: {owner: {posts: 'author'}}, }, function(err, passports) { console.log('passports.owner.posts.author', passports); }); - User.find({ include: ['posts', 'passports'] }, function(err, users) { + User.find({include: ['posts', 'passports']}, function(err, users) { console.log('users.passports && users.posts', users); }); }); function setup(done) { - var db = new jdb.DataSource({ connector: 'memory' }); + var db = new jdb.DataSource({connector: 'memory'}); City = db.define('City'); Street = db.define('Street'); Building = db.define('Building'); @@ -48,10 +48,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 +62,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 +79,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 +94,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/nesting-schema.js b/examples/nesting-schema.js index 93ea233d..1d553a39 100644 --- a/examples/nesting-schema.js +++ b/examples/nesting-schema.js @@ -38,8 +38,8 @@ var user = new User({ state: 'CA', }, emails: [ - { label: 'work', email: 'xyz@sample.com' }, + {label: 'work', email: 'xyz@sample.com'}, ], - friends: ['John', 'Mary'] }); + friends: ['John', 'Mary']}); console.log(user); console.log(user.toObject()); diff --git a/examples/relations.js b/examples/relations.js index 496170f1..156e1a46 100644 --- a/examples/relations.js +++ b/examples/relations.js @@ -20,43 +20,43 @@ Order.belongsTo(Customer); var order1, order2, order3; -Customer.create({ name: 'John' }, function(err, customer) { - Order.create({ customerId: customer.id, orderDate: new Date(), items: ['Book'] }, function(err, order) { +Customer.create({name: 'John'}, function(err, customer) { + Order.create({customerId: customer.id, orderDate: new Date(), items: ['Book']}, function(err, order) { order1 = order; order.customer(console.log); order.customer(true, console.log); - Customer.create({ name: 'Mary' }, function(err, customer2) { + Customer.create({name: 'Mary'}, function(err, customer2) { order.customer(customer2); order.customer(console.log); }); }); - Order.create({ orderDate: new Date(), items: ['Phone'] }, function(err, order) { - order.customer.create({ name: 'Smith' }, function(err, customer2) { + Order.create({orderDate: new Date(), items: ['Phone']}, function(err, order) { + order.customer.create({name: 'Smith'}, function(err, customer2) { console.log(order, customer2); order.save(function(err, order) { order2 = order; }); }); - var customer3 = order.customer.build({ name: 'Tom' }); + var customer3 = order.customer.build({name: 'Tom'}); console.log('Customer 3', customer3); }); }); -Customer.hasMany(Order, { as: 'orders', foreignKey: 'customerId' }); +Customer.hasMany(Order, {as: 'orders', foreignKey: 'customerId'}); -Customer.create({ name: 'Ray' }, function(err, customer) { - Order.create({ customerId: customer.id, qty: 3, orderDate: new Date() }, function(err, order) { +Customer.create({name: 'Ray'}, function(err, customer) { + Order.create({customerId: customer.id, qty: 3, orderDate: new Date()}, function(err, order) { order3 = order; customer.orders(console.log); - customer.orders.create({ orderDate: new Date(), qty: 4 }, function(err, order) { + customer.orders.create({orderDate: new Date(), qty: 4}, function(err, order) { console.log(order); Customer.include([customer], 'orders', function(err, results) { console.log('Results: ', results); }); - customer.orders({ where: { qty: 4 }}, function(err, results) { + customer.orders({where: {qty: 4}}, function(err, results) { console.log('customer.orders', results); }); customer.orders.findById(order3.id, console.log); @@ -82,13 +82,13 @@ var Appointment = ds.createModel('Appointment', { Appointment.belongsTo(Patient); Appointment.belongsTo(Physician); -Physician.hasMany(Patient, { through: Appointment }); -Patient.hasMany(Physician, { through: Appointment }); +Physician.hasMany(Patient, {through: Appointment}); +Patient.hasMany(Physician, {through: Appointment}); -Physician.create({ name: 'Dr John' }, function(err, physician1) { - Physician.create({ name: 'Dr Smith' }, function(err, physician2) { - Patient.create({ name: 'Mary' }, function(err, patient1) { - Patient.create({ name: 'Ben' }, function(err, patient2) { +Physician.create({name: 'Dr John'}, function(err, physician1) { + Physician.create({name: 'Dr Smith'}, function(err, physician2) { + Patient.create({name: 'Mary'}, function(err, patient1) { + Patient.create({name: 'Ben'}, function(err, patient2) { Appointment.create({ appointmentDate: new Date(), physicianId: physician1.id, @@ -100,11 +100,11 @@ Physician.create({ name: 'Dr John' }, function(err, physician1) { patientId: patient2.id, }, function(err, appt2) { physician1.patients(console.log); - physician1.patients({ where: { name: 'Mary' }}, console.log); + physician1.patients({where: {name: 'Mary'}}, console.log); patient1.physicians(console.log); // Build an appointment? - var patient3 = patient1.physicians.build({ name: 'Dr X' }); + var patient3 = patient1.physicians.build({name: 'Dr X'}); console.log( 'Physician 3: ', patient3, @@ -113,7 +113,7 @@ Physician.create({ name: 'Dr John' }, function(err, physician1) { // Create a physician? patient1.physicians.create( - { name: 'Dr X' }, + {name: 'Dr X'}, function(err, patient4) { console.log( 'Physician 4: ', @@ -140,22 +140,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/lib/connectors/memory.js b/lib/connectors/memory.js index d75e9391..c14b46ba 100644 --- a/lib/connectors/memory.js +++ b/lib/connectors/memory.js @@ -107,7 +107,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 +241,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 +256,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 +323,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 +342,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 +412,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 +485,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 +507,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 +522,7 @@ function applyFilter(filter) { var dotIndex = key.indexOf('.'); var subValue = obj[key.substring(0, dotIndex)]; if (dotIndex !== -1) { - var subFilter = { where: {}}; + var subFilter = {where: {}}; var subKey = key.substring(dotIndex + 1); subFilter.where[subKey] = where[key]; if (Array.isArray(subValue)) { @@ -601,8 +601,8 @@ function applyFilter(filter) { } if ('between' in example) { - return (testInEquality({ gte: example.between[0] }, value) && - testInEquality({ lte: example.between[1] }, value)); + return (testInEquality({gte: example.between[0]}, value) && + testInEquality({lte: example.between[1]}, value)); } if (example.like || example.nlike || example.ilike || example.nilike) { @@ -687,7 +687,7 @@ Memory.prototype.destroyAll = function destroyAll(model, where, options, callbac var filter = null; var count = 0; if (where) { - filter = applyFilter({ where: where }); + filter = applyFilter({where: where}); Object.keys(cache).forEach(function(id) { if (!filter || filter(this.fromDb(model, cache[id]))) { count++; @@ -698,14 +698,14 @@ Memory.prototype.destroyAll = function destroyAll(model, where, options, callbac count = Object.keys(cache).length; this.collection(model, {}); } - this.saveToFile({ count: count }, callback); + this.saveToFile({count: count}, callback); }; Memory.prototype.count = function count(model, where, options, callback) { var cache = this.collection(model); var data = Object.keys(cache); if (where) { - var filter = { where: where }; + var filter = {where: where}; data = data.map(function(id) { return this.fromDb(model, cache[id]); }.bind(this)); @@ -722,7 +722,7 @@ Memory.prototype.update = var cache = this.collection(model); var filter = null; where = where || {}; - filter = applyFilter({ where: where }); + filter = applyFilter({where: where}); var ids = Object.keys(cache); var count = 0; @@ -739,7 +739,7 @@ Memory.prototype.update = } }, function(err) { if (err) return cb(err); - self.saveToFile({ count: count }, cb); + self.saveToFile({count: count}, cb); }); }; @@ -803,7 +803,7 @@ Memory.prototype.replaceOrCreate = function(model, data, options, callback) { var self = this; var idName = self.idNames(model)[0]; var idValue = self.getIdValue(model, data); - var filter = { where: {}}; + var filter = {where: {}}; filter.where[idName] = idValue; var nodes = self._findAllSkippingIncludes(model, filter); var found = nodes[0]; @@ -815,14 +815,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..19a5cd9f 100644 --- a/lib/connectors/transient.js +++ b/lib/connectors/transient.js @@ -104,7 +104,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 22d9918b..e0c32af7 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) { @@ -507,7 +507,7 @@ DataAccessObject.upsert = function(data, options, cb) { var update = data; var inst = data; if (!(data instanceof Model)) { - inst = new Model(data, { applyDefaultValues: false }); + inst = new Model(data, {applyDefaultValues: false}); } update = inst.toObject(false); @@ -580,7 +580,7 @@ DataAccessObject.upsert = function(data, options, cb) { var obj; if (data && !(data instanceof Model)) { - inst._initProperties(data, { persisted: true }); + inst._initProperties(data, {persisted: true}); obj = inst; } else { obj = data; @@ -610,11 +610,11 @@ DataAccessObject.upsert = function(data, options, cb) { } }); } else { - var opts = { notify: false }; + var opts = {notify: false}; if (ctx.options && ctx.options.transaction) { opts.transaction = ctx.options.transaction; } - Model.findOne({ where: ctx.query.where }, opts, function(err, inst) { + Model.findOne({where: ctx.query.where}, opts, function(err, inst) { if (err) { return cb(err); } @@ -679,7 +679,7 @@ DataAccessObject.upsertWithWhere = function(where, data, options, cb) { var Model = this; var connector = Model.getConnector(); var modelName = Model.modelName; - var query = { where: where }; + var query = {where: where}; var context = { Model: Model, query: query, @@ -704,7 +704,7 @@ DataAccessObject.upsertWithWhere = function(where, data, options, cb) { var update = data; var inst = data; if (!(data instanceof Model)) { - inst = new Model(data, { applyDefaultValues: false }); + inst = new Model(data, {applyDefaultValues: false}); } update = inst.toObject(false); Model.applyScope(query); @@ -758,7 +758,7 @@ DataAccessObject.upsertWithWhere = function(where, data, options, cb) { if (err) return cb(err); var obj; if (contxt.data && !(contxt.data instanceof Model)) { - inst._initProperties(contxt.data, { persisted: true }); + inst._initProperties(contxt.data, {persisted: true}); obj = inst; } else { obj = contxt.data; @@ -777,11 +777,11 @@ DataAccessObject.upsertWithWhere = function(where, data, options, cb) { } }); } else { - var opts = { notify: false }; + var opts = {notify: false}; if (ctx.options && ctx.options.transaction) { opts.transaction = ctx.options.transaction; } - self.find({ where: ctx.query.where }, opts, function(err, instances) { + self.find({where: ctx.query.where}, opts, function(err, instances) { if (err) return cb(err); var modelsLength = instances.length; if (modelsLength === 0) { @@ -931,7 +931,7 @@ DataAccessObject.replaceOrCreate = function replaceOrCreate(data, options, cb) { var obj; if (data && !(data instanceof Model)) { - inst._initProperties(data, { persisted: true }); + inst._initProperties(data, {persisted: true}); obj = inst; } else { obj = data; @@ -958,11 +958,11 @@ DataAccessObject.replaceOrCreate = function replaceOrCreate(data, options, cb) { } }); } else { - var opts = { notify: false }; + var opts = {notify: false}; if (ctx.options && ctx.options.transaction) { opts.transaction = ctx.options.transaction; } - Model.findOne({ where: ctx.query.where }, opts, function(err, found) { + Model.findOne({where: ctx.query.where}, opts, function(err, found) { if (err) return cb(err); if (!isOriginalQuery) { // The custom query returned from a hook may hide the fact that @@ -1007,14 +1007,14 @@ DataAccessObject.findOrCreate = function findOrCreate(query, data, options, cb) // findOrCreate(data); // query will be built from data, and method will return Promise data = query; - query = { where: data }; + query = {where: data}; } else if (options === undefined && cb === undefined) { if (typeof data === 'function') { // findOrCreate(data, cb); // query will be built from data cb = data; data = query; - query = { where: data }; + query = {where: data}; } } else if (cb === undefined) { if (typeof options === 'function') { @@ -1025,7 +1025,7 @@ DataAccessObject.findOrCreate = function findOrCreate(query, data, options, cb) } cb = cb || utils.createPromiseCallback(); - query = query || { where: {}}; + query = query || {where: {}}; data = data || {}; options = options || {}; @@ -1056,8 +1056,8 @@ DataAccessObject.findOrCreate = function findOrCreate(query, data, options, cb) var obj, Model = self.lookupModel(data); if (data) { - obj = new Model(data, { fields: query.fields, applySetters: false, - persisted: true }); + obj = new Model(data, {fields: query.fields, applySetters: false, + persisted: true}); } if (created) { @@ -1344,9 +1344,9 @@ DataAccessObject.findByIds = function(ids, query, options, cb) { return cb.promise; } - var filter = { where: {}}; + var filter = {where: {}}; var pk = idName(this); - filter.where[pk] = { inq: [].concat(ids) }; + filter.where[pk] = {inq: [].concat(ids)}; mergeQuery(filter, query || {}); // to know if the result need to be sorted by ids or not @@ -1866,7 +1866,7 @@ DataAccessObject.find = function find(query, options, cb) { if (!err && Array.isArray(data)) { async.map(data, function(item, next) { var Model = self.lookupModel(item); - var obj = new Model(item, { fields: query.fields, applySetters: false, persisted: true }); + var obj = new Model(item, {fields: query.fields, applySetters: false, persisted: true}); if (query && query.include) { if (query.collect) { @@ -2064,7 +2064,7 @@ DataAccessObject.destroyAll = function destroyAll(where, options, cb) { var hookState = {}; - var query = { where: where }; + var query = {where: where}; this.applyScope(query); where = query.where; @@ -2078,7 +2078,7 @@ DataAccessObject.destroyAll = function destroyAll(where, options, cb) { if (options.notify === false) { doDelete(where); } else { - query = { where: whereIsEmpty(where) ? {} : where }; + query = {where: whereIsEmpty(where) ? {} : where}; var context = { Model: Model, query: query, @@ -2268,7 +2268,7 @@ DataAccessObject.count = function(where, options, cb) { var hookState = {}; - var query = { where: where }; + var query = {where: where}; this.applyScope(query); where = query.where; @@ -2284,7 +2284,7 @@ DataAccessObject.count = function(where, options, cb) { var context = { Model: Model, - query: { where: where }, + query: {where: where}, hookState: hookState, options: options, }; @@ -2406,7 +2406,7 @@ DataAccessObject.prototype.save = function(options, cb) { Model.notifyObserversOf('loaded', context, function(err) { if (err) return cb(err); - inst._initProperties(data, { persisted: true }); + inst._initProperties(data, {persisted: true}); var context = { Model: Model, @@ -2517,7 +2517,7 @@ DataAccessObject.updateAll = function(where, data, options, cb) { var hookState = {}; - var query = { where: where }; + var query = {where: where}; this.applyScope(query); this.applyProperties(data); @@ -2525,7 +2525,7 @@ DataAccessObject.updateAll = function(where, data, options, cb) { var context = { Model: Model, - query: { where: where }, + query: {where: where}, hookState: hookState, options: options, }; @@ -2668,7 +2668,7 @@ DataAccessObject.prototype.remove = // A hook modified the query, it is no longer // a simple 'delete model with the given id'. // We must switch to full query-based delete. - Model.deleteAll(where, { notify: false }, function(err, info) { + Model.deleteAll(where, {notify: false}, function(err, info) { if (err) return cb(err, false); var deleted = info && info.count > 0; if (Model.settings.strictDelete && !deleted) { @@ -2834,7 +2834,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 7f4dfb5d..7dbf73a6 100644 --- a/lib/datasource.js +++ b/lib/datasource.js @@ -515,7 +515,7 @@ DataSource.prototype.setupDataAccess = function(modelClass, settings) { modelClass.definition.rawProperties[idName].type = idType; modelClass.definition.properties[idName].type = idType; if (settings.forceId) { - modelClass.validatesAbsenceOf(idName, { if: 'isNewRecord' }); + modelClass.validatesAbsenceOf(idName, {if: 'isNewRecord'}); } } if (this.connector.define) { @@ -648,7 +648,7 @@ DataSource.prototype.mixin = function(ModelCtor) { var DAO = this.DataAccessObject; // mixin DAO - jutil.mixin(ModelCtor, DAO, { proxyFunctions: true, override: true }); + jutil.mixin(ModelCtor, DAO, {proxyFunctions: true, override: true}); // decorate operations as alias functions Object.keys(ops).forEach(function(name) { @@ -1416,7 +1416,7 @@ DataSource.prototype.discoverSchemas = function(modelName, options, cb) { var key = fk.pkOwner + '.' + fk.pkTableName; if (!options.visited.hasOwnProperty(key) && !otherTables.hasOwnProperty(key)) { - otherTables[key] = { owner: fk.pkOwner, tableName: fk.pkTableName }; + otherTables[key] = {owner: fk.pkOwner, tableName: fk.pkTableName}; } }); } @@ -1567,7 +1567,7 @@ DataSource.prototype.discoverSchemasSync = function(modelName, options) { var key = fk.pkOwner + '.' + fk.pkTableName; if (!options.visited.hasOwnProperty(key) && !otherTables.hasOwnProperty(key)) { - otherTables[key] = { owner: fk.pkOwner, tableName: fk.pkTableName }; + otherTables[key] = {owner: fk.pkOwner, tableName: fk.pkTableName}; } }); } @@ -1825,7 +1825,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 16c8e0cd..a90018b8 100644 --- a/lib/geo.js +++ b/lib/geo.js @@ -57,7 +57,7 @@ exports.filter = function(arr, filter) { if (typeof loc.lat !== 'number') return; if (typeof loc.lng !== 'number') return; - var d = GeoPoint.distanceBetween(origin, loc, { type: unit }); + var d = GeoPoint.distanceBetween(origin, loc, {type: unit}); if (max && d > max) { // dont add diff --git a/lib/include.js b/lib/include.js index f814e36f..99277915 100644 --- a/lib/include.js +++ b/lib/include.js @@ -242,7 +242,7 @@ Inclusion.include = function(objects, include, options, cb) { } }); } - utils.mergeQuery(filter, includeScope, { fields: false }); + utils.mergeQuery(filter, includeScope, {fields: false}); } //Let's add a placeholder where query filter.where = filter.where || {}; @@ -639,7 +639,7 @@ Inclusion.include = function(objects, include, options, cb) { * @param callback */ function processPolymorphicType(modelType, callback) { - var typeFilter = { where: {}}; + var typeFilter = {where: {}}; utils.mergeQuery(typeFilter, filter); var targetIds = targetIdsByType[modelType]; typeFilter.where[relation.keyTo] = { @@ -906,7 +906,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/kvao/set.js b/lib/kvao/set.js index 49478267..15bd224b 100644 --- a/lib/kvao/set.js +++ b/lib/kvao/set.js @@ -23,7 +23,7 @@ module.exports = function keyValueSet(key, value, options, callback) { callback = options; options = {}; } else if (typeof options === 'number') { - options = { ttl: options }; + options = {ttl: options}; } else if (!options) { options = {}; } diff --git a/lib/model-builder.js b/lib/model-builder.js index 8033dc41..9e9225e2 100644 --- a/lib/model-builder.js +++ b/lib/model-builder.js @@ -73,7 +73,7 @@ function isModelClass(cls) { ModelBuilder.prototype.getModel = function(name, forceCreate) { var model = this.models[name]; if (!model && forceCreate) { - model = this.define(name, {}, { unresolved: true }); + model = this.define(name, {}, {unresolved: true}); } return model; }; @@ -216,7 +216,7 @@ ModelBuilder.prototype.define = function defineClass(className, properties, sett // Return the unresolved model if (settings.unresolved) { - ModelClass.settings = { unresolved: true }; + ModelClass.settings = {unresolved: true}; return ModelClass; } @@ -229,7 +229,7 @@ ModelBuilder.prototype.define = function defineClass(className, properties, sett // Support both flavors path: 'x' and path: '/x' pathName = '/' + pathName; } - hiddenProperty(ModelClass, 'http', { path: pathName }); + hiddenProperty(ModelClass, 'http', {path: pathName}); hiddenProperty(ModelClass, 'base', ModelBaseClass); hiddenProperty(ModelClass, '_observers', {}); hiddenProperty(ModelClass, '_warned', {}); @@ -291,7 +291,7 @@ ModelBuilder.prototype.define = function defineClass(className, properties, sett // Add the id property if (idInjection) { // Set up the id property - ModelClass.definition.defineProperty('id', { type: Number, id: 1, generated: true }); + ModelClass.definition.defineProperty('id', {type: Number, id: 1, generated: true}); } idNames = modelDefinition.idNames(); // Reload it after rebuild @@ -697,7 +697,7 @@ ModelBuilder.prototype.resolveType = function(type) { return schemaType; } else { // The type cannot be resolved, let's create a place holder - type = this.define(type, {}, { unresolved: true }); + type = this.define(type, {}, {unresolved: true}); return type; } } else if (type.constructor.name === 'Object') { @@ -744,7 +744,7 @@ ModelBuilder.prototype.buildModels = function(schemas, createModel) { { name: this.getSchemaName(), properties: schemas, - options: { anonymous: true }, + options: {anonymous: true}, }, ]; } @@ -771,7 +771,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..216f3c9f 100644 --- a/lib/model-definition.js +++ b/lib/model-definition.js @@ -143,7 +143,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 d6a5ae7c..e7832598 100644 --- a/lib/model.js +++ b/lib/model.js @@ -198,7 +198,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/relation-definition.js b/lib/relation-definition.js index 358e883c..a6862931 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}); } } @@ -1025,7 +1025,7 @@ HasManyThrough.prototype.create = function create(data, options, cb) { var fk2 = keys[1]; function createRelation(to, next) { - var d = {}, q = {}, filter = { where: q }; + var d = {}, q = {}, filter = {where: q}; d[fk1] = q[fk1] = modelInstance[definition.keyFrom]; d[fk2] = q[fk2] = to[pk2]; definition.applyProperties(modelInstance, d); @@ -1090,7 +1090,7 @@ HasManyThrough.prototype.add = function(acInst, data, options, cb) { query[fk1] = this.modelInstance[pk1]; query[fk2] = (acInst instanceof definition.modelTo) ? acInst[pk2] : acInst; - var filter = { where: query }; + var filter = {where: query}; definition.applyScope(this.modelInstance, filter); @@ -1136,7 +1136,7 @@ HasManyThrough.prototype.exists = function(acInst, options, cb) { query[fk1] = this.modelInstance[pk1]; query[fk2] = (acInst instanceof definition.modelTo) ? acInst[pk2] : acInst; - var filter = { where: query }; + var filter = {where: query}; definition.applyScope(this.modelInstance, filter); @@ -1174,7 +1174,7 @@ HasManyThrough.prototype.remove = function(acInst, options, cb) { query[fk1] = this.modelInstance[pk1]; query[fk2] = (acInst instanceof definition.modelTo) ? acInst[pk2] : acInst; - var filter = { where: query }; + var filter = {where: query}; definition.applyScope(this.modelInstance, filter); @@ -1239,12 +1239,12 @@ RelationDefinition.belongsTo = function(modelFrom, modelTo, params) { discriminator = polymorphic.discriminator; if (polymorphic.idType) { // explicit key type - modelFrom.dataSource.defineProperty(modelFrom.modelName, fk, { type: polymorphic.idType, index: true }); + modelFrom.dataSource.defineProperty(modelFrom.modelName, fk, {type: polymorphic.idType, index: true}); } else { // try to use the same foreign key type as modelFrom modelFrom.dataSource.defineForeignKey(modelFrom.modelName, fk, modelFrom.modelName, pkName); } - modelFrom.dataSource.defineProperty(modelFrom.modelName, discriminator, { type: 'string', index: true }); + modelFrom.dataSource.defineProperty(modelFrom.modelName, discriminator, {type: 'string', index: true}); } else { pkName = params.primaryKey || modelTo.dataSource.idName(modelTo.modelName) || 'id'; relationName = params.as || i8n.camelize(modelTo.modelName, true); @@ -1461,7 +1461,7 @@ BelongsTo.prototype.related = function(condOrRefresh, options, cb) { } if (cachedValue === undefined || !(cachedValue instanceof ModelBaseClass)) { - var query = { where: {}}; + var query = {where: {}}; query.where[pk] = modelInstance[fk]; if (query.where[pk] === undefined || query.where[pk] === null) { @@ -1560,7 +1560,7 @@ RelationDefinition.hasAndBelongsToMany = function hasAndBelongsToMany(modelFrom, modelFrom.dataSource.define(name1); } - var options = { as: params.as, through: params.through }; + var options = {as: params.as, through: params.through}; options.properties = params.properties; options.scope = params.scope; // Forward relation options like "disableInclude" @@ -1572,7 +1572,7 @@ RelationDefinition.hasAndBelongsToMany = function hasAndBelongsToMany(modelFrom, var accessor = params.through.prototype[polymorphic.as]; if (typeof accessor !== 'function') { // declare once // use the name of the polymorphic rel, not modelTo - params.through.belongsTo(polymorphic.as, { polymorphic: true }); + params.through.belongsTo(polymorphic.as, {polymorphic: true}); } } else { params.through.belongsTo(modelFrom); @@ -1613,7 +1613,7 @@ RelationDefinition.hasOne = function(modelFrom, modelTo, params) { fk = polymorphic.foreignKey; discriminator = polymorphic.discriminator; if (!params.through) { - modelTo.dataSource.defineProperty(modelTo.modelName, discriminator, { type: 'string', index: true }); + modelTo.dataSource.defineProperty(modelTo.modelName, discriminator, {type: 'string', index: true}); } } @@ -1705,7 +1705,7 @@ HasOne.prototype.create = function(targetModelData, options, cb) { cb = cb || utils.createPromiseCallback(); targetModelData[fk] = modelInstance[pk]; - var query = { where: {}}; + var query = {where: {}}; query.where[fk] = targetModelData[fk]; this.definition.applyScope(modelInstance, query); @@ -1882,7 +1882,7 @@ HasOne.prototype.related = function(condOrRefresh, options, cb) { self.resetCache(newValue); } else if (typeof cb === 'function') { // acts as async getter if (cachedValue === undefined) { - var query = { where: {}}; + var query = {where: {}}; query.where[fk] = modelInstance[pk]; definition.applyScope(modelInstance, query); modelTo.findOne(query, options, function(err, inst) { @@ -1967,7 +1967,7 @@ RelationDefinition.embedsOne = function(modelFrom, modelTo, params) { methods: params.methods, }); - var opts = { type: modelTo }; + var opts = {type: modelTo}; if (params.default === true) { opts.default = function() { return new modelTo(); }; @@ -2394,7 +2394,7 @@ RelationDefinition.embedsMany = function embedsMany(modelFrom, modelTo, params) this.errors.add(propertyName, 'contains duplicate `' + idName + '`', 'uniqueness'); err(false); } - }, { code: 'uniqueness' }); + }, {code: 'uniqueness'}); } // validate all embedded items @@ -2753,7 +2753,7 @@ EmbedsMany.prototype.destroyAll = function(where, options, cb) { var embeddedList = this.embeddedList(); if (where && Object.keys(where).length > 0) { - var filter = applyFilter({ where: where }); + var filter = applyFilter({where: where}); var reject = function(v) { return !filter(v); }; embeddedList = embeddedList ? embeddedList.filter(reject) : embeddedList; } else { @@ -2944,7 +2944,7 @@ EmbedsMany.prototype.add = function(acInst, data, options, cb) { query[fk2] = (acInst instanceof belongsTo.modelTo) ? acInst[pk2] : acInst; - var filter = { where: query }; + var filter = {where: query}; belongsTo.applyScope(modelInstance, filter); @@ -2991,7 +2991,7 @@ EmbedsMany.prototype.remove = function(acInst, options, cb) { query[fk2] = (acInst instanceof belongsTo.modelTo) ? acInst[pk2] : acInst; - var filter = { where: query }; + var filter = {where: query}; belongsTo.applyScope(modelInstance, filter); @@ -3048,7 +3048,7 @@ RelationDefinition.referencesMany = function referencesMany(modelFrom, modelTo, this.errors.add(relationName, msg, 'uniqueness'); err(false); } - }, { code: 'uniqueness' }); + }, {code: 'uniqueness'}); var scopeMethods = { findById: scopeMethod(definition, 'findById'), @@ -3352,7 +3352,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/scope.js b/lib/scope.js index 4279b2c1..e876b365 100644 --- a/lib/scope.js +++ b/lib/scope.js @@ -85,7 +85,7 @@ ScopeDefinition.prototype.related = function(receiver, scopeParams, condOrRefres if (!self.__cachedRelations || self.__cachedRelations[name] === undefined || actualRefresh) { // It either doesn't hit the cache or refresh is required - var params = mergeQuery(actualCond, scopeParams, { nestedInclude: true }); + var params = mergeQuery(actualCond, scopeParams, {nestedInclude: true}); var targetModel = this.targetModel(receiver); targetModel.find(params, options, function(err, data) { if (!err && saveOnCache) { @@ -371,7 +371,7 @@ function defineScope(cls, targetClass, name, params, methods, options) { var targetModel = definition.targetModel(this._receiver); var scoped = (this._scope && this._scope.where) || {}; - var filter = mergeQuery({ where: scoped }, { where: where || {}}); + var filter = mergeQuery({where: scoped}, {where: where || {}}); return targetModel.destroyAll(filter.where, options, cb); } @@ -391,7 +391,7 @@ function defineScope(cls, targetClass, name, params, methods, options) { options = options || {}; var targetModel = definition.targetModel(this._receiver); var scoped = (this._scope && this._scope.where) || {}; - var filter = mergeQuery({ where: scoped }, { where: where || {}}); + var filter = mergeQuery({where: scoped}, {where: where || {}}); return targetModel.updateAll(filter.where, data, options, cb); } @@ -419,7 +419,7 @@ function defineScope(cls, targetClass, name, params, methods, options) { filter = filter || {}; var targetModel = definition.targetModel(this._receiver); var idName = targetModel.definition.idName(); - var query = { where: {}}; + var query = {where: {}}; query.where[idName] = id; query = mergeQuery(query, filter); return this.findOne(query, options, cb); @@ -439,7 +439,7 @@ function defineScope(cls, targetClass, name, params, methods, options) { options = options || {}; var targetModel = definition.targetModel(this._receiver); var scoped = (this._scope && this._scope.where) || {}; - filter = mergeQuery({ where: scoped }, filter || {}); + filter = mergeQuery({where: scoped}, filter || {}); return targetModel.findOne(filter, options, cb); } @@ -457,7 +457,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/utils.js b/lib/utils.js index fe028654..1b5127ce 100644 --- a/lib/utils.js +++ b/lib/utils.js @@ -162,7 +162,7 @@ function mergeQuery(base, update, spec) { if (update.where && Object.keys(update.where).length > 0) { if (base.where && Object.keys(base.where).length > 0) { - base.where = { and: [base.where, update.where] }; + base.where = {and: [base.where, update.where]}; } else { base.where = update.where; } @@ -483,8 +483,8 @@ function createPromiseCallback() { if (!global.Promise) { cb = function() {}; cb.promise = {}; - Object.defineProperty(cb.promise, 'then', { get: throwPromiseNotDefined }); - Object.defineProperty(cb.promise, 'catch', { get: throwPromiseNotDefined }); + Object.defineProperty(cb.promise, 'then', {get: throwPromiseNotDefined}); + Object.defineProperty(cb.promise, 'catch', {get: throwPromiseNotDefined}); return cb; } diff --git a/lib/validations.js b/lib/validations.js index 94246972..69d4a1ce 100644 --- a/lib/validations.js +++ b/lib/validations.js @@ -214,7 +214,7 @@ Validatable.validate = getConfigurator('custom'); * @property {String} message Optional error message if property is not valid. Default error message: " is invalid". * @property {Boolean} allowNull Whether null values are allowed. */ -Validatable.validateAsync = getConfigurator('custom', { async: true }); +Validatable.validateAsync = getConfigurator('custom', {async: true}); /** * Validate uniqueness. Ensure the value for property is unique in the collection of models. @@ -239,7 +239,7 @@ Validatable.validateAsync = getConfigurator('custom', { async: true }); * @property {String} message Optional error message if property is not valid. Default error message: "is not unique". * @property {Boolean} allowNull Whether null values are allowed. */ -Validatable.validatesUniquenessOf = getConfigurator('uniqueness', { async: true }); +Validatable.validatesUniquenessOf = getConfigurator('uniqueness', {async: true}); // implementation of validators @@ -352,7 +352,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/test/async-observer.test.js b/test/async-observer.test.js index 90ed0489..f25ba60c 100644 --- a/test/async-observer.test.js +++ b/test/async-observer.test.js @@ -10,7 +10,7 @@ describe('async observer', function() { var TestModel; beforeEach(function defineTestModel() { var modelBuilder = new ModelBuilder(); - TestModel = modelBuilder.define('TestModel', { name: String }); + TestModel = modelBuilder.define('TestModel', {name: String}); }); it('calls registered async observers', function(done) { @@ -302,7 +302,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 502f527f..2fea7462 100644 --- a/test/basic-querying.test.js +++ b/test/basic-querying.test.js @@ -12,13 +12,13 @@ describe('basic-querying', function() { before(function(done) { db = getSchema(); User = db.define('User', { - seq: { type: Number, index: true }, - name: { type: String, index: true, sort: true }, - email: { type: String, index: true }, - birthday: { type: Date, index: true }, - role: { type: String, index: true }, - order: { type: Number, index: true, sort: true }, - vip: { type: Boolean }, + seq: {type: Number, index: true}, + name: {type: String, index: true, sort: true}, + email: {type: String, index: true}, + birthday: {type: Date, index: true}, + role: {type: String, index: true}, + order: {type: Number, index: true, sort: true}, + vip: {type: Boolean}, }); db.automigrate(done); @@ -64,12 +64,12 @@ describe('basic-querying', function() { var createdUsers; before(function(done) { var people = [ - { name: 'a', vip: true }, - { name: 'b' }, - { name: 'c' }, - { name: 'd', vip: true }, - { name: 'e' }, - { name: 'f' }, + {name: 'a', vip: true}, + {name: 'b'}, + {name: 'c'}, + {name: 'd', vip: true}, + {name: 'e'}, + {name: 'f'}, ]; db.automigrate(['User'], function(err) { User.create(people, function(err, users) { @@ -103,7 +103,7 @@ describe('basic-querying', function() { createdUsers[1].id, createdUsers[2].id, createdUsers[3].id], - { where: { vip: true }}, function(err, users) { + {where: {vip: true}}, function(err, users) { should.exist(users); should.not.exist(err); var names = users.map(function(u) { @@ -141,7 +141,7 @@ describe('basic-querying', function() { }); it('should query limited collection', function(done) { - User.find({ limit: 3 }, function(err, users) { + User.find({limit: 3}, function(err, users) { should.exists(users); should.not.exists(err); users.should.have.lengthOf(3); @@ -150,7 +150,7 @@ describe('basic-querying', function() { }); it('should query collection with skip & limit', function(done) { - User.find({ skip: 1, limit: 4, order: 'seq' }, function(err, users) { + User.find({skip: 1, limit: 4, order: 'seq'}, function(err, users) { should.exists(users); should.not.exists(err); users[0].seq.should.be.eql(1); @@ -160,7 +160,7 @@ describe('basic-querying', function() { }); it('should query collection with offset & limit', function(done) { - User.find({ offset: 2, limit: 3, order: 'seq' }, function(err, users) { + User.find({offset: 2, limit: 3, order: 'seq'}, function(err, users) { should.exists(users); should.not.exists(err); users[0].seq.should.be.eql(2); @@ -170,7 +170,7 @@ describe('basic-querying', function() { }); it('should query filtered collection', function(done) { - User.find({ where: { role: 'lead' }}, function(err, users) { + User.find({where: {role: 'lead'}}, function(err, users) { should.exists(users); should.not.exists(err); users.should.have.lengthOf(2); @@ -179,7 +179,7 @@ describe('basic-querying', function() { }); it('should query collection sorted by numeric field', function(done) { - User.find({ order: 'order' }, function(err, users) { + User.find({order: 'order'}, function(err, users) { should.exists(users); should.not.exists(err); users.forEach(function(u, i) { @@ -190,7 +190,7 @@ describe('basic-querying', function() { }); it('should query collection desc sorted by numeric field', function(done) { - User.find({ order: 'order DESC' }, function(err, users) { + User.find({order: 'order DESC'}, function(err, users) { should.exists(users); should.not.exists(err); users.forEach(function(u, i) { @@ -201,7 +201,7 @@ describe('basic-querying', function() { }); it('should query collection sorted by string field', function(done) { - User.find({ order: 'name' }, function(err, users) { + User.find({order: 'name'}, function(err, users) { should.exists(users); should.not.exists(err); users.shift().name.should.equal('George Harrison'); @@ -212,7 +212,7 @@ describe('basic-querying', function() { }); it('should query collection desc sorted by string field', function(done) { - User.find({ order: 'name DESC' }, function(err, users) { + User.find({order: 'name DESC'}, function(err, users) { should.exists(users); should.not.exists(err); users.pop().name.should.equal('George Harrison'); @@ -224,7 +224,7 @@ describe('basic-querying', function() { it('should query sorted desc by order integer field even though there' + 'is an async model loaded hook', function(done) { - User.find({ order: 'order DESC' }, function(err, users) { + User.find({order: 'order DESC'}, function(err, users) { if (err) return done(err); should.exists(users); @@ -235,10 +235,10 @@ describe('basic-querying', function() { }); it('should support "and" operator that is satisfied', function(done) { - User.find({ where: { and: [ - { name: 'John Lennon' }, - { role: 'lead' }, - ] }}, function(err, users) { + User.find({where: {and: [ + {name: 'John Lennon'}, + {role: 'lead'}, + ]}}, function(err, users) { should.not.exist(err); users.should.have.property('length', 1); done(); @@ -246,10 +246,10 @@ describe('basic-querying', function() { }); it('should support "and" operator that is not satisfied', function(done) { - User.find({ where: { and: [ - { name: 'John Lennon' }, - { role: 'member' }, - ] }}, function(err, users) { + User.find({where: {and: [ + {name: 'John Lennon'}, + {role: 'member'}, + ]}}, function(err, users) { should.not.exist(err); users.should.have.property('length', 0); done(); @@ -257,10 +257,10 @@ describe('basic-querying', function() { }); it('should support "or" that is satisfied', function(done) { - User.find({ where: { or: [ - { name: 'John Lennon' }, - { role: 'lead' }, - ] }}, function(err, users) { + User.find({where: {or: [ + {name: 'John Lennon'}, + {role: 'lead'}, + ]}}, function(err, users) { should.not.exist(err); users.should.have.property('length', 2); done(); @@ -268,10 +268,10 @@ describe('basic-querying', function() { }); it('should support "or" operator that is not satisfied', function(done) { - User.find({ where: { or: [ - { name: 'XYZ' }, - { role: 'Hello1' }, - ] }}, function(err, users) { + User.find({where: {or: [ + {name: 'XYZ'}, + {role: 'Hello1'}, + ]}}, function(err, users) { should.not.exist(err); users.should.have.property('length', 0); done(); @@ -279,7 +279,7 @@ describe('basic-querying', function() { }); it('should support date "gte" that is satisfied', function(done) { - User.find({ order: 'seq', where: { birthday: { 'gte': new Date('1980-12-08') }, + User.find({order: 'seq', where: {birthday: {'gte': new Date('1980-12-08')}, }}, function(err, users) { should.not.exist(err); users.should.have.property('length', 1); @@ -289,7 +289,7 @@ describe('basic-querying', function() { }); it('should support date "gt" that is not satisfied', function(done) { - User.find({ order: 'seq', where: { birthday: { 'gt': new Date('1980-12-08') }, + User.find({order: 'seq', where: {birthday: {'gt': new Date('1980-12-08')}, }}, function(err, users) { should.not.exist(err); users.should.have.property('length', 0); @@ -298,7 +298,7 @@ describe('basic-querying', function() { }); it('should support date "gt" that is satisfied', function(done) { - User.find({ order: 'seq', where: { birthday: { 'gt': new Date('1980-12-07') }, + User.find({order: 'seq', where: {birthday: {'gt': new Date('1980-12-07')}, }}, function(err, users) { should.not.exist(err); users.should.have.property('length', 1); @@ -308,7 +308,7 @@ describe('basic-querying', function() { }); it('should support date "lt" that is satisfied', function(done) { - User.find({ order: 'seq', where: { birthday: { 'lt': new Date('1980-12-07') }, + User.find({order: 'seq', where: {birthday: {'lt': new Date('1980-12-07')}, }}, function(err, users) { should.not.exist(err); users.should.have.property('length', 1); @@ -318,7 +318,7 @@ describe('basic-querying', function() { }); it('should support number "gte" that is satisfied', function(done) { - User.find({ order: 'seq', where: { order: { 'gte': 3 }, + User.find({order: 'seq', where: {order: {'gte': 3}, }}, function(err, users) { should.not.exist(err); users.should.have.property('length', 4); @@ -328,7 +328,7 @@ describe('basic-querying', function() { }); it('should support number "gt" that is not satisfied', function(done) { - User.find({ order: 'seq', where: { order: { 'gt': 6 }, + User.find({order: 'seq', where: {order: {'gt': 6}, }}, function(err, users) { should.not.exist(err); users.should.have.property('length', 0); @@ -337,7 +337,7 @@ describe('basic-querying', function() { }); it('should support number "gt" that is satisfied', function(done) { - User.find({ order: 'seq', where: { order: { 'gt': 5 }, + User.find({order: 'seq', where: {order: {'gt': 5}, }}, function(err, users) { should.not.exist(err); users.should.have.property('length', 1); @@ -347,7 +347,7 @@ describe('basic-querying', function() { }); it('should support number "lt" that is satisfied', function(done) { - User.find({ order: 'seq', where: { order: { 'lt': 2 }, + User.find({order: 'seq', where: {order: {'lt': 2}, }}, function(err, users) { should.not.exist(err); users.should.have.property('length', 1); @@ -357,7 +357,7 @@ describe('basic-querying', function() { }); it('should support number "gt" that is satisfied by null value', function(done) { - User.find({ order: 'seq', where: { order: { 'gt': null }, + User.find({order: 'seq', where: {order: {'gt': null}, }}, function(err, users) { should.not.exist(err); users.should.have.property('length', 0); @@ -366,7 +366,7 @@ describe('basic-querying', function() { }); it('should support number "lt" that is not satisfied by null value', function(done) { - User.find({ order: 'seq', where: { order: { 'lt': null }, + User.find({order: 'seq', where: {order: {'lt': null}, }}, function(err, users) { should.not.exist(err); users.should.have.property('length', 0); @@ -375,7 +375,7 @@ describe('basic-querying', function() { }); it('should support string "gte" that is satisfied by null value', function(done) { - User.find({ order: 'seq', where: { name: { 'gte': null }, + User.find({order: 'seq', where: {name: {'gte': null}, }}, function(err, users) { should.not.exist(err); users.should.have.property('length', 0); @@ -384,7 +384,7 @@ describe('basic-querying', function() { }); it('should support string "gte" that is satisfied', function(done) { - User.find({ order: 'seq', where: { name: { 'gte': 'Paul McCartney' }, + User.find({order: 'seq', where: {name: {'gte': 'Paul McCartney'}, }}, function(err, users) { should.not.exist(err); users.should.have.property('length', 4); @@ -394,7 +394,7 @@ describe('basic-querying', function() { }); it('should support string "gt" that is not satisfied', function(done) { - User.find({ order: 'seq', where: { name: { 'gt': 'xyz' }, + User.find({order: 'seq', where: {name: {'gt': 'xyz'}, }}, function(err, users) { should.not.exist(err); users.should.have.property('length', 0); @@ -403,7 +403,7 @@ describe('basic-querying', function() { }); it('should support string "gt" that is satisfied', function(done) { - User.find({ order: 'seq', where: { name: { 'gt': 'Paul McCartney' }, + User.find({order: 'seq', where: {name: {'gt': 'Paul McCartney'}, }}, function(err, users) { should.not.exist(err); users.should.have.property('length', 3); @@ -413,7 +413,7 @@ describe('basic-querying', function() { }); it('should support string "lt" that is satisfied', function(done) { - User.find({ order: 'seq', where: { name: { 'lt': 'Paul McCartney' }, + User.find({order: 'seq', where: {name: {'lt': 'Paul McCartney'}, }}, function(err, users) { should.not.exist(err); users.should.have.property('length', 2); @@ -423,7 +423,7 @@ describe('basic-querying', function() { }); it('should support boolean "gte" that is satisfied', function(done) { - User.find({ order: 'seq', where: { vip: { 'gte': true }, + User.find({order: 'seq', where: {vip: {'gte': true}, }}, function(err, users) { should.not.exist(err); users.should.have.property('length', 3); @@ -433,7 +433,7 @@ describe('basic-querying', function() { }); it('should support boolean "gt" that is not satisfied', function(done) { - User.find({ order: 'seq', where: { vip: { 'gt': true }, + User.find({order: 'seq', where: {vip: {'gt': true}, }}, function(err, users) { should.not.exist(err); users.should.have.property('length', 0); @@ -442,7 +442,7 @@ describe('basic-querying', function() { }); it('should support boolean "gt" that is satisfied', function(done) { - User.find({ order: 'seq', where: { vip: { 'gt': false }, + User.find({order: 'seq', where: {vip: {'gt': false}, }}, function(err, users) { should.not.exist(err); users.should.have.property('length', 3); @@ -452,7 +452,7 @@ describe('basic-querying', function() { }); it('should support boolean "lt" that is satisfied', function(done) { - User.find({ order: 'seq', where: { vip: { 'lt': true }, + User.find({order: 'seq', where: {vip: {'lt': true}, }}, function(err, users) { should.not.exist(err); users.should.have.property('length', 2); @@ -464,7 +464,7 @@ describe('basic-querying', function() { var itWhenIlikeSupported = connectorCapabilities.ilike ? it : it.skip.bind(it); itWhenIlikeSupported('should support "like" that is satisfied', function(done) { - User.find({ where: { name: { like: 'John' }}}, function(err, users) { + User.find({where: {name: {like: 'John'}}}, function(err, users) { if (err) return done(err); users.length.should.equal(1); users[0].name.should.equal('John Lennon'); @@ -473,7 +473,7 @@ describe('basic-querying', function() { }); itWhenIlikeSupported('should support "like" that is not satisfied', function(done) { - User.find({ where: { name: { like: 'Bob' }}}, function(err, users) { + User.find({where: {name: {like: 'Bob'}}}, function(err, users) { if (err) return done(err); users.length.should.equal(0); done(); @@ -483,7 +483,7 @@ describe('basic-querying', function() { var itWhenNilikeSupported = connectorCapabilities.nilike ? it : it.skip.bind(it); itWhenNilikeSupported('should support "nlike" that is satisfied', function(done) { - User.find({ where: { name: { nlike: 'John' }}}, function(err, users) { + User.find({where: {name: {nlike: 'John'}}}, function(err, users) { if (err) return done(err); users.length.should.equal(5); users[0].name.should.equal('Paul McCartney'); @@ -492,7 +492,7 @@ describe('basic-querying', function() { }); itWhenIlikeSupported('should support "ilike" that is satisfied', function(done) { - User.find({ where: { name: { ilike: 'john' }}}, function(err, users) { + User.find({where: {name: {ilike: 'john'}}}, function(err, users) { if (err) return done(err); users.length.should.equal(1); users[0].name.should.equal('John Lennon'); @@ -501,7 +501,7 @@ describe('basic-querying', function() { }); itWhenIlikeSupported('should support "ilike" that is not satisfied', function(done) { - User.find({ where: { name: { ilike: 'bob' }}}, function(err, users) { + User.find({where: {name: {ilike: 'bob'}}}, function(err, users) { if (err) return done(err); users.length.should.equal(0); done(); @@ -509,7 +509,7 @@ describe('basic-querying', function() { }); itWhenNilikeSupported('should support "nilike" that is satisfied', function(done) { - User.find({ where: { name: { nilike: 'john' }}}, function(err, users) { + User.find({where: {name: {nilike: 'john'}}}, function(err, users) { if (err) return done(err); users.length.should.equal(5); users[0].name.should.equal('Paul McCartney'); @@ -524,7 +524,7 @@ describe('basic-querying', function() { return { expect: function(arr) { remaining++; - User.find({ fields: fields }, function(err, users) { + User.find({fields: fields}, function(err, users) { remaining--; if (err) return done(err); @@ -553,10 +553,10 @@ describe('basic-querying', function() { }; } - sample({ name: true }).expect(['name']); - sample({ name: false }).expect(['id', 'seq', 'email', 'role', 'order', 'birthday', 'vip']); - sample({ name: false, id: true }).expect(['id']); - sample({ id: true }).expect(['id']); + sample({name: true}).expect(['name']); + sample({name: false}).expect(['id', 'seq', 'email', 'role', 'order', 'birthday', 'vip']); + sample({name: false, id: true}).expect(['id']); + sample({id: true}).expect(['id']); sample('id').expect(['id']); sample(['id']).expect(['id']); sample(['email']).expect(['email']); @@ -576,7 +576,7 @@ describe('basic-querying', function() { }); it('should query filtered count', function(done) { - User.count({ role: 'lead' }, function(err, n) { + User.count({role: 'lead'}, function(err, n) { should.not.exist(err); should.exist(n); n.should.equal(2); @@ -589,7 +589,7 @@ describe('basic-querying', function() { before(seed); it('should find first record (default sort by id)', function(done) { - User.all({ order: 'id' }, function(err, users) { + User.all({order: 'id'}, function(err, users) { User.findOne(function(e, u) { should.not.exist(e); should.exist(u); @@ -600,7 +600,7 @@ describe('basic-querying', function() { }); it('should find first record', function(done) { - User.findOne({ order: 'order' }, function(e, u) { + User.findOne({order: 'order'}, function(e, u) { should.not.exist(e); should.exist(u); u.order.should.equal(1); @@ -610,7 +610,7 @@ describe('basic-querying', function() { }); it('should find last record', function(done) { - User.findOne({ order: 'order DESC' }, function(e, u) { + User.findOne({order: 'order DESC'}, function(e, u) { should.not.exist(e); should.exist(u); u.order.should.equal(6); @@ -621,7 +621,7 @@ describe('basic-querying', function() { it('should find last record in filtered set', function(done) { User.findOne({ - where: { role: 'lead' }, + where: {role: 'lead'}, order: 'order DESC', }, function(e, u) { should.not.exist(e); @@ -634,7 +634,7 @@ describe('basic-querying', function() { it('should work even when find by id', function(done) { User.findOne(function(e, u) { - User.findOne({ where: { id: u.id }}, function(err, user) { + User.findOne({where: {id: u.id}}, function(err, user) { should.not.exist(err); should.exist(user); done(); @@ -677,7 +677,7 @@ describe('basic-querying', function() { // `undefined` is not tested because the `removeUndefined` function // in `lib/dao.js` removes it before coercion invalidDataTypes.forEach(function(invalidDataType) { - User.find({ where: { name: { regexp: invalidDataType }}}, function(err, + User.find({where: {name: {regexp: invalidDataType}}}, function(err, users) { should.exist(err); }); @@ -694,7 +694,7 @@ describe.skip('queries', function() { var db = getSchema(); Todo = db.define('Todo', { id: false, - content: { type: 'string' }, + content: {type: 'string'}, }, { idInjection: false, }); @@ -703,16 +703,16 @@ describe.skip('queries', function() { beforeEach(function resetFixtures(done) { Todo.destroyAll(function() { Todo.create([ - { content: 'Buy eggs' }, - { content: 'Buy milk' }, - { content: 'Buy sausages' }, + {content: 'Buy eggs'}, + {content: 'Buy milk'}, + {content: 'Buy sausages'}, ], done); }); }); context('that do not require an id', function() { it('should work for create', function(done) { - Todo.create({ content: 'Buy ham' }, function(err) { + Todo.create({content: 'Buy ham'}, function(err) { should.not.exist(err); done(); }); @@ -721,7 +721,7 @@ describe.skip('queries', function() { it('should work for updateOrCreate/upsert', function(done) { var aliases = ['updateOrCreate', 'upsert']; async.each(aliases, function(alias, cb) { - Todo[alias]({ content: 'Buy ham' }, function(err) { + Todo[alias]({content: 'Buy ham'}, function(err) { should.not.exist(err); cb(); }); @@ -729,14 +729,14 @@ describe.skip('queries', function() { }); it('should work for findOrCreate', function(done) { - Todo.findOrCreate({ content: 'Buy ham' }, function(err) { + Todo.findOrCreate({content: 'Buy ham'}, function(err) { should.not.exist(err); done(); }); }); it('should work for exists', function(done) { - Todo.exists({ content: 'Buy ham' }, function(err) { + Todo.exists({content: 'Buy ham'}, function(err) { should.not.exist(err); done(); }); @@ -769,14 +769,14 @@ describe.skip('queries', function() { }); it('should work for update/updateAll', function(done) { - Todo.update({ content: 'Buy ham' }, function(err) { + Todo.update({content: 'Buy ham'}, function(err) { should.not.exist(err); done(); }); }); it('should work for count', function(done) { - Todo.count({ content: 'Buy eggs' }, function(err) { + Todo.count({content: 'Buy eggs'}, function(err) { should.not.exist(err); done(); }); @@ -846,7 +846,7 @@ describe.skip('queries', function() { it('should return an error for instance.updateAttributes', function(done) { Todo.findOne(function(err, todo) { - todo.updateAttributes({ content: 'Buy ham' }, function(err) { + todo.updateAttributes({content: 'Buy ham'}, function(err) { should.exist(err); err.message.should.equal(expectedErrMsg); done(); @@ -876,10 +876,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_test.js b/test/common_test.js index 0bea082c..75b226a4 100644 --- a/test/common_test.js +++ b/test/common_test.js @@ -95,45 +95,45 @@ function testOrm(dataSource) { it('should define class', function(test) { User = dataSource.define('User', { - name: { type: String, index: true }, - email: { type: String, index: true }, + name: {type: String, index: true}, + email: {type: String, index: true}, bio: Text, approved: Boolean, joinedAt: Date, age: Number, - passwd: { type: String, index: true }, + passwd: {type: String, index: true}, }); Dog = dataSource.define('Dog', { - name: { type: String, limit: 64, allowNull: false }, + name: {type: String, limit: 64, allowNull: false}, }); Log = dataSource.define('Log', { - ownerId: { type: Number, allowNull: true }, - name: { type: String, limit: 64, allowNull: false }, + ownerId: {type: Number, allowNull: true}, + name: {type: String, limit: 64, allowNull: false}, }); - Log.belongsTo(Dog, { as: 'owner', foreignKey: 'ownerId' }); + Log.belongsTo(Dog, {as: 'owner', foreignKey: 'ownerId'}); dataSource.extendModel('User', { - settings: { type: Schema.JSON }, + settings: {type: Schema.JSON}, extra: Object, }); - var newuser = new User({ settings: { hey: 'you' }}); + var newuser = new User({settings: {hey: 'you'}}); test.ok(newuser.settings); Post = dataSource.define('Post', { - title: { type: String, length: 255, index: true }, - subject: { type: String }, - content: { type: Text }, - date: { type: Date, default: function() { + title: {type: String, length: 255, index: true}, + subject: {type: String}, + content: {type: Text}, + date: {type: Date, default: function() { return new Date; - }, index: true }, - published: { type: Boolean, default: false, index: true }, + }, index: true}, + published: {type: Boolean, default: false, index: true}, likes: [], related: [RelatedPost], - }, { table: 'posts' }); + }, {table: 'posts'}); function RelatedPost() { } @@ -146,7 +146,7 @@ function testOrm(dataSource) { process.nextTick(done); }); - User.hasMany(Post, { as: 'posts', foreignKey: 'userId' }); + User.hasMany(Post, {as: 'posts', foreignKey: 'userId'}); // creates instance methods: // user.posts(conds) // user.posts.build(data) // like new Post({userId: user.id}); @@ -161,7 +161,7 @@ function testOrm(dataSource) { // user.latestPost.build(data) // user.latestPost.create(data) - Post.belongsTo(User, { as: 'author', foreignKey: 'userId' }); + Post.belongsTo(User, {as: 'author', foreignKey: 'userId'}); // creates instance methods: // post.author(callback) -- getter when called with function // post.author() -- sync getter when called without params @@ -171,8 +171,8 @@ function testOrm(dataSource) { number: String, }); - Passport.belongsTo(User, { as: 'owner', foreignKey: 'ownerId' }); - User.hasMany(Passport, { as: 'passports', foreignKey: 'ownerId' }); + Passport.belongsTo(User, {as: 'owner', foreignKey: 'ownerId'}); + User.hasMany(Passport, {as: 'passports', foreignKey: 'ownerId'}); var user = new User; @@ -198,8 +198,8 @@ function testOrm(dataSource) { it('should initialize object properly', function(test) { var hw = 'Hello word', now = Date.now(), - post = new Post({ title: hw }), - anotherPost = Post({ title: 'Resig style constructor' }); + post = new Post({title: hw}), + anotherPost = Post({title: 'Resig style constructor'}); test.equal(post.title, hw); test.ok(!post.propertyChanged('title'), 'property changed: title'); @@ -231,7 +231,7 @@ function testOrm(dataSource) { test.equal(obj.title, title2); test.ok(!obj.propertyChanged('title')); - var p = new Post({ title: 1 }); + var p = new Post({title: 1}); p.title = 2; p.save(function(err, obj) { test.ok(!p.propertyChanged('title')); @@ -268,7 +268,7 @@ function testOrm(dataSource) { }); it('should save only dataSource-defined field in database', function(test) { - Post.create({ title: '1602', nonSchemaField: 'some value' }, function(err, post) { + Post.create({title: '1602', nonSchemaField: 'some value'}, function(err, post) { test.ok(!post.nonSchemaField); post.a = 1; post.save(function() { @@ -299,7 +299,7 @@ function testOrm(dataSource) { it('should not re-instantiate object on saving', function(test) { var title = 'Initial title'; - var post = new Post({ title: title }); + var post = new Post({title: title}); post.save(function(err, savedPost) { test.strictEqual(post, savedPost); test.done(); @@ -359,7 +359,7 @@ function testOrm(dataSource) { // }); it('should update single attribute', function(test) { - Post.create({ title: 'title', content: 'content', published: true }, function(err, post) { + Post.create({title: 'title', content: 'content', published: true}, function(err, post) { post.content = 'New content'; post.updateAttribute('title', 'New title', function() { test.equal(post.title, 'New title'); @@ -392,8 +392,8 @@ function testOrm(dataSource) { it('should find records filtered with multiple attributes', function(test) { var d = new Date; - Post.create({ title: 'title', content: 'content', published: true, date: d }, function(err, post) { - Post.all({ where: { title: 'title', date: d, published: true }}, function(err, res) { + Post.create({title: 'title', content: 'content', published: true, date: d}, function(err, post) { + Post.all({where: {title: 'title', date: d, published: true}}, function(err, res) { test.equals(res.length, 1, 'Filtering Posts returns one post'); test.done(); }); @@ -440,9 +440,9 @@ function testOrm(dataSource) { }); it('should navigate variations of belongsTo regardless of column name', function(test) { - Dog.create({ name: 'theDog' }, function(err, obj) { + Dog.create({name: 'theDog'}, function(err, obj) { test.ok(obj instanceof Dog); - Log.create({ name: 'theLog', ownerId: obj.id }, function(err, obj) { + Log.create({name: 'theLog', ownerId: obj.id}, function(err, obj) { test.ok(obj instanceof Log); obj.owner(function(err, obj) { test.ok(!err, 'Should not have an error.'); // Before cba174b this would be 'Error: Permission denied' @@ -466,7 +466,7 @@ function testOrm(dataSource) { it('hasMany should support additional conditions', function(test) { User.create(function(e, u) { u.posts.create({}, function(e, p) { - u.posts({ where: { id: p.id }}, function(e, posts) { + u.posts({where: {id: p.id}}, function(e, posts) { test.equal(posts.length, 1, 'There should be only 1 post.'); test.done(); }); @@ -550,7 +550,7 @@ function testOrm(dataSource) { var wait = 2; test.ok(Post.scope, 'Scope supported'); - Post.scope('published', { where: { published: true }}); + Post.scope('published', {where: {published: true}}); test.ok(typeof Post.published === 'function'); test.ok(Post.published._scope.where.published === true); var post = Post.published.build(); @@ -588,12 +588,12 @@ function testOrm(dataSource) { it('should handle ORDER clause', function(test) { var titles = [ - { title: 'Title A', subject: 'B' }, - { title: 'Title Z', subject: 'A' }, - { title: 'Title M', subject: 'C' }, - { title: 'Title A', subject: 'A' }, - { title: 'Title B', subject: 'A' }, - { title: 'Title C', subject: 'D' }, + {title: 'Title A', subject: 'B'}, + {title: 'Title Z', subject: 'A'}, + {title: 'Title M', subject: 'C'}, + {title: 'Title A', subject: 'A'}, + {title: 'Title B', subject: 'A'}, + {title: 'Title C', subject: 'D'}, ]; var isRedis = Post.dataSource.name === 'redis'; var dates = isRedis ? [5, 9, 0, 17, 10, 9] : [ @@ -605,7 +605,7 @@ function testOrm(dataSource) { new Date(1000 * 9), ]; titles.forEach(function(t, i) { - Post.create({ title: t.title, subject: t.subject, date: dates[i] }, done); + Post.create({title: t.title, subject: t.subject, date: dates[i]}, done); }); var i = 0, tests = 0; @@ -634,7 +634,7 @@ function testOrm(dataSource) { function doStringTest() { tests += 1; - Post.all({ order: 'title' }, function(err, posts) { + Post.all({order: 'title'}, function(err, posts) { if (err) console.log(err); test.equal(posts.length, 6); titles.sort(compare).forEach(function(t, i) { @@ -646,7 +646,7 @@ function testOrm(dataSource) { function doNumberTest() { tests += 1; - Post.all({ order: 'date' }, function(err, posts) { + Post.all({order: 'date'}, function(err, posts) { if (err) console.log(err); test.equal(posts.length, 6); dates.sort(numerically).forEach(function(d, i) { @@ -659,7 +659,7 @@ function testOrm(dataSource) { function doFilterAndSortTest() { tests += 1; - Post.all({ where: { date: new Date(1000 * 9) }, order: 'title', limit: 3 }, function(err, posts) { + Post.all({where: {date: new Date(1000 * 9)}, order: 'title', limit: 3}, function(err, posts) { if (err) console.log(err); console.log(posts.length); test.equal(posts.length, 2, 'Exactly 2 posts returned by query'); @@ -674,7 +674,7 @@ function testOrm(dataSource) { function doFilterAndSortReverseTest() { tests += 1; - Post.all({ where: { date: new Date(1000 * 9) }, order: 'title DESC', limit: 3 }, function(err, posts) { + Post.all({where: {date: new Date(1000 * 9)}, order: 'title DESC', limit: 3}, function(err, posts) { if (err) console.log(err); test.equal(posts.length, 2, 'Exactly 2 posts returned by query'); ['Title Z', 'Title C'].forEach(function(t, i) { @@ -688,7 +688,7 @@ function testOrm(dataSource) { function doMultipleSortTest() { tests += 1; - Post.all({ order: 'title ASC, subject ASC' }, function(err, posts) { + Post.all({order: 'title ASC, subject ASC'}, function(err, posts) { if (err) console.log(err); test.equal(posts.length, 6); test.equal(posts[0].title, 'Title A'); @@ -702,7 +702,7 @@ function testOrm(dataSource) { function doMultipleReverseSortTest() { tests += 1; - Post.all({ order: 'title ASC, subject DESC' }, function(err, posts) { + Post.all({order: 'title ASC, subject DESC'}, function(err, posts) { if (err) console.log(err); test.equal(posts.length, 6); test.equal(posts[0].title, 'Title A'); @@ -881,7 +881,7 @@ function testOrm(dataSource) { User.destroyAll(function() { emails.forEach(function(email) { wait += 1; - User.create({ email: email, name: 'Nick' }, done); + User.create({email: email, name: 'Nick'}, done); }); }); var tests = 2; @@ -896,7 +896,7 @@ function testOrm(dataSource) { } function doSortTest() { - User.all({ order: 'email ASC', where: { name: 'Nick' }}, function(err, users) { + User.all({order: 'email ASC', where: {name: 'Nick'}}, function(err, users) { var _emails = emails.sort(); users.forEach(function(user, i) { test.equal(_emails[i], user.email, 'ASC sorting'); @@ -906,7 +906,7 @@ function testOrm(dataSource) { } function doReverseSortTest() { - User.all({ order: 'email DESC', where: { name: 'Nick' }}, function(err, users) { + User.all({order: 'email DESC', where: {name: 'Nick'}}, function(err, users) { var _emails = emails.sort().reverse(); users.forEach(function(user, i) { test.equal(_emails[i], user.email, 'DESC sorting'); @@ -924,7 +924,7 @@ function testOrm(dataSource) { Post.create(function(err, post) { var id = post.id; test.ok(post.published === false); - post.updateAttributes({ title: 'hey', published: true }, function() { + post.updateAttributes({title: 'hey', published: true}, function() { Post.find(id, function(err, post) { test.ok(!!post.published, 'Update boolean field'); test.ok(post.id); @@ -935,7 +935,7 @@ function testOrm(dataSource) { }); it('should handle belongsTo correctly', function(test) { - var passport = new Passport({ ownerId: 16 }); + var passport = new Passport({ownerId: 16}); // sync getter test.equal(passport.owner(), 16); // sync setter @@ -948,14 +948,14 @@ function testOrm(dataSource) { test.expect(4); Post.findOne(function(err, post) { test.ok(post && post.id); - Post.findOne({ where: { title: 'hey' }}, function(err, post) { + Post.findOne({where: {title: 'hey'}}, function(err, post) { if (err) { console.log(err); return test.done(); } test.equal(post && post.constructor.modelName, 'Post'); test.equal(post && post.title, 'hey'); - Post.findOne({ where: { title: 'not exists' }}, function(err, post) { + Post.findOne({where: {title: 'not exists'}}, function(err, post) { test.ok(post === null); test.done(); }); @@ -1038,7 +1038,7 @@ function testOrm(dataSource) { } test.equal(newData.title, post.toObject().title); test.equal(newData.content, post.toObject().content); - Post.updateOrCreate({ id: 100001, title: 'hey' }, function(err, post) { + Post.updateOrCreate({id: 100001, title: 'hey'}, function(err, post) { if (dataSource.name !== 'mongodb') test.equal(post.id, 100001); test.equal(post.title, 'hey'); Post.findById(post.id, function(err, post) { @@ -1055,18 +1055,18 @@ function testOrm(dataSource) { User.setter.passwd = function(pass) { this._passwd = pass + 'salt'; }; - var u = new User({ passwd: 'qwerty' }); + var u = new User({passwd: 'qwerty'}); test.equal(u.passwd, 'qwertysalt'); u.save(function(err, user) { User.findById(user.id, function(err, user) { test.ok(user !== u); test.equal(user.passwd, 'qwertysalt'); - User.all({ where: { passwd: 'qwertysalt' }}, function(err, users) { + User.all({where: {passwd: 'qwertysalt'}}, function(err, users) { test.ok(users[0] !== user); test.equal(users[0].passwd, 'qwertysalt'); - User.create({ passwd: 'asalat' }, function(err, usr) { + User.create({passwd: 'asalat'}, function(err, usr) { test.equal(usr.passwd, 'asalatsalt'); - User.upsert({ passwd: 'heyman' }, function(err, us) { + User.upsert({passwd: 'heyman'}, function(err, us) { test.equal(us.passwd, 'heymansalt'); User.findById(us.id, function(err, user) { test.equal(user.passwd, 'heymansalt'); @@ -1081,14 +1081,14 @@ function testOrm(dataSource) { it('should work with typed and untyped nested collections', function(test) { var post = new Post; - var like = post.likes.push({ foo: 'bar' }); + var like = post.likes.push({foo: 'bar'}); test.equal(like.constructor.name, 'ListItem'); - var related = post.related.push({ hello: 'world' }); + var related = post.related.push({hello: 'world'}); test.ok(related.someMethod); post.save(function(err, p) { test.equal(p.likes.nextid, 2); - p.likes.push({ second: 2 }); - p.likes.push({ third: 3 }); + p.likes.push({second: 2}); + p.likes.push({third: 3}); p.save(function(err) { Post.findById(p.id, function(err, pp) { test.equal(pp.likes.length, 3); @@ -1117,11 +1117,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 ba69dd09..be862584 100644 --- a/test/crud-with-options.test.js +++ b/test/crud-with-options.test.js @@ -12,16 +12,16 @@ describe('crud-with-options', function() { before(function(done) { db = getSchema(); User = db.define('User', { - seq: { type: Number, index: true }, - name: { type: String, index: true, sort: true }, - email: { type: String, index: true }, - birthday: { type: Date, index: true }, - role: { type: String, index: true }, - order: { type: Number, index: true, sort: true }, - vip: { type: Boolean }, + seq: {type: Number, index: true}, + name: {type: String, index: true, sort: true}, + email: {type: String, index: true}, + birthday: {type: Date, index: true}, + role: {type: String, index: true}, + order: {type: Number, index: true, sort: true}, + vip: {type: Boolean}, }); options = {}; - filter = { fields: ['name', 'id'] }; + filter = {fields: ['name', 'id']}; db.automigrate(['User'], done); }); @@ -92,7 +92,7 @@ describe('crud-with-options', function() { it('should allow findById(id, filter, cb) for a matching id', function(done) { - User.create({ name: 'x', email: 'x@y.com' }, function(err, u) { + User.create({name: 'x', email: 'x@y.com'}, function(err, u) { should.not.exist(err); should.exist(u.id); User.findById(u.id, filter, function(err, u) { @@ -108,7 +108,7 @@ describe('crud-with-options', function() { it('should allow findById(id, options, cb) for a matching id', function(done) { - User.create({ name: 'y', email: 'y@y.com' }, function(err, u) { + User.create({name: 'y', email: 'y@y.com'}, function(err, u) { should.not.exist(err); should.exist(u.id); User.findById(u.id, options, function(err, u) { @@ -124,7 +124,7 @@ describe('crud-with-options', function() { it('should allow findById(id, filter, options, cb) for a matching id', function(done) { - User.create({ name: 'z', email: 'z@y.com' }, function(err, u) { + User.create({name: 'z', email: 'z@y.com'}, function(err, u) { should.not.exist(err); should.exist(u.id); User.findById(u.id, filter, options, function(err, u) { @@ -140,7 +140,7 @@ describe('crud-with-options', function() { it('should allow promise-style findById', function(done) { - User.create({ name: 'w', email: 'w@y.com' }).then(function(u) { + User.create({name: 'w', email: 'w@y.com'}).then(function(u) { should.exist(u.id); return User.findById(u.id).then(function(u) { should.exist(u); @@ -188,12 +188,12 @@ describe('crud-with-options', function() { describe('findByIds', function() { before(function(done) { var people = [ - { id: 1, name: 'a', vip: true }, - { id: 2, name: 'b' }, - { id: 3, name: 'c' }, - { id: 4, name: 'd', vip: true }, - { id: 5, name: 'e' }, - { id: 6, name: 'f' }, + {id: 1, name: 'a', vip: true}, + {id: 2, name: 'b'}, + {id: 3, name: 'c'}, + {id: 4, name: 'd', vip: true}, + {id: 5, name: 'e'}, + {id: 6, name: 'f'}, ]; // Use automigrate so that serial keys are 1-6 db.automigrate(['User'], function(err) { @@ -216,7 +216,7 @@ describe('crud-with-options', function() { it('should allow findByIds(ids, filter, options, cb)', function(done) { User.findByIds([4, 3, 2, 1], - { where: { vip: true }}, options, function(err, users) { + {where: {vip: true}}, options, function(err, users) { should.exist(users); should.not.exist(err); var names = users.map(function(u) { @@ -241,7 +241,7 @@ describe('crud-with-options', function() { }); it('should allow find(filter, cb)', function(done) { - User.find({ limit: 3 }, function(err, users) { + User.find({limit: 3}, function(err, users) { should.exists(users); should.not.exists(err); users.should.have.lengthOf(3); @@ -259,15 +259,15 @@ describe('crud-with-options', function() { }); it('should allow find(filter, options)', function() { - User.find({ limit: 3 }, options); + User.find({limit: 3}, options); }); it('should allow find(filter)', function() { - User.find({ limit: 3 }); + User.find({limit: 3}); }); it('should skip trailing undefined args', function(done) { - User.find({ limit: 3 }, function(err, users) { + User.find({limit: 3}, function(err, users) { should.exists(users); should.not.exists(err); users.should.have.lengthOf(3); @@ -285,7 +285,7 @@ describe('crud-with-options', function() { it('should throw on an invalid options arg', function() { (function() { - User.find({ limit: 3 }, 'invalid option', function(err, users) { + User.find({limit: 3}, 'invalid option', function(err, users) { // noop }); }).should.throw('The options argument must be an object'); @@ -293,7 +293,7 @@ describe('crud-with-options', function() { it('should throw on an invalid cb arg', function() { (function() { - User.find({ limit: 3 }, {}, 'invalid cb'); + User.find({limit: 3}, {}, 'invalid cb'); }).should.throw('The cb argument must be a function'); }); }); @@ -311,7 +311,7 @@ describe('crud-with-options', function() { }); it('should allow count(where, cb)', function(done) { - User.count({ role: 'lead' }, function(err, n) { + User.count({role: 'lead'}, function(err, n) { should.not.exist(err); should.exist(n); n.should.equal(2); @@ -320,7 +320,7 @@ describe('crud-with-options', function() { }); it('should allow count(where, options, cb)', function(done) { - User.count({ role: 'lead' }, options, function(err, n) { + User.count({role: 'lead'}, options, function(err, n) { should.not.exist(err); should.exist(n); n.should.equal(2); @@ -333,7 +333,7 @@ describe('crud-with-options', function() { before(seed); it('should allow findOne(cb)', function(done) { - User.find({ order: 'id' }, function(err, users) { + User.find({order: 'id'}, function(err, users) { User.findOne(function(e, u) { should.not.exist(e); should.exist(u); @@ -344,7 +344,7 @@ describe('crud-with-options', function() { }); it('should allow findOne(filter, options, cb)', function(done) { - User.findOne({ order: 'order' }, options, function(e, u) { + User.findOne({order: 'order'}, options, function(e, u) { should.not.exist(e); should.exist(u); u.order.should.equal(1); @@ -354,7 +354,7 @@ describe('crud-with-options', function() { }); it('should allow findOne(filter, cb)', function(done) { - User.findOne({ order: 'order' }, function(e, u) { + User.findOne({order: 'order'}, function(e, u) { should.not.exist(e); should.exist(u); u.order.should.equal(1); @@ -364,7 +364,7 @@ describe('crud-with-options', function() { }); it('should allow trailing undefined args', function(done) { - User.findOne({ order: 'order' }, function(e, u) { + User.findOne({order: 'order'}, function(e, u) { should.not.exist(e); should.exist(u); u.order.should.equal(1); @@ -401,7 +401,7 @@ describe('crud-with-options', function() { describe('save', function() { it('should allow save(options, cb)', function(done) { - var options = { foo: 'bar' }; + var options = {foo: 'bar'}; var opts; User.observe('after save', function(ctx, next) { @@ -422,12 +422,12 @@ describe('crud-with-options', function() { beforeEach(seed); it('should allow destroyAll(where, options, cb)', function(done) { - User.destroyAll({ name: 'John Lennon' }, options, function(err) { + User.destroyAll({name: 'John Lennon'}, options, function(err) { should.not.exist(err); - User.find({ where: { name: 'John Lennon' }}, function(err, data) { + User.find({where: {name: 'John Lennon'}}, function(err, data) { should.not.exist(err); data.length.should.equal(0); - User.find({ where: { name: 'Paul McCartney' }}, function(err, data) { + User.find({where: {name: 'Paul McCartney'}}, function(err, data) { should.not.exist(err); data.length.should.equal(1); done(); @@ -437,12 +437,12 @@ describe('crud-with-options', function() { }); it('should allow destroyAll(where, cb)', function(done) { - User.destroyAll({ name: 'John Lennon' }, function(err) { + User.destroyAll({name: 'John Lennon'}, function(err) { should.not.exist(err); - User.find({ where: { name: 'John Lennon' }}, function(err, data) { + User.find({where: {name: 'John Lennon'}}, function(err, data) { should.not.exist(err); data.length.should.equal(0); - User.find({ where: { name: 'Paul McCartney' }}, function(err, data) { + User.find({where: {name: 'Paul McCartney'}}, function(err, data) { should.not.exist(err); data.length.should.equal(1); done(); @@ -454,10 +454,10 @@ describe('crud-with-options', function() { it('should allow destroyAll(cb)', function(done) { User.destroyAll(function(err) { should.not.exist(err); - User.find({ where: { name: 'John Lennon' }}, function(err, data) { + User.find({where: {name: 'John Lennon'}}, function(err, data) { should.not.exist(err); data.length.should.equal(0); - User.find({ where: { name: 'Paul McCartney' }}, function(err, data) { + User.find({where: {name: 'Paul McCartney'}}, function(err, data) { should.not.exist(err); data.length.should.equal(0); done(); @@ -471,12 +471,12 @@ describe('crud-with-options', function() { beforeEach(seed); it('should allow updateAll(where, data, cb)', function(done) { - User.update({ name: 'John Lennon' }, { name: 'John Smith' }, function(err) { + User.update({name: 'John Lennon'}, {name: 'John Smith'}, function(err) { should.not.exist(err); - User.find({ where: { name: 'John Lennon' }}, function(err, data) { + User.find({where: {name: 'John Lennon'}}, function(err, data) { should.not.exist(err); data.length.should.equal(0); - User.find({ where: { name: 'John Smith' }}, function(err, data) { + User.find({where: {name: 'John Smith'}}, function(err, data) { should.not.exist(err); data.length.should.equal(1); done(); @@ -486,13 +486,13 @@ describe('crud-with-options', function() { }); it('should allow updateAll(where, data, options, cb)', function(done) { - User.update({ name: 'John Lennon' }, { name: 'John Smith' }, options, + User.update({name: 'John Lennon'}, {name: 'John Smith'}, options, function(err) { should.not.exist(err); - User.find({ where: { name: 'John Lennon' }}, function(err, data) { + User.find({where: {name: 'John Lennon'}}, function(err, data) { should.not.exist(err); data.length.should.equal(0); - User.find({ where: { name: 'John Smith' }}, function(err, data) { + User.find({where: {name: 'John Smith'}}, function(err, data) { should.not.exist(err); data.length.should.equal(1); done(); @@ -502,11 +502,11 @@ describe('crud-with-options', function() { }); it('should allow updateAll(data, cb)', function(done) { - User.update({ name: 'John Smith' }, function() { - User.find({ where: { name: 'John Lennon' }}, function(err, data) { + User.update({name: 'John Smith'}, function() { + User.find({where: {name: 'John Lennon'}}, function(err, data) { should.not.exist(err); data.length.should.equal(0); - User.find({ where: { name: 'John Smith' }}, function(err, data) { + User.find({where: {name: 'John Smith'}}, function(err, data) { should.not.exist(err); data.length.should.equal(6); done(); @@ -542,12 +542,12 @@ describe('upsertWithWhere', function() { }); it('allows upsertWithWhere by accepting where,data and cb as arguments', function(done) { - User.upsertWithWhere({ name: 'John Lennon' }, { name: 'John Smith' }, function(err) { + User.upsertWithWhere({name: 'John Lennon'}, {name: 'John Smith'}, function(err) { if (err) return done(err); - User.find({ where: { name: 'John Lennon' }}, function(err, data) { + User.find({where: {name: 'John Lennon'}}, function(err, data) { if (err) return done(err); data.length.should.equal(0); - User.find({ where: { name: 'John Smith' }}, function(err, data) { + User.find({where: {name: 'John Smith'}}, function(err, data) { if (err) return done(err); data.length.should.equal(1); data[0].name.should.equal('John Smith'); @@ -563,9 +563,9 @@ describe('upsertWithWhere', function() { it('allows upsertWithWhere by accepting where, data, options, and cb as arguments', function(done) { options = {}; - User.upsertWithWhere({ name: 'John Lennon' }, { name: 'John Smith' }, options, function(err) { + User.upsertWithWhere({name: 'John Lennon'}, {name: 'John Smith'}, options, function(err) { if (err) return done(err); - User.find({ where: { name: 'John Smith' }}, function(err, data) { + User.find({where: {name: 'John Smith'}}, function(err, data) { if (err) return done(err); data.length.should.equal(1); data[0].name.should.equal('John Smith'); @@ -600,10 +600,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/datatype.test.js b/test/datatype.test.js index 67b88297..ad5d947f 100644 --- a/test/datatype.test.js +++ b/test/datatype.test.js @@ -18,7 +18,7 @@ describe('datatypes', function() { date: Date, num: Number, bool: Boolean, - list: { type: [String] }, + list: {type: [String]}, arr: Array, nested: Nested, }); @@ -28,12 +28,12 @@ describe('datatypes', function() { it('should return 400 when property of type array is set to string value', function(done) { var myModel = db.define('myModel', { - list: { type: ['object'] }, + list: {type: ['object']}, }); (function() { - myModel.create({ list: 'This string will crash the server' }); - }).should.throw({ statusCode: 400 }); + myModel.create({list: 'This string will crash the server'}); + }).should.throw({statusCode: 400}); done(); }); @@ -41,12 +41,12 @@ describe('datatypes', function() { it('should return 400 when property of type array is set to object value', function(done) { var myModel = db.define('myModel', { - list: { type: ['object'] }, + list: {type: ['object']}, }); (function() { - myModel.create({ list: { key: 'This string will crash the server' }}); - }).should.throw({ statusCode: 400 }); + myModel.create({list: {key: 'This string will crash the server'}}); + }).should.throw({statusCode: 400}); done(); }); @@ -54,12 +54,12 @@ describe('datatypes', function() { it('throws an error when property of type Date is set to an invalid value', function() { var myModel = db.define('myModel', { - date: { type: Date }, + date: {type: Date}, }); (function() { - myModel.create({ date: 'invalid' }); - }).should.throw({ message: 'Invalid date: invalid' }); + myModel.create({date: 'invalid'}); + }).should.throw({message: 'Invalid date: invalid'}); }); it('should keep types when get read data from db', function(done) { @@ -114,7 +114,7 @@ describe('datatypes', function() { var d = new Date, id; Model.create({ - str: 'hello', date: d, num: '3', bool: 1 }, function(err, m) { + str: 'hello', date: d, num: '3', bool: 1}, function(err, m) { should.not.exist(err); should.exist(m && m.id); @@ -162,7 +162,7 @@ describe('datatypes', function() { }); it('should not coerce nested objects into ModelConstructor types', function() { - var coerced = Model._coerce({ nested: { foo: 'bar' }}); + var coerced = Model._coerce({nested: {foo: 'bar'}}); coerced.nested.constructor.name.should.equal('Object'); }); @@ -170,10 +170,10 @@ describe('datatypes', function() { function(done) { db = getSchema(); Model = db.define('RequiredNumber', { - num: { type: Number, required: true }, + num: {type: Number, required: true}, }); db.automigrate(['Model'], function() { - Model.create({ num: [1, 2, 3] }, function(err, inst) { + Model.create({num: [1, 2, 3]}, function(err, inst) { should.exist(err); err.should.have.property('name').equal('ValidationError'); done(); @@ -187,8 +187,8 @@ describe('datatypes', function() { TestModel = db.define( 'TestModel', { - desc: { type: String, required: false }, - stars: { type: Number, required: false }, + desc: {type: String, required: false}, + stars: {type: Number, required: false}, }, { persistUndefinedAsNull: true, @@ -200,8 +200,8 @@ describe('datatypes', function() { }); it('should set missing optional properties to null', function(done) { - var EXPECTED = { desc: null, stars: null }; - TestModel.create({ name: 'a-test-name' }, function(err, created) { + var EXPECTED = {desc: null, stars: null}; + TestModel.create({name: 'a-test-name'}, function(err, created) { if (err) return done(err); created.should.have.properties(EXPECTED); @@ -214,13 +214,13 @@ describe('datatypes', function() { }); it('should convert property value undefined to null', function(done) { - var EXPECTED = { desc: null, extra: null }; + var EXPECTED = {desc: null, extra: null}; if (isStrict) { // SQL-based connectors don't support dynamic properties delete EXPECTED.extra; } - var data = { desc: undefined, extra: undefined }; + var data = {desc: undefined, extra: undefined}; TestModel.create(data, function(err, created) { if (err) return done(err); @@ -249,7 +249,7 @@ describe('datatypes', function() { }); it('should convert undefined to null on save', function(done) { - var EXPECTED = { desc: null, stars: null, extra: null, dx: null }; + var EXPECTED = {desc: null, stars: null, extra: null, dx: null}; if (isStrict) { // SQL-based connectors don't support dynamic properties delete EXPECTED.extra; @@ -279,14 +279,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 928698e9..7e926513 100644 --- a/test/default-scope.test.js +++ b/test/default-scope.test.js @@ -18,31 +18,31 @@ var db, Category, Product, Tool, Widget, Thing, Person; var setupProducts = function(ids, done) { async.series([ function(next) { - Tool.create({ name: 'Tool Z' }, function(err, inst) { + Tool.create({name: 'Tool Z'}, function(err, inst) { ids.toolZ = inst.id; next(); }); }, function(next) { - Widget.create({ name: 'Widget Z' }, function(err, inst) { + Widget.create({name: 'Widget Z'}, function(err, inst) { ids.widgetZ = inst.id; next(); }); }, function(next) { - Tool.create({ name: 'Tool A', active: false }, function(err, inst) { + Tool.create({name: 'Tool A', active: false}, function(err, inst) { ids.toolA = inst.id; next(); }); }, function(next) { - Widget.create({ name: 'Widget A' }, function(err, inst) { + Widget.create({name: 'Widget A'}, function(err, inst) { ids.widgetA = inst.id; next(); }); }, function(next) { - Widget.create({ name: 'Widget B', active: false }, function(err, inst) { + Widget.create({name: 'Widget B', active: false}, function(err, inst) { ids.widgetB = inst.id; next(); }); @@ -62,10 +62,10 @@ describe('default scope', function() { name: String, kind: String, description: String, - active: { type: Boolean, default: true }, + active: {type: Boolean, default: true}, }, { - scope: { order: 'name' }, - scopes: { active: { where: { active: true }}}, + scope: {order: 'name'}, + scopes: {active: {where: {active: true}}}, }); Product.lookupModel = function(data) { @@ -76,46 +76,46 @@ describe('default scope', function() { Tool = db.define('Tool', Product.definition.properties, { base: 'Product', - scope: { where: { kind: 'Tool' }, order: 'name' }, - scopes: { active: { where: { active: true }}}, - mongodb: { collection: 'Product' }, - memory: { collection: 'Product' }, + scope: {where: {kind: 'Tool'}, order: 'name'}, + scopes: {active: {where: {active: true}}}, + mongodb: {collection: 'Product'}, + memory: {collection: 'Product'}, }); Widget = db.define('Widget', Product.definition.properties, { base: 'Product', - properties: { kind: 'Widget' }, - scope: { where: { kind: 'Widget' }, order: 'name' }, - scopes: { active: { where: { active: true }}}, - mongodb: { collection: 'Product' }, - memory: { collection: 'Product' }, + properties: {kind: 'Widget'}, + scope: {where: {kind: 'Widget'}, order: 'name'}, + scopes: {active: {where: {active: true}}}, + mongodb: {collection: 'Product'}, + memory: {collection: 'Product'}, }); - Person = db.define('Person', { name: String }, { - scope: { include: 'things' }, + Person = db.define('Person', {name: String}, { + scope: {include: 'things'}, }); // inst is only valid for instance methods // like save, updateAttributes var scopeFn = function(target, inst) { - return { where: { kind: this.modelName }}; + return {where: {kind: this.modelName}}; }; var propertiesFn = function(target, inst) { - return { kind: this.modelName }; + return {kind: this.modelName}; }; Thing = db.define('Thing', Product.definition.properties, { base: 'Product', attributes: propertiesFn, scope: scopeFn, - mongodb: { collection: 'Product' }, - memory: { collection: 'Product' }, + mongodb: {collection: 'Product'}, + memory: {collection: 'Product'}, }); Category.hasMany(Product); - Category.hasMany(Tool, { scope: { order: 'name DESC' }}); + Category.hasMany(Tool, {scope: {order: 'name DESC'}}); Category.hasMany(Widget); Category.hasMany(Thing); @@ -138,10 +138,10 @@ describe('default scope', function() { }); it('should return a scoped instance', function() { - var p = new Tool({ name: 'Product A', kind: 'ignored' }); + var p = new Tool({name: 'Product A', kind: 'ignored'}); p.name.should.equal('Product A'); p.kind.should.equal('Tool'); - p.setAttributes({ kind: 'ignored' }); + p.setAttributes({kind: 'ignored'}); p.kind.should.equal('Tool'); p.setAttribute('kind', 'other'); // currently not enforced @@ -149,7 +149,7 @@ describe('default scope', function() { }); it('should create a scoped instance - tool', function(done) { - Tool.create({ name: 'Product A', kind: 'ignored' }, function(err, p) { + Tool.create({name: 'Product A', kind: 'ignored'}, function(err, p) { should.not.exist(err); p.name.should.equal('Product A'); p.kind.should.equal('Tool'); @@ -159,7 +159,7 @@ describe('default scope', function() { }); it('should create a scoped instance - widget', function(done) { - Widget.create({ name: 'Product B', kind: 'ignored' }, function(err, p) { + Widget.create({name: 'Product B', kind: 'ignored'}, function(err, p) { should.not.exist(err); p.name.should.equal('Product B'); p.kind.should.equal('Widget'); @@ -170,7 +170,7 @@ describe('default scope', function() { it('should update a scoped instance - updateAttributes', function(done) { Tool.findById(ids.productA, function(err, p) { - p.updateAttributes({ description: 'A thing...', kind: 'ingored' }, function(err, inst) { + p.updateAttributes({description: 'A thing...', kind: 'ingored'}, function(err, inst) { should.not.exist(err); p.name.should.equal('Product A'); p.kind.should.equal('Tool'); @@ -198,7 +198,7 @@ describe('default scope', function() { }); it('should update a scoped instance - updateOrCreate', function(done) { - var data = { id: ids.productA, description: 'Anything...', kind: 'ingored' }; + var data = {id: ids.productA, description: 'Anything...', kind: 'ingored'}; Tool.updateOrCreate(data, function(err, p) { should.not.exist(err); p.name.should.equal('Product A'); @@ -270,7 +270,7 @@ describe('default scope', function() { }); it('should apply default scope - order override', function(done) { - Product.find({ order: 'name DESC' }, function(err, products) { + Product.find({order: 'name DESC'}, function(err, products) { should.not.exist(err); products.should.have.length(5); products[0].name.should.equal('Widget Z'); @@ -293,7 +293,7 @@ describe('default scope', function() { }); it('should apply default scope - where (widget)', function(done) { - Widget.find({ where: { active: true }}, function(err, products) { + Widget.find({where: {active: true}}, function(err, products) { should.not.exist(err); products.should.have.length(2); products[0].name.should.equal('Widget A'); @@ -303,7 +303,7 @@ describe('default scope', function() { }); it('should apply default scope - order (widget)', function(done) { - Widget.find({ order: 'name DESC' }, function(err, products) { + Widget.find({order: 'name DESC'}, function(err, products) { should.not.exist(err); products.should.have.length(3); products[0].name.should.equal('Widget Z'); @@ -394,7 +394,7 @@ describe('default scope', function() { }); it('should apply default scope - where', function(done) { - Widget.count({ name: 'Widget Z' }, function(err, count) { + Widget.count({name: 'Widget Z'}, function(err, count) { should.not.exist(err); count.should.equal(1); done(); @@ -402,7 +402,7 @@ describe('default scope', function() { }); it('should apply default scope - no match', function(done) { - Tool.count({ name: 'Widget Z' }, function(err, count) { + Tool.count({name: 'Widget Z'}, function(err, count) { should.not.exist(err); count.should.equal(0); done(); @@ -476,9 +476,9 @@ describe('default scope', function() { }); it('should apply default scope', function(done) { - Widget.update({ active: false }, { active: true, kind: 'ignored' }, function(err) { + Widget.update({active: false}, {active: true, kind: 'ignored'}, function(err) { should.not.exist(err); - Widget.find({ where: { active: true }}, function(err, products) { + Widget.find({where: {active: true}}, function(err, products) { should.not.exist(err); products.should.have.length(3); products[0].name.should.equal('Widget A'); @@ -490,7 +490,7 @@ describe('default scope', function() { }); it('should apply default scope - no match', function(done) { - Tool.update({ name: 'Widget A' }, { name: 'Ignored' }, function(err) { + Tool.update({name: 'Widget A'}, {name: 'Ignored'}, function(err) { should.not.exist(err); Product.findById(ids.widgetA, function(err, product) { should.not.exist(err); @@ -501,7 +501,7 @@ describe('default scope', function() { }); it('should have updated within scope', function(done) { - Product.find({ where: { active: true }}, function(err, products) { + Product.find({where: {active: true}}, function(err, products) { should.not.exist(err); products.should.have.length(4); products[0].name.should.equal('Tool Z'); @@ -521,7 +521,7 @@ describe('default scope', function() { }); it('should apply default scope - custom where', function(done) { - Widget.remove({ name: 'Widget A' }, function(err) { + Widget.remove({name: 'Widget A'}, function(err) { should.not.exist(err); Product.find(function(err, products) { products.should.have.length(4); @@ -535,7 +535,7 @@ describe('default scope', function() { }); it('should apply default scope - custom where (no match)', function(done) { - Tool.remove({ name: 'Widget Z' }, function(err) { + Tool.remove({name: 'Widget Z'}, function(err) { should.not.exist(err); Product.find(function(err, products) { products.should.have.length(4); @@ -561,7 +561,7 @@ describe('default scope', function() { }); it('should create a scoped instance - tool', function(done) { - Tool.create({ name: 'Tool B' }, function(err, p) { + Tool.create({name: 'Tool B'}, function(err, p) { should.not.exist(err); Product.find(function(err, products) { products.should.have.length(3); @@ -629,7 +629,7 @@ describe('default scope', function() { }); it('should create a scoped instance - widget', function(done) { - Widget.create({ name: 'Product', kind: 'ignored' }, function(err, p) { + Widget.create({name: 'Product', kind: 'ignored'}, function(err, p) { p.name.should.equal('Product'); p.kind.should.equal('Widget'); done(); @@ -637,7 +637,7 @@ describe('default scope', function() { }); it('should create a scoped instance - thing', function(done) { - Thing.create({ name: 'Product', kind: 'ignored' }, function(err, p) { + Thing.create({name: 'Product', kind: 'ignored'}, function(err, p) { p.name.should.equal('Product'); p.kind.should.equal('Thing'); done(); @@ -645,7 +645,7 @@ describe('default scope', function() { }); it('should find a scoped instance - widget', function(done) { - Widget.findOne({ where: { name: 'Product' }}, function(err, p) { + Widget.findOne({where: {name: 'Product'}}, function(err, p) { p.name.should.equal('Product'); p.kind.should.equal('Widget'); done(); @@ -653,7 +653,7 @@ describe('default scope', function() { }); it('should find a scoped instance - thing', function(done) { - Thing.findOne({ where: { name: 'Product' }}, function(err, p) { + Thing.findOne({where: {name: 'Product'}}, function(err, p) { p.name.should.equal('Product'); p.kind.should.equal('Thing'); done(); @@ -661,7 +661,7 @@ describe('default scope', function() { }); it('should find a scoped instance - thing', function(done) { - Product.find({ where: { name: 'Product' }}, function(err, products) { + Product.find({where: {name: 'Product'}}, function(err, products) { products.should.have.length(2); products[0].name.should.equal('Product'); products[1].name.should.equal('Product'); @@ -681,20 +681,20 @@ describe('default scope', function() { }); before(function(done) { - Category.create({ name: 'Category A' }, function(err, cat) { + Category.create({name: 'Category A'}, function(err, cat) { ids.categoryA = cat.id; async.series([ function(next) { - cat.widgets.create({ name: 'Widget B', kind: 'ignored' }, next); + cat.widgets.create({name: 'Widget B', kind: 'ignored'}, next); }, function(next) { - cat.widgets.create({ name: 'Widget A' }, next); + cat.widgets.create({name: 'Widget A'}, next); }, function(next) { - cat.tools.create({ name: 'Tool A' }, next); + cat.tools.create({name: 'Tool A'}, next); }, function(next) { - cat.things.create({ name: 'Thing A' }, next); + cat.things.create({name: 'Thing A'}, next); }, ], done); }); @@ -776,7 +776,7 @@ describe('default scope', function() { it('should create related item with default scope', function(done) { Category.findById(ids.categoryA, function(err, cat) { - cat.tools.create({ name: 'Tool B' }, done); + cat.tools.create({name: 'Tool B'}, done); }); }); @@ -800,8 +800,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 d8480c71..6ab7ac45 100644 --- a/test/defaults.test.js +++ b/test/defaults.test.js @@ -14,8 +14,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 +43,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 +56,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 +65,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 06f993a3..22f7ce6b 100644 --- a/test/discovery.test.js +++ b/test/discovery.test.js @@ -11,11 +11,11 @@ describe('Memory connector with mocked discovery', function() { var ds; before(function() { - ds = new DataSource({ connector: 'memory' }); + ds = new DataSource({connector: 'memory'}); - var models = [{ type: 'table', name: 'CUSTOMER', owner: 'STRONGLOOP' }, - { type: 'table', name: 'INVENTORY', owner: 'STRONGLOOP' }, - { type: 'table', name: 'LOCATION', owner: 'STRONGLOOP' }]; + var models = [{type: 'table', name: 'CUSTOMER', owner: 'STRONGLOOP'}, + {type: 'table', name: 'INVENTORY', owner: 'STRONGLOOP'}, + {type: 'table', name: 'LOCATION', owner: 'STRONGLOOP'}]; ds.discoverModelDefinitions = function(options, cb) { process.nextTick(function() { @@ -102,7 +102,7 @@ describe('Memory connector with mocked discovery', function() { it('should not convert table/column names with null custom mapper', function(done) { - ds.discoverSchemas('INVENTORY', { nameMapper: null }, function(err, schemas) { + ds.discoverSchemas('INVENTORY', {nameMapper: null}, function(err, schemas) { if (err) return done(err); schemas.should.have.property('STRONGLOOP.INVENTORY'); var s = schemas['STRONGLOOP.INVENTORY']; @@ -117,8 +117,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 +126,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 +137,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 +184,7 @@ describe('Memory connector with mocked discovery', function() { name: 'Inventory', options: { idInjection: false, - memory: { schema: 'STRONGLOOP', table: 'INVENTORY' }, + memory: {schema: 'STRONGLOOP', table: 'INVENTORY'}, }, properties: { available: { @@ -285,11 +285,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 +352,7 @@ describe('discoverModelProperties', function() { var ds; var modelProperties; before(function() { - ds = new DataSource({ connector: 'memory' }); + ds = new DataSource({connector: 'memory'}); modelProperties = [{ owner: 'STRONGLOOP', @@ -438,7 +438,7 @@ describe('discoverPrimaryKeys', function() { var ds; var modelProperties; before(function() { - ds = new DataSource({ connector: 'memory' }); + ds = new DataSource({connector: 'memory'}); primaryKeys = [ { @@ -498,7 +498,7 @@ describe('discoverForeignKeys', function() { var ds; var modelProperties; before(function() { - ds = new DataSource({ connector: 'memory' }); + ds = new DataSource({connector: 'memory'}); foreignKeys = [{ fkOwner: 'STRONGLOOP', @@ -555,7 +555,7 @@ describe('discoverExportedForeignKeys', function() { var ds; var modelProperties; before(function() { - ds = new DataSource({ connector: 'memory' }); + ds = new DataSource({connector: 'memory'}); exportedForeignKeys = [{ fkName: 'PRODUCT_FK', diff --git a/test/events.js b/test/events.js index 21d2cb5a..44761cec 100644 --- a/test/events.js +++ b/test/events.js @@ -28,25 +28,25 @@ describe('events', function() { describe('changed', function() { it('should be emitted after save', function(done) { - var model = new this.TestModel({ name: 'foobar' }); + var model = new this.TestModel({name: 'foobar'}); this.shouldEmitEvent('changed', assertValidChangedArgs, done); model.save(); }); it('should be emitted after upsert', function(done) { this.shouldEmitEvent('changed', assertValidChangedArgs, done); - this.TestModel.upsert({ name: 'batbaz' }); + this.TestModel.upsert({name: 'batbaz'}); }); it('should be emitted after create', function(done) { this.shouldEmitEvent('changed', assertValidChangedArgs, done); - this.TestModel.create({ name: '...' }); + this.TestModel.create({name: '...'}); }); it('should be emitted after updateAttributes', function(done) { var test = this; - this.TestModel.create({ name: 'bazzy' }, function(err, model) { + this.TestModel.create({name: 'bazzy'}, function(err, model) { // prevent getting the changed event from "create" process.nextTick(function() { test.shouldEmitEvent('changed', assertValidChangedArgs, done); - model.updateAttributes({ name: 'foo' }); + model.updateAttributes({name: 'foo'}); }); }); }); @@ -68,7 +68,7 @@ describe('events', function() { this.shouldEmitEvent('deletedAll', function(where) { where.name.should.equal('foo'); }, done); - this.TestModel.destroyAll({ name: 'foo' }); + this.TestModel.destroyAll({name: 'foo'}); }); }); }); diff --git a/test/geo.test.js b/test/geo.test.js index 0b850a1a..b2f26da9 100644 --- a/test/geo.test.js +++ b/test/geo.test.js @@ -21,7 +21,7 @@ describe('GeoPoint', function() { }); it('should support a valid object', function() { - var point = new GeoPoint({ lat: -34, lng: 150 }); + var point = new GeoPoint({lat: -34, lng: 150}); point.lat.should.equal(-34); point.lng.should.equal(150); @@ -80,14 +80,14 @@ describe('GeoPoint', function() { describe('toString()', function() { it('should return a string in the form "lat,lng"', function() { - var point = new GeoPoint({ lat: -34, lng: 150 }); + var point = new GeoPoint({lat: -34, lng: 150}); point.toString().should.equal('-34,150'); }); }); describe('distance calculation between two points', function() { - var here = new GeoPoint({ lat: 40.77492964101182, lng: -73.90950187151662 }); - var there = new GeoPoint({ lat: 40.7753227, lng: -73.909217 }); + var here = new GeoPoint({lat: 40.77492964101182, lng: -73.90950187151662}); + var there = new GeoPoint({lat: 40.7753227, lng: -73.909217}); it('should return value in miles by default', function() { var distance = GeoPoint.distanceBetween(here, there); @@ -105,27 +105,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/hooks.test.js b/test/hooks.test.js index 8804ca63..f1a6b209 100644 --- a/test/hooks.test.js +++ b/test/hooks.test.js @@ -18,7 +18,7 @@ describe('hooks', function() { db = getSchema(); User = db.define('User', { - email: { type: String, index: true }, + email: {type: String, index: true}, name: String, password: String, state: String, @@ -46,7 +46,7 @@ describe('hooks', function() { this.name += ' Rozental'; } }; - User.create({ name: 'Nickolay' }, function(err, u) { + User.create({name: 'Nickolay'}, function(err, u) { u.id.should.be.ok; u.name.should.equal('Nickolay Rozental'); done(); @@ -127,7 +127,7 @@ describe('hooks', function() { it('should be triggered on updateAttributes', function(done) { User.create(function(err, user) { addHooks('Save', done); - user.updateAttributes({ name: 'Anatoliy' }); + user.updateAttributes({name: 'Anatoliy'}); }); }); @@ -161,7 +161,7 @@ describe('hooks', function() { password: '53cr3t', }, function() { User.findOne({ - where: { email: 'james.bond@example.com' }, + where: {email: 'james.bond@example.com'}, }, function(err, jb) { jb.password.should.equal('hash'); done(); @@ -184,7 +184,7 @@ describe('hooks', function() { should.exist(u); u.password.should.equal('hash'); User.findOne({ - where: { email: 'james.bond@example.com' }, + where: {email: 'james.bond@example.com'}, }, function(err, jb) { jb.password.should.equal('hash'); done(); @@ -229,7 +229,7 @@ describe('hooks', function() { it('should be triggered on updateAttributes', function(done) { User.create(function(err, user) { addHooks('Update', done); - user.updateAttributes({ name: 'Anatoliy' }); + user.updateAttributes({name: 'Anatoliy'}); }); }); @@ -247,7 +247,7 @@ describe('hooks', function() { data.should.have.keys('name', 'email'); done(); }; - user.updateAttributes({ name: 1, email: 2 }); + user.updateAttributes({name: 1, email: 2}); }); }); @@ -392,7 +392,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 0d2be343..ec3beb43 100644 --- a/test/include.test.js +++ b/test/include.test.js @@ -16,7 +16,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 +39,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 +59,7 @@ describe('include', function() { }); it('should fetch Passport - Owner - Posts', function(done) { - Passport.find({ include: { owner: 'posts' }}, function(err, passports) { + Passport.find({include: {owner: 'posts'}}, function(err, passports) { should.not.exist(err); should.exist(passports); passports.length.should.be.ok; @@ -90,7 +90,7 @@ describe('include', function() { }); it('should fetch Passport - Owner - empty Posts', function(done) { - Passport.findOne({ where: { number: '4' }, include: { owner: 'posts' }}, function(err, passport) { + Passport.findOne({where: {number: '4'}, include: {owner: 'posts'}}, function(err, passport) { should.not.exist(err); should.exist(passport); passport.__cachedRelations.should.have.property('owner'); @@ -112,7 +112,7 @@ describe('include', function() { }); it('should fetch Passport - Owner - Posts - alternate syntax', function(done) { - Passport.find({ include: { owner: { relation: 'posts' }}}, function(err, passports) { + Passport.find({include: {owner: {relation: 'posts'}}}, function(err, passports) { should.not.exist(err); should.exist(passports); passports.length.should.be.ok; @@ -124,7 +124,7 @@ describe('include', function() { it('should fetch Passports - User - Posts - User', function(done) { Passport.find({ - include: { owner: { posts: 'author' }}, + include: {owner: {posts: 'author'}}, }, function(err, passports) { should.not.exist(err); should.exist(passports); @@ -154,7 +154,7 @@ describe('include', function() { it('should fetch Passports with include scope on Posts', function(done) { Passport.find({ - include: { owner: { relation: 'posts', scope: { + include: {owner: {relation: 'posts', scope: { fields: ['title'], include: ['author'], order: 'title DESC', }}}, @@ -209,7 +209,7 @@ describe('include', function() { it('should fetch Users with include scope on Posts - belongsTo', function(done) { Post.find({ - include: { relation: 'author', scope: { fields: ['name'] }}, + include: {relation: 'author', scope: {fields: ['name']}}, }, function(err, posts) { should.not.exist(err); should.exist(posts); @@ -262,7 +262,7 @@ describe('include', function() { include: { relation: 'passports', scope: { - where: { number: '2' }, + where: {number: '2'}, }, }, }, function(err, users) { @@ -282,7 +282,7 @@ describe('include', function() { }); it('should fetch User - Posts AND Passports', function(done) { - User.find({ include: ['posts', 'passports'] }, function(err, users) { + User.find({include: ['posts', 'passports']}, function(err, users) { should.not.exist(err); should.exist(users); users.length.should.be.ok; @@ -315,12 +315,12 @@ describe('include', function() { it('should fetch User - Posts AND Passports in relation syntax', function(done) { - User.find({ include: [ - { relation: 'posts', scope: { - where: { title: 'Post A' }, + User.find({include: [ + {relation: 'posts', scope: { + where: {title: 'Post A'}, }}, 'passports', - ] }, function(err, users) { + ]}, function(err, users) { should.not.exist(err); should.exist(users); users.length.should.be.ok; @@ -353,7 +353,7 @@ describe('include', function() { }); it('should not fetch User - AccessTokens', function(done) { - User.find({ include: ['accesstokens'] }, function(err, users) { + User.find({include: ['accesstokens']}, function(err, users) { should.not.exist(err); should.exist(users); users.length.should.be.ok; @@ -366,8 +366,8 @@ describe('include', function() { }); it('should support hasAndBelongsToMany', function(done) { - Assembly.create({ name: 'car' }, function(err, assembly) { - Part.create({ partNumber: 'engine' }, function(err, part) { + Assembly.create({name: 'car'}, function(err, assembly) { + Part.create({partNumber: 'engine'}, function(err, part) { assembly.parts.add(part, function(err, data) { assembly.parts(function(err, parts) { should.not.exist(err); @@ -376,8 +376,8 @@ describe('include', function() { parts[0].partNumber.should.equal('engine'); // Create a part - assembly.parts.create({ partNumber: 'door' }, function(err, part4) { - Assembly.find({ include: 'parts' }, function(err, assemblies) { + assembly.parts.create({partNumber: 'door'}, function(err, part4) { + Assembly.find({include: 'parts'}, function(err, assemblies) { assemblies.length.should.equal(1); assemblies[0].parts().length.should.equal(2); done(); @@ -390,7 +390,7 @@ describe('include', function() { }); it('should fetch User - Profile (HasOne)', function(done) { - User.find({ include: ['profile'] }, function(err, users) { + User.find({include: ['profile']}, function(err, users) { should.not.exist(err); should.exist(users); users.length.should.be.ok; @@ -422,8 +422,8 @@ describe('include', function() { // Not implemented correctly, see: loopback-datasource-juggler/issues/166 // fixed by DB optimization it('should support include scope on hasAndBelongsToMany', function(done) { - Assembly.find({ include: { relation: 'parts', scope: { - where: { partNumber: 'engine' }, + Assembly.find({include: {relation: 'parts', scope: { + where: {partNumber: 'engine'}, }}}, function(err, assemblies) { assemblies.length.should.equal(1); var parts = assemblies[0].parts(); @@ -471,7 +471,7 @@ describe('include', function() { }); it('including belongsTo should make only 2 db calls', function(done) { var self = this; - Passport.find({ include: 'owner' }, function(err, passports) { + Passport.find({include: 'owner'}, function(err, passports) { passports.length.should.be.ok; passports.forEach(function(p) { p.__cachedRelations.should.have.property('owner'); @@ -494,11 +494,11 @@ describe('include', function() { it('including hasManyThrough should make only 3 db calls', function(done) { var self = this; - Assembly.create([{ name: 'sedan' }, { name: 'hatchback' }, - { name: 'SUV' }], + Assembly.create([{name: 'sedan'}, {name: 'hatchback'}, + {name: 'SUV'}], function(err, assemblies) { - Part.create([{ partNumber: 'engine' }, { partNumber: 'bootspace' }, - { partNumber: 'silencer' }], + Part.create([{partNumber: 'engine'}, {partNumber: 'bootspace'}, + {partNumber: 'silencer'}], function(err, parts) { async.each(parts, function(part, next) { async.each(assemblies, function(assembly, next) { @@ -547,7 +547,7 @@ describe('include', function() { it('including hasMany should make only 2 db calls', function(done) { var self = this; - User.find({ include: ['posts', 'passports'] }, function(err, users) { + User.find({include: ['posts', 'passports']}, function(err, users) { should.not.exist(err); should.exist(users); users.length.should.be.ok; @@ -582,9 +582,9 @@ describe('include', function() { it('should not make n+1 db calls in relation syntax', function(done) { var self = this; - User.find({ include: [{ relation: 'posts', scope: { - where: { title: 'Post A' }, - }}, 'passports'] }, function(err, users) { + User.find({include: [{relation: 'posts', scope: { + where: {title: 'Post A'}, + }}, 'passports']}, function(err, users) { should.not.exist(err); should.exist(users); users.length.should.be.ok; @@ -619,22 +619,22 @@ describe('include', function() { }); it('should support disableInclude for hasAndBelongsToMany', function() { - var Patient = db.define('Patient', { name: String }); - var Doctor = db.define('Doctor', { name: String }); + var Patient = db.define('Patient', {name: String}); + var Doctor = db.define('Doctor', {name: String}); var DoctorPatient = db.define('DoctorPatient'); Doctor.hasAndBelongsToMany('patients', { model: 'Patient', - options: { disableInclude: true }, + options: {disableInclude: true}, }); var doctor; return db.automigrate(['Patient', 'Doctor', 'DoctorPatient']).then(function() { - return Doctor.create({ name: 'Who' }); + return Doctor.create({name: 'Who'}); }).then(function(inst) { doctor = inst; - return doctor.patients.create({ name: 'Lazarus' }); + return doctor.patients.create({name: 'Lazarus'}); }).then(function() { - return Doctor.find({ include: ['patients'] }); + return Doctor.find({include: ['patients']}); }).then(function(list) { list.should.have.length(1); list[0].toJSON().should.not.have.property('patients'); @@ -664,16 +664,16 @@ function setup(done) { title: String, }); - Passport.belongsTo('owner', { model: User }); - User.hasMany('passports', { foreignKey: 'ownerId' }); - User.hasMany('posts', { foreignKey: 'userId' }); + Passport.belongsTo('owner', {model: User}); + User.hasMany('passports', {foreignKey: 'ownerId'}); + User.hasMany('posts', {foreignKey: 'userId'}); User.hasMany('accesstokens', { foreignKey: 'userId', - options: { disableInclude: true }, + options: {disableInclude: true}, }); - Profile.belongsTo('user', { model: User }); - User.hasOne('profile', { foreignKey: 'userId' }); - Post.belongsTo('author', { model: User, foreignKey: 'userId' }); + Profile.belongsTo('user', {model: User}); + User.hasOne('profile', {foreignKey: 'userId'}); + Post.belongsTo('author', {model: User, foreignKey: 'userId'}); Assembly = db.define('Assembly', { name: String, @@ -696,11 +696,11 @@ function setup(done) { clearAndCreate( User, [ - { name: 'User A', age: 21 }, - { name: 'User B', age: 22 }, - { name: 'User C', age: 23 }, - { name: 'User D', age: 24 }, - { name: 'User E', age: 25 }, + {name: 'User A', age: 21}, + {name: 'User B', age: 22}, + {name: 'User C', age: 23}, + {name: 'User D', age: 24}, + {name: 'User E', age: 25}, ], function(items) { createdUsers = items; @@ -714,8 +714,8 @@ function setup(done) { clearAndCreate( AccessToken, [ - { token: '1', userId: createdUsers[0].id }, - { token: '2', userId: createdUsers[1].id }, + {token: '1', userId: createdUsers[0].id}, + {token: '2', userId: createdUsers[1].id}, ], function(items) {} ); @@ -725,10 +725,10 @@ function setup(done) { clearAndCreate( Passport, [ - { number: '1', ownerId: createdUsers[0].id }, - { number: '2', ownerId: createdUsers[1].id }, - { number: '3' }, - { number: '4', ownerId: createdUsers[2].id }, + {number: '1', ownerId: createdUsers[0].id}, + {number: '2', ownerId: createdUsers[1].id}, + {number: '3'}, + {number: '4', ownerId: createdUsers[2].id}, ], function(items) { createdPassports = items; @@ -741,9 +741,9 @@ function setup(done) { clearAndCreate( Profile, [ - { profileName: 'Profile A', userId: createdUsers[0].id }, - { profileName: 'Profile B', userId: createdUsers[1].id }, - { profileName: 'Profile Z' }, + {profileName: 'Profile A', userId: createdUsers[0].id}, + {profileName: 'Profile B', userId: createdUsers[1].id}, + {profileName: 'Profile Z'}, ], function(items) { createdProfiles = items; @@ -756,11 +756,11 @@ function setup(done) { clearAndCreate( Post, [ - { title: 'Post A', userId: createdUsers[0].id }, - { title: 'Post B', userId: createdUsers[0].id }, - { title: 'Post C', userId: createdUsers[0].id }, - { title: 'Post D', userId: createdUsers[1].id }, - { title: 'Post E' }, + {title: 'Post A', userId: createdUsers[0].id}, + {title: 'Post B', userId: createdUsers[0].id}, + {title: 'Post C', userId: createdUsers[0].id}, + {title: 'Post D', userId: createdUsers[1].id}, + {title: 'Post E'}, ], function(items) { createdPosts = items; @@ -796,7 +796,7 @@ describe('Model instance with included relation .toJSON()', function() { var db, ChallengerModel, GameParticipationModel, ResultModel; before(function(done) { - db = new DataSource({ connector: 'memory' }); + db = new DataSource({connector: 'memory'}); ChallengerModel = db.createModel('Challenger', { name: String, @@ -852,25 +852,25 @@ describe('Model instance with included relation .toJSON()', function() { }); function createChallengers(callback) { - ChallengerModel.create([{ name: 'challenger1' }, { name: 'challenger2' }], callback); + ChallengerModel.create([{name: 'challenger1'}, {name: 'challenger2'}], callback); } function createGameParticipations(challengers, callback) { GameParticipationModel.create([ - { challengerId: challengers[0].id, date: Date.now() }, - { challengerId: challengers[0].id, date: Date.now() }, + {challengerId: challengers[0].id, date: Date.now()}, + {challengerId: challengers[0].id, date: Date.now()}, ], callback); } function createResults(gameParticipations, callback) { ResultModel.create([ - { gameParticipationId: gameParticipations[0].id, points: 10 }, - { gameParticipationId: gameParticipations[0].id, points: 20 }, + {gameParticipationId: gameParticipations[0].id, points: 10}, + {gameParticipationId: gameParticipations[0].id, points: 20}, ], callback); } it('should recursively serialize objects', function(done) { - var filter = { include: { gameParticipations: 'results' }}; + var filter = {include: {gameParticipations: 'results'}}; ChallengerModel.find(filter, function(err, challengers) { var levelOneInclusion = challengers[0].toJSON().gameParticipations[0]; assert(levelOneInclusion.__data === undefined, '.__data of a level 1 inclusion is undefined.'); diff --git a/test/include_util.test.js b/test/include_util.test.js index 8e3fda00..b9388f5e 100644 --- a/test/include_util.test.js +++ b/test/include_util.test.js @@ -14,8 +14,8 @@ describe('include_util', function() { describe('#buildOneToOneIdentityMapWithOrigKeys', function() { it('should return an object with keys', function() { var objs = [ - { id: 11, letter: 'A' }, - { id: 22, letter: 'B' }, + {id: 11, letter: 'A'}, + {id: 22, letter: 'B'}, ]; var result = includeUtils.buildOneToOneIdentityMapWithOrigKeys(objs, 'id'); result.get(11).should.be.ok; @@ -24,10 +24,10 @@ describe('include_util', function() { it('should overwrite keys in case of collision', function() { var objs = [ - { id: 11, letter: 'A' }, - { id: 22, letter: 'B' }, - { id: 33, letter: 'C' }, - { id: 11, letter: 'HA!' }, + {id: 11, letter: 'A'}, + {id: 22, letter: 'B'}, + {id: 33, letter: 'C'}, + {id: 11, letter: 'HA!'}, ]; var result = includeUtils.buildOneToOneIdentityMapWithOrigKeys(objs, 'id'); @@ -41,8 +41,8 @@ describe('include_util', function() { describe('#buildOneToOneIdentityMapWithOrigKeys', function() { it('should return an object with keys', function() { var objs = [ - { id: 11, letter: 'A' }, - { id: 22, letter: 'B' }, + {id: 11, letter: 'A'}, + {id: 22, letter: 'B'}, ]; var result = includeUtils.buildOneToOneIdentityMapWithOrigKeys(objs, 'id'); result.get(11).should.be.ok; @@ -53,8 +53,8 @@ describe('include_util', function() { describe('#buildOneToManyIdentityMap', function() { it('should return an object with keys', function() { var objs = [ - { id: 11, letter: 'A' }, - { id: 22, letter: 'B' }, + {id: 11, letter: 'A'}, + {id: 22, letter: 'B'}, ]; var result = includeUtils.buildOneToManyIdentityMapWithOrigKeys(objs, 'id'); result.exist(11).should.be.true; @@ -63,10 +63,10 @@ describe('include_util', function() { it('should collect keys in case of collision', function() { var objs = [ - { fk_id: 11, letter: 'A' }, - { fk_id: 22, letter: 'B' }, - { fk_id: 33, letter: 'C' }, - { fk_id: 11, letter: 'HA!' }, + {fk_id: 11, letter: 'A'}, + {fk_id: 22, letter: 'B'}, + {fk_id: 33, letter: 'C'}, + {fk_id: 11, letter: 'HA!'}, ]; var result = includeUtils.buildOneToManyIdentityMapWithOrigKeys(objs, 'fk_id'); @@ -92,11 +92,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/introspection.test.js b/test/introspection.test.js index 41979872..84dc40ea 100644 --- a/test/introspection.test.js +++ b/test/introspection.test.js @@ -23,8 +23,8 @@ var json = { }, friends: ['John', 'Mary'], emails: [ - { label: 'work', id: 'x@sample.com' }, - { label: 'home', id: 'x@home.com' }, + {label: 'work', id: 'x@sample.com'}, + {label: 'home', id: 'x@home.com'}, ], tags: [], }; @@ -59,7 +59,7 @@ describe('Introspection of model definitions from JSON', function() { }); it('should return a schema for object', function() { - var json = { a: 'str', b: 0, c: true }; + var json = {a: 'str', b: 0, c: true}; var type = introspectType(json); assert.equal(type.a, 'string'); assert.equal(type.b, 'number'); @@ -67,7 +67,7 @@ describe('Introspection of model definitions from JSON', function() { }); it('should handle nesting objects', function() { - var json = { a: 'str', b: 0, c: true, d: { x: 10, y: 5 }}; + var json = {a: 'str', b: 0, c: true, d: {x: 10, y: 5}}; var type = introspectType(json); assert.equal(type.a, 'string'); assert.equal(type.b, 'number'); @@ -77,7 +77,7 @@ describe('Introspection of model definitions from JSON', function() { }); it('should handle nesting arrays', function() { - var json = { a: 'str', b: 0, c: true, d: [1, 2] }; + var json = {a: 'str', b: 0, c: true, d: [1, 2]}; var type = introspectType(json); assert.equal(type.a, 'string'); assert.equal(type.b, 'number'); @@ -91,7 +91,7 @@ describe('Introspection of model definitions from JSON', function() { var schema = introspectType(json); var builder = new ModelBuilder(); - var Model = builder.define('MyModel', schema, { idInjection: false }); + var Model = builder.define('MyModel', schema, {idInjection: false}); // FIXME: [rfeng] The constructor mutates the arguments var obj = new Model(json); @@ -106,7 +106,7 @@ describe('Introspection of model definitions from JSON', function() { var copy = traverse(json).clone(); var builder = new ModelBuilder(); - var Model = builder.buildModelFromInstance('MyModel', copy, { idInjection: false }); + var Model = builder.buildModelFromInstance('MyModel', copy, {idInjection: false}); var obj = new Model(json); obj = obj.toObject(); @@ -119,7 +119,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..9a8278f1 100644 --- a/test/json.test.js +++ b/test/json.test.js @@ -14,7 +14,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 +30,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..ba40c23b 100644 --- a/test/kv-memory.js +++ b/test/kv-memory.js @@ -3,7 +3,7 @@ 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 6e1481a1..66bbca21 100644 --- a/test/kvao/get-set.suite.js +++ b/test/kvao/get-set.suite.js @@ -31,9 +31,9 @@ module.exports = function(dataSourceFactory, connectorCapabilities) { }); it('works for Object values', function() { - return CacheItem.set('a-key', { a: 1, b: 2 }) + return CacheItem.set('a-key', {a: 1, b: 2}) .then(function() { return CacheItem.get('a-key'); }) - .then(function(value) { value.should.eql({ a: 1, b: 2 }); }); + .then(function(value) { value.should.eql({a: 1, b: 2}); }); }); it('works for Buffer values', function() { @@ -70,7 +70,7 @@ module.exports = function(dataSourceFactory, connectorCapabilities) { }); it('honours options.ttl', function() { - return Promise.resolve(CacheItem.set('a-key', 'a-value', { ttl: TTL_PRECISION })) + return Promise.resolve(CacheItem.set('a-key', 'a-value', {ttl: TTL_PRECISION})) .delay(2 * TTL_PRECISION) .then(function() { return CacheItem.get('a-key'); }) .then(function(value) { should.equal(value, null); }); @@ -92,7 +92,7 @@ module.exports = function(dataSourceFactory, connectorCapabilities) { }); it('resets TTL timer', function() { - return Promise.resolve(CacheItem.set('a-key', 'a-value', { ttl: TTL_PRECISION })) + return Promise.resolve(CacheItem.set('a-key', 'a-value', {ttl: TTL_PRECISION})) .then(function() { return CacheItem.set('a-key', 'another-value'); // no TTL }) diff --git a/test/kvao/keys.suite.js b/test/kvao/keys.suite.js index 6b197b23..a571ae87 100644 --- a/test/kvao/keys.suite.js +++ b/test/kvao/keys.suite.js @@ -87,19 +87,19 @@ module.exports = function(dataSourceFactory, connectorCapabilities) { }); it('supports "?" operator', function() { - return CacheItem.sortedKeys({ match: 'h?llo' }).then(function(keys) { + return CacheItem.sortedKeys({match: 'h?llo'}).then(function(keys) { should(keys).eql(['hallo', 'hello', 'hxllo']); }); }); it('supports "*" operator', function() { - return CacheItem.sortedKeys({ match: 'h*llo' }).then(function(keys) { + return CacheItem.sortedKeys({match: 'h*llo'}).then(function(keys) { should(keys).eql(['hallo', 'heeello', 'hello', 'hllo', 'hxllo']); }); }); it('handles no matches found', function() { - return CacheItem.sortedKeys({ match: 'not-found' }) + return CacheItem.sortedKeys({match: 'not-found'}) .then(function(keys) { should(keys).eql([]); }); diff --git a/test/kvao/ttl.suite.js b/test/kvao/ttl.suite.js index 4e028f4d..e772c98a 100644 --- a/test/kvao/ttl.suite.js +++ b/test/kvao/ttl.suite.js @@ -28,7 +28,7 @@ module.exports = function(dataSourceFactory, connectorCapabilities) { it('gets TTL when key with unexpired TTL exists - Promise API', function() { return Promise.resolve( - CacheItem.set('a-key', 'a-value', { ttl: INITIAL_TTL })) + CacheItem.set('a-key', 'a-value', {ttl: INITIAL_TTL})) .delay(SMALL_DELAY) .then(function() { return CacheItem.ttl('a-key'); }) .then(function(ttl) { ttl.should.be.within(1, INITIAL_TTL); }); @@ -36,7 +36,7 @@ module.exports = function(dataSourceFactory, connectorCapabilities) { it('gets TTL when key with unexpired TTL exists - Callback API', function(done) { - CacheItem.set('a-key', 'a-value', { ttl: INITIAL_TTL }, function(err) { + CacheItem.set('a-key', 'a-value', {ttl: INITIAL_TTL}, function(err) { if (err) return done(err); CacheItem.ttl('a-key', function(err, ttl) { if (err) return done(err); @@ -54,7 +54,7 @@ module.exports = function(dataSourceFactory, connectorCapabilities) { it('fails when getting TTL for a key with expired TTL', function() { return Promise.resolve( - CacheItem.set('expired-key', 'a-value', { ttl: TTL_PRECISION })) + CacheItem.set('expired-key', 'a-value', {ttl: TTL_PRECISION})) .delay(2 * TTL_PRECISION) .then(function() { return CacheItem.ttl('expired-key'); diff --git a/test/loopback-dl.test.js b/test/loopback-dl.test.js index 74d31a66..27117561 100644 --- a/test/loopback-dl.test.js +++ b/test/loopback-dl.test.js @@ -32,7 +32,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'); @@ -46,9 +46,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'); @@ -63,9 +63,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'; @@ -87,10 +87,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'); @@ -101,9 +101,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'); @@ -116,9 +116,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'; @@ -143,7 +143,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'); @@ -189,9 +189,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'], }); @@ -218,11 +218,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 @@ -236,7 +236,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); @@ -250,14 +250,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}); }); }); @@ -283,7 +283,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; @@ -299,13 +299,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 @@ -313,11 +313,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 @@ -325,49 +325,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); @@ -389,9 +389,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); @@ -429,9 +429,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'); assert(user.name === 'Joe'); @@ -446,10 +446,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'); @@ -460,8 +460,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']); @@ -471,10 +471,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'); user.should.have.property('age', 20); @@ -495,7 +495,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'); user.should.have.property('name', 'Joe'); @@ -509,9 +509,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'); @@ -527,10 +527,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'); @@ -542,7 +542,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) { @@ -555,9 +555,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'); @@ -575,12 +575,12 @@ describe('DataSource define model', function() { it('should update the instance with unknown properties', function(done) { 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}, }); - 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); @@ -602,7 +602,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(); }); @@ -610,7 +610,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(); }); @@ -618,15 +618,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(); }); @@ -634,8 +634,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'); }); @@ -643,8 +643,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'); }); @@ -654,14 +654,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); @@ -670,7 +670,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); } @@ -679,9 +679,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); @@ -690,10 +690,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'); @@ -706,21 +706,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'); @@ -729,14 +729,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); @@ -754,8 +754,8 @@ 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], }); }); @@ -765,7 +765,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); @@ -786,7 +786,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; @@ -810,7 +810,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); @@ -830,7 +830,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); @@ -851,7 +851,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); @@ -872,7 +872,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); @@ -995,11 +995,11 @@ 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 Post = ds.define('Post', {userId: Number, content: String}); var User = ds.define( 'User', - { name: String }, - { relations: { posts: { type: 'hasMany', model: 'Post' }}} + {name: String}, + {relations: {posts: {type: 'hasMany', model: 'Post'}}} ); assert(User.relations['posts']); @@ -1009,11 +1009,11 @@ 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 User = ds.define('User', {name: String}); var Post = ds.define( 'Post', - { userId: Number, content: String }, - { relations: { user: { type: 'belongsTo', model: 'User' }}} + {userId: Number, content: String}, + {relations: {user: {type: 'belongsTo', model: 'User'}}} ); assert(Post.relations['user']); @@ -1023,11 +1023,11 @@ 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 Post = ds.define('Post', {userId: Number, content: String}); var User = ds.define( 'User', - { name: String }, - { relations: { posts: { type: 'referencesMany', model: 'Post' }}} + {name: String}, + {relations: {posts: {type: 'referencesMany', model: 'Post'}}} ); assert(User.relations['posts']); @@ -1037,11 +1037,11 @@ 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 Post = ds.define('Post', {userId: Number, content: String}); var User = ds.define( 'User', - { name: String }, - { relations: { posts: { type: 'embedsMany', model: 'Post' }}} + {name: String}, + {relations: {posts: {type: 'embedsMany', model: 'Post'}}} ); assert(User.relations['posts']); @@ -1051,11 +1051,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']); @@ -1097,12 +1097,12 @@ describe('Load models with relations', function() { var User = ds.define( 'User', - { name: String, id: { type: String, id: true }} + {name: String, id: {type: String, id: true}} ); var Post = ds.define( 'Post', - { content: String }, - { relations: { user: { type: 'belongsTo', model: 'User' }}} + {content: String}, + {relations: {user: {type: 'belongsTo', model: 'User'}}} ); var fk = Post.definition.properties['userId']; @@ -1117,7 +1117,7 @@ describe('Load models with relations', function() { var User = ds.define( 'User', - { name: String }, + {name: String}, { relations: { posts: { @@ -1137,14 +1137,14 @@ describe('Load models with relations', function() { var Post = ds.define( 'Post', - { userId: Number, content: String }, - { relations: { user: { type: 'belongsTo', model: 'User' }}} + {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' }}} + {userId: Number, type: String}, + {relations: {user: {type: 'belongsTo', model: 'User'}}} ); assert(Post.relations['user']); @@ -1184,13 +1184,13 @@ 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' }}} + {name: String}, + {relations: {posts: {model: 'Post'}}} ); } catch (e) { done(); @@ -1200,13 +1200,13 @@ 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' }}} + {name: String}, + {relations: {posts: {type: 'hasXYZ', model: 'Post'}}} ); } catch (e) { done(); @@ -1217,17 +1217,17 @@ describe('Load models with relations', function() { var ds = new DataSource('memory'); var Physician = ds.createModel('Physician', { name: String, - }, { relations: { patients: { model: 'Patient', type: 'hasMany', through: 'Appointment' }}}); + }, {relations: {patients: {model: 'Patient', type: 'hasMany', through: 'Appointment'}}}); var Patient = ds.createModel('Patient', { name: String, - }, { relations: { physicians: { model: 'Physician', type: 'hasMany', through: 'Appointment' }}}); + }, {relations: {physicians: {model: 'Physician', type: 'hasMany', through: 'Appointment'}}}); assert(!Physician.relations['patients']); // Appointment hasn't been resolved yet assert(!Patient.relations['physicians']); // Appointment hasn't been resolved yet var Appointment = ds.createModel('Appointment', - { physicianId: Number, patientId: Number, appointmentDate: Date }, + {physicianId: Number, patientId: Number, appointmentDate: Date}, { relations: { patient: { @@ -1250,7 +1250,7 @@ describe('Load models with relations', function() { it('should handle hasMany through options', function(done) { var ds = new DataSource('memory'); var Physician = ds.createModel('Physician', - { name: String }, + {name: String}, { relations: { patients: { @@ -1263,7 +1263,7 @@ describe('Load models with relations', function() { } ); var Patient = ds.createModel('Patient', - { name: String }, + {name: String}, { relations: { physicians: { @@ -1276,7 +1276,7 @@ describe('Load models with relations', function() { } ); var Appointment = ds.createModel('Appointment', - { physicianId: Number, patientId: Number, appointmentDate: Date }, + {physicianId: Number, patientId: Number, appointmentDate: Date}, { relations: { patient: { @@ -1300,11 +1300,11 @@ 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 Post = modelBuilder.define('Post', {userId: Number, content: String}); var User = modelBuilder.define( 'User', - { name: String }, - { relations: { posts: { type: 'hasMany', model: 'Post' }}} + {name: String}, + {relations: {posts: {type: 'hasMany', model: 'Post'}}} ); assert(!User.relations['posts']); @@ -1318,12 +1318,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); @@ -1348,7 +1348,7 @@ describe('DataAccessObject', function() { 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, @@ -1362,10 +1362,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) { @@ -1376,72 +1376,72 @@ 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() { @@ -1458,7 +1458,7 @@ describe('DataAccessObject', function() { try { // The where clause cannot be an array model._coerce([ - { vip: true }, + {vip: true}, ]); } catch (err) { error = err; @@ -1469,7 +1469,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; } @@ -1479,7 +1479,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; } @@ -1489,7 +1489,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; } @@ -1510,7 +1510,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; } @@ -1520,7 +1520,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; } @@ -1530,7 +1530,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; } @@ -1540,7 +1540,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; } @@ -1550,7 +1550,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; } @@ -1558,56 +1558,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 @@ -1655,7 +1655,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'); @@ -1692,7 +1692,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); }); @@ -1708,7 +1708,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); }); @@ -1723,9 +1723,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'); @@ -1779,7 +1779,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: [ @@ -1860,12 +1860,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'); }); }); @@ -1874,7 +1874,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, }}); @@ -1884,7 +1884,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', }}); @@ -1894,7 +1894,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 d31a0a7c..9352e5cb 100644 --- a/test/manipulation.test.js +++ b/test/manipulation.test.js @@ -20,10 +20,10 @@ describe('manipulation', function() { name: String, gender: String, married: Boolean, - age: { type: Number, index: true }, + age: {type: Number, index: true}, dob: Date, - createdAt: { type: Date, default: Date }, - }, { forceId: true, strict: true }); + createdAt: {type: Date, default: Date}, + }, {forceId: true, strict: true}); db.automigrate(['Person'], done); }); @@ -33,7 +33,7 @@ describe('manipulation', function() { // For the purpose of the tests, we use a counter instead of a hash fn. var StubUser; before(function setupStubUserModel(done) { - StubUser = db.createModel('StubUser', { password: String }, { forceId: true }); + StubUser = db.createModel('StubUser', {password: String}, {forceId: true}); StubUser.setter.password = function(plain) { var hashed = false; if (!plain) return; @@ -59,7 +59,7 @@ describe('manipulation', function() { }); it('should create instance', function(done) { - Person.create({ name: 'Anatoliy' }, function(err, p) { + Person.create({name: 'Anatoliy'}, function(err, p) { p.name.should.equal('Anatoliy'); should.not.exist(err); should.exist(p); @@ -72,7 +72,7 @@ describe('manipulation', function() { }); it('should create instance (promise variant)', function(done) { - Person.create({ name: 'Anatoliy' }) + Person.create({name: 'Anatoliy'}) .then (function(p) { p.name.should.equal('Anatoliy'); should.exist(p); @@ -87,7 +87,7 @@ describe('manipulation', function() { }); it('should instantiate an object', function(done) { - var p = new Person({ name: 'Anatoliy' }); + var p = new Person({name: 'Anatoliy'}); p.name.should.equal('Anatoliy'); p.isNewRecord().should.be.true; p.save(function(err, inst) { @@ -99,7 +99,7 @@ describe('manipulation', function() { }); it('should instantiate an object (promise variant)', function(done) { - var p = new Person({ name: 'Anatoliy' }); + var p = new Person({name: 'Anatoliy'}); p.name.should.equal('Anatoliy'); p.isNewRecord().should.be.true; p.save() @@ -122,7 +122,7 @@ describe('manipulation', function() { }); it('should not allow user-defined value for the id of object - create', function(done) { - Person.create({ id: 123456 }, function(err, p) { + Person.create({id: 123456}, function(err, p) { err.should.be.instanceof(ValidationError); err.statusCode.should.equal(422); err.details.messages.id.should.eql(['can\'t be set']); @@ -134,7 +134,7 @@ describe('manipulation', function() { }); it('should not allow user-defined value for the id of object - create (promise variant)', function(done) { - Person.create({ id: 123456 }) + Person.create({id: 123456}) .then (function(p) { done(new Error('Person.create should have failed.')); }, function(err) { @@ -147,7 +147,7 @@ describe('manipulation', function() { }); it('should not allow user-defined value for the id of object - save', function(done) { - var p = new Person({ id: 123456 }); + var p = new Person({id: 123456}); p.isNewRecord().should.be.true; p.save(function(err, inst) { err.should.be.instanceof(ValidationError); @@ -160,7 +160,7 @@ describe('manipulation', function() { }); it('should not allow user-defined value for the id of object - save (promise variant)', function(done) { - var p = new Person({ id: 123456 }); + var p = new Person({id: 123456}); p.isNewRecord().should.be.true; p.save() .then (function(inst) { @@ -183,7 +183,7 @@ describe('manipulation', function() { next(); setTimeout(done, 10); }; - Person.create({ name: 'Nickolay' }); + Person.create({name: 'Nickolay'}); }); it('should create instance with blank data', function(done) { @@ -227,8 +227,8 @@ describe('manipulation', function() { it('should create batch of objects', function(done) { var batch = [ - { name: 'Shaltay' }, - { name: 'Boltay' }, + {name: 'Shaltay'}, + {name: 'Boltay'}, {}, ]; Person.create(batch, function(e, ps) { @@ -257,14 +257,14 @@ describe('manipulation', function() { it('should create batch of objects with beforeCreate', function(done) { Person.beforeCreate = function(next, data) { if (data && data.name === 'A') { - return next(null, { id: 'a', name: 'A' }); + return next(null, {id: 'a', name: 'A'}); } else { return next(); } }; var batch = [ - { name: 'A' }, - { name: 'B' }, + {name: 'A'}, + {name: 'B'}, undefined, ]; Person.create(batch, function(e, ps) { @@ -272,14 +272,14 @@ describe('manipulation', function() { should.exist(ps); ps.should.be.instanceOf(Array); ps.should.have.lengthOf(batch.length); - ps[0].should.be.eql({ id: 'a', name: 'A' }); + ps[0].should.be.eql({id: 'a', name: 'A'}); done(); }); }); it('should preserve properties with "undefined" value', function(done) { Person.create( - { name: 'a-name', gender: undefined }, + {name: 'a-name', gender: undefined}, function(err, created) { if (err) return done(err); created.toObject().should.have.properties({ @@ -305,13 +305,13 @@ describe('manipulation', function() { it('should refuse to create object with duplicate id', function(done) { // NOTE(bajtos) We cannot reuse Person model here, // `settings.forceId` aborts the CREATE request at the validation step. - var Product = db.define('ProductTest', { name: String }); + var Product = db.define('ProductTest', {name: String}); db.automigrate('ProductTest', function(err) { if (err) return done(err); - Product.create({ name: 'a-name' }, function(err, p) { + Product.create({name: 'a-name'}, function(err, p) { if (err) return done(err); - Product.create({ id: p.id, name: 'duplicate' }, function(err) { + Product.create({id: p.id, name: 'duplicate'}, function(err) { if (!err) { return done(new Error('Create should have rejected duplicate id.')); } @@ -385,7 +385,7 @@ describe('manipulation', function() { p.name = 'Nana'; p.save(function(err) { should.exist(err); - p.save({ validate: false }, function(err) { + p.save({validate: false}, function(err) { should.not.exist(err); done(); }); @@ -406,7 +406,7 @@ describe('manipulation', function() { done(new Error('save should have failed.')); }, function(err) { should.exist(err); - p.save({ validate: false }) + p.save({validate: false}) .then(function(d) { should.exist(d); done(); @@ -434,7 +434,7 @@ describe('manipulation', function() { it('should preserve properties with dynamic setters', function(done) { // This test reproduces a problem discovered by LoopBack unit-test // "User.hasPassword() should match a password after it is changed" - StubUser.create({ password: 'foo' }, function(err, created) { + StubUser.create({password: 'foo'}, function(err, created) { if (err) return done(err); created.password = 'bar'; created.save(function(err, saved) { @@ -455,7 +455,7 @@ describe('manipulation', function() { before(function(done) { Person.destroyAll(function() { - Person.create({ name: 'Mary', age: 15 }, function(err, p) { + Person.create({name: 'Mary', age: 15}, function(err, p) { if (err) return done(err); person = p; done(); @@ -470,7 +470,7 @@ describe('manipulation', function() { it('should have updated password hashed with updateAttribute', function(done) { - StubUser.create({ password: 'foo' }, function(err, created) { + StubUser.create({password: 'foo'}, function(err, created) { if (err) return done(err); created.updateAttribute('password', 'test', function(err, created) { if (err) return done(err); @@ -509,7 +509,7 @@ describe('manipulation', function() { }); it('should ignore undefined values on updateAttributes', function(done) { - person.updateAttributes({ 'name': 'John', age: undefined }, + person.updateAttributes({'name': 'John', age: undefined}, function(err, p) { if (err) return done(err); Person.findById(p.id, function(e, p) { @@ -525,7 +525,7 @@ describe('manipulation', function() { // Using {foo: 'bar'} only causes dependent test failures due to the // stripping of object properties when in strict mode (ie. {foo: 'bar'} // changes to '{}' and breaks other tests - person.updateAttributes({ name: 'John', foo: 'bar' }, + person.updateAttributes({name: 'John', foo: 'bar'}, function(err, p) { if (err) return done(err); should.not.exist(p.foo); @@ -540,7 +540,7 @@ describe('manipulation', function() { it('should throw error on unknown attributes when strict: throw', function(done) { Person.definition.settings.strict = 'throw'; Person.findById(person.id, function(err, p) { - p.updateAttributes({ foo: 'bar' }, + p.updateAttributes({foo: 'bar'}, function(err, p) { should.exist(err); err.name.should.equal('Error'); @@ -558,7 +558,7 @@ describe('manipulation', function() { it('should throw error on unknown attributes when strict: throw', function(done) { Person.definition.settings.strict = 'validate'; Person.findById(person.id, function(err, p) { - p.updateAttributes({ foo: 'bar' }, + p.updateAttributes({foo: 'bar'}, function(err, p) { should.exist(err); err.name.should.equal('ValidationError'); @@ -573,7 +573,7 @@ describe('manipulation', function() { }); it('should allow same id value on updateAttributes', function(done) { - person.updateAttributes({ id: person.id, name: 'John' }, + person.updateAttributes({id: person.id, name: 'John'}, function(err, p) { if (err) return done(err); Person.findById(p.id, function(e, p) { @@ -592,7 +592,7 @@ describe('manipulation', function() { // For example MongoDB ObjectId pid = person.id.toString(); } - person.updateAttributes({ id: pid, name: 'John' }, + person.updateAttributes({id: pid, name: 'John'}, function(err, p) { if (err) return done(err); Person.findById(p.id, function(e, p) { @@ -606,7 +606,7 @@ describe('manipulation', function() { it('should fail if an id value is to be changed on updateAttributes', function(done) { - person.updateAttributes({ id: person.id + 1, name: 'John' }, + person.updateAttributes({id: person.id + 1, name: 'John'}, function(err, p) { should.exist(err); done(); @@ -614,7 +614,7 @@ describe('manipulation', function() { }); it('should allow model instance on updateAttributes', function(done) { - person.updateAttributes(new Person({ 'name': 'John', age: undefined }), + person.updateAttributes(new Person({'name': 'John', age: undefined}), function(err, p) { if (err) return done(err); Person.findById(p.id, function(e, p) { @@ -627,7 +627,7 @@ describe('manipulation', function() { }); it('should allow model instance on updateAttributes (promise variant)', function(done) { - person.updateAttributes(new Person({ 'name': 'Jane', age: undefined })) + person.updateAttributes(new Person({'name': 'Jane', age: undefined})) .then(function(p) { return Person.findById(p.id) .then(function(p) { @@ -646,7 +646,7 @@ describe('manipulation', function() { }, }; person.getConnector = function() { return fakeConnector; }; - person.updateAttributes({ name: 'John' }, function(err, p) { + person.updateAttributes({name: 'John'}, function(err, p) { should.exist(err); done(); }); @@ -659,8 +659,8 @@ describe('manipulation', function() { before('prepare "Post" model', function(done) { Post = ds.define('Post', { - title: { type: String, id: true }, - content: { type: String }, + title: {type: String, id: true}, + content: {type: String}, }); ds.automigrate('Post', done); }); @@ -670,7 +670,7 @@ describe('manipulation', function() { }); it('should preserve properties with dynamic setters on create', function(done) { - StubUser.updateOrCreate({ password: 'foo' }, function(err, created) { + StubUser.updateOrCreate({password: 'foo'}, function(err, created) { if (err) return done(err); created.password.should.equal('foo-FOO'); StubUser.findById(created.id, function(err, found) { @@ -682,9 +682,9 @@ describe('manipulation', function() { }); it('should preserve properties with dynamic setters on update', function(done) { - StubUser.create({ password: 'foo' }, function(err, created) { + StubUser.create({password: 'foo'}, function(err, created) { if (err) return done(err); - var data = { id: created.id, password: 'bar' }; + var data = {id: created.id, password: 'bar'}; StubUser.updateOrCreate(data, function(err, updated) { if (err) return done(err); updated.password.should.equal('bar-BAR'); @@ -699,7 +699,7 @@ describe('manipulation', function() { it('should preserve properties with "undefined" value', function(done) { Person.create( - { name: 'a-name', gender: undefined }, + {name: 'a-name', gender: undefined}, function(err, instance) { if (err) return done(err); instance.toObject().should.have.properties({ @@ -709,7 +709,7 @@ describe('manipulation', function() { }); Person.updateOrCreate( - { id: instance.id, name: 'updated name' }, + {id: instance.id, name: 'updated name'}, function(err, updated) { if (err) return done(err); var result = updated.toObject(); @@ -725,8 +725,8 @@ describe('manipulation', function() { it.skip('updates specific instances when PK is not an auto-generated id', function(done) { Post.create([ - { title: 'postA', content: 'contentA' }, - { title: 'postB', content: 'contentB' }, + {title: 'postA', content: 'contentA'}, + {title: 'postB', content: 'contentB'}, ], function(err, instance) { if (err) return done(err); @@ -756,7 +756,7 @@ describe('manipulation', function() { it('should allow save() of the created instance', function(done) { Person.updateOrCreate( - { id: 999 /* a new id */, name: 'a-name' }, + {id: 999 /* a new id */, name: 'a-name'}, function(err, inst) { if (err) return done(err); inst.save(done); @@ -772,15 +772,15 @@ describe('manipulation', function() { var ds = getSchema(); before(function(done) { Post = ds.define('Post', { - title: { type: String, length: 255, index: true }, - content: { type: String }, + title: {type: String, length: 255, index: true}, + content: {type: String}, comments: [String], }); ds.automigrate('Post', done); }); it('works without options on create (promise variant)', function(done) { - var post = { id: 123, title: 'a', content: 'AAA' }; + var post = {id: 123, title: 'a', content: 'AAA'}; Post.replaceOrCreate(post) .then(function(p) { should.exist(p); @@ -802,8 +802,8 @@ describe('manipulation', function() { }); it('works with options on create (promise variant)', function(done) { - var post = { id: 123, title: 'a', content: 'AAA' }; - Post.replaceOrCreate(post, { validate: false }) + var post = {id: 123, title: 'a', content: 'AAA'}; + Post.replaceOrCreate(post, {validate: false}) .then(function(p) { should.exist(p); p.should.be.instanceOf(Post); @@ -824,7 +824,7 @@ describe('manipulation', function() { }); it('works without options on update (promise variant)', function(done) { - var post = { title: 'a', content: 'AAA', comments: ['Comment1'] }; + var post = {title: 'a', content: 'AAA', comments: ['Comment1']}; Post.create(post) .then(function(created) { created = created.toObject(); @@ -854,14 +854,14 @@ describe('manipulation', function() { }); it('works with options on update (promise variant)', function(done) { - var post = { title: 'a', content: 'AAA', comments: ['Comment1'] }; + var post = {title: 'a', content: 'AAA', comments: ['Comment1']}; Post.create(post) .then(function(created) { created = created.toObject(); delete created.comments; delete created.content; created.title = 'b'; - return Post.replaceOrCreate(created, { validate: false }) + return Post.replaceOrCreate(created, {validate: false}) .then(function(p) { should.exist(p); p.should.be.instanceOf(Post); @@ -884,7 +884,7 @@ describe('manipulation', function() { }); it('works without options on update (callback variant)', function(done) { - Post.create({ title: 'a', content: 'AAA', comments: ['Comment1'] }, + Post.create({title: 'a', content: 'AAA', comments: ['Comment1']}, function(err, post) { if (err) return done(err); post = post.toObject(); @@ -912,8 +912,8 @@ describe('manipulation', function() { }); it('works with options on update (callback variant)', function(done) { - Post.create({ title: 'a', content: 'AAA', comments: ['Comment1'] }, - { validate: false }, + Post.create({title: 'a', content: 'AAA', comments: ['Comment1']}, + {validate: false}, function(err, post) { if (err) return done(err); post = post.toObject(); @@ -941,7 +941,7 @@ describe('manipulation', function() { }); it('works without options on create (callback variant)', function(done) { - var post = { id: 123, title: 'a', content: 'AAA' }; + var post = {id: 123, title: 'a', content: 'AAA'}; Post.replaceOrCreate(post, function(err, p) { if (err) return done(err); p.id.should.equal(post.id); @@ -960,8 +960,8 @@ describe('manipulation', function() { }); it('works with options on create (callback variant)', function(done) { - var post = { id: 123, title: 'a', content: 'AAA' }; - Post.replaceOrCreate(post, { validate: false }, function(err, p) { + var post = {id: 123, title: 'a', content: 'AAA'}; + Post.replaceOrCreate(post, {validate: false}, function(err, p) { if (err) return done(err); p.id.should.equal(post.id); p.should.not.have.property('_id'); @@ -989,15 +989,15 @@ describe('manipulation', function() { var ds = getSchema(); before(function(done) { Post = ds.define('Post', { - title: { type: String, length: 255, index: true }, - content: { type: String }, + title: {type: String, length: 255, index: true}, + content: {type: String}, comments: [String], }); ds.automigrate('Post', done); }); beforeEach(function(done) { Post.destroyAll(function() { - Post.create({ title: 'a', content: 'AAA' }, function(err, p) { + Post.create({title: 'a', content: 'AAA'}, function(err, p) { if (err) return done(err); postInstance = p; done(); @@ -1007,9 +1007,9 @@ describe('manipulation', function() { it('should have updated password hashed with replaceAttributes', function(done) { - StubUser.create({ password: 'foo' }, function(err, created) { + StubUser.create({password: 'foo'}, function(err, created) { if (err) return done(err); - created.replaceAttributes({ password: 'test' }, + created.replaceAttributes({password: 'test'}, function(err, created) { if (err) return done(err); created.password.should.equal('test-TEST'); @@ -1027,7 +1027,7 @@ describe('manipulation', function() { Post.findById(postInstance.id, function(err, p) { if (err) return done(err); changePostIdInHook('before save'); - p.replaceAttributes({ title: 'b' }, function(err, data) { + p.replaceAttributes({title: 'b'}, function(err, data) { data.id.should.eql(postInstance.id); if (err) return done(err); Post.find(function(err, p) { @@ -1045,7 +1045,7 @@ describe('manipulation', function() { Post.findById(postInstance.id, function(err, p) { if (err) return done(err); changePostIdInHook('before save'); - p.replaceAttributes({ title: 'b' }, function(err, data) { + p.replaceAttributes({title: 'b'}, function(err, data) { if (err) return done(err); Post._warned.cannotOverwritePKInBeforeSaveHook.should.equal(true); data.id.should.equal(postInstance.id); @@ -1059,7 +1059,7 @@ describe('manipulation', function() { Post.findById(postInstance.id, function(err, p) { if (err) return done(err); changePostIdInHook('loaded'); - p.replaceAttributes({ title: 'b' }, function(err, data) { + p.replaceAttributes({title: 'b'}, function(err, data) { data.id.should.eql(postInstance.id); if (err) return done(err); // clear observers to make sure `loaded` @@ -1077,7 +1077,7 @@ describe('manipulation', function() { it('works without options(promise variant)', function(done) { Post.findById(postInstance.id) .then(function(p) { - p.replaceAttributes({ title: 'b' }) + p.replaceAttributes({title: 'b'}) .then(function(p) { should.exist(p); p.should.be.instanceOf(Post); @@ -1097,7 +1097,7 @@ describe('manipulation', function() { it('works with options(promise variant)', function(done) { Post.findById(postInstance.id) .then(function(p) { - p.replaceAttributes({ title: 'b' }, { validate: false }) + p.replaceAttributes({title: 'b'}, {validate: false}) .then(function(p) { should.exist(p); p.should.be.instanceOf(Post); @@ -1117,7 +1117,7 @@ describe('manipulation', function() { it('should fail when changing id', function(done) { Post.findById(postInstance.id, function(err, p) { if (err) return done(err); - p.replaceAttributes({ title: 'b', id: 999 }, function(err, p) { + p.replaceAttributes({title: 'b', id: 999}, function(err, p) { should.exist(err); var expectedErrMsg = 'id property (id) cannot be updated from ' + postInstance.id + ' to 999'; err.message.should.equal(expectedErrMsg); @@ -1129,7 +1129,7 @@ describe('manipulation', function() { it('works without options(callback variant)', function(done) { Post.findById(postInstance.id, function(err, p) { if (err) return done(err); - p.replaceAttributes({ title: 'b' }, function(err, p) { + p.replaceAttributes({title: 'b'}, function(err, p) { if (err) return done(err); p.should.have.property('content', undefined); p.title.should.equal('b'); @@ -1141,7 +1141,7 @@ describe('manipulation', function() { it('works with options(callback variant)', function(done) { Post.findById(postInstance.id, function(err, p) { if (err) return done(err); - p.replaceAttributes({ title: 'b' }, { validate: false }, function(err, p) { + p.replaceAttributes({title: 'b'}, {validate: false}, function(err, p) { if (err) return done(err); p.should.have.property('content', undefined); p.title.should.equal('b'); @@ -1161,7 +1161,7 @@ describe('manipulation', function() { describe('findOrCreate', function() { it('should create a record with if new', function(done) { - Person.findOrCreate({ name: 'Zed', gender: 'male' }, + Person.findOrCreate({name: 'Zed', gender: 'male'}, function(err, p, created) { if (err) return done(err); should.exist(p); @@ -1175,8 +1175,8 @@ describe('manipulation', function() { it('should find a record if exists', function(done) { Person.findOrCreate( - { where: { name: 'Zed' }}, - { name: 'Zed', gender: 'male' }, + {where: {name: 'Zed'}}, + {name: 'Zed', gender: 'male'}, function(err, p, created) { if (err) return done(err); should.exist(p); @@ -1189,7 +1189,7 @@ describe('manipulation', function() { }); it('should create a record with if new (promise variant)', function(done) { - Person.findOrCreate({ name: 'Jed', gender: 'male' }) + Person.findOrCreate({name: 'Jed', gender: 'male'}) .then(function(res) { should.exist(res); res.should.be.instanceOf(Array); @@ -1207,8 +1207,8 @@ describe('manipulation', function() { it('should find a record if exists (promise variant)', function(done) { Person.findOrCreate( - { where: { name: 'Jed' }}, - { name: 'Jed', gender: 'male' }) + {where: {name: 'Jed'}}, + {name: 'Jed', gender: 'male'}) .then(function(res) { res.should.be.instanceOf(Array); res.should.have.lengthOf(2); @@ -1308,13 +1308,13 @@ describe('manipulation', function() { it('should only delete instances that satisfy the where condition', function(done) { - Person.deleteAll({ name: 'John' }, function(err, info) { + Person.deleteAll({name: 'John'}, function(err, info) { if (err) return done(err); info.should.have.property('count', 1); - Person.find({ where: { name: 'John' }}, function(err, data) { + Person.find({where: {name: 'John'}}, function(err, data) { if (err) return done(err); data.should.have.length(0); - Person.find({ where: { name: 'Jane' }}, function(err, data) { + Person.find({where: {name: 'Jane'}}, function(err, data) { if (err) return done(err); data.should.have.length(1); done(); @@ -1325,7 +1325,7 @@ describe('manipulation', function() { it('should report zero deleted instances when no matches are found', function(done) { - Person.deleteAll({ name: 'does-not-match' }, function(err, info) { + Person.deleteAll({name: 'does-not-match'}, function(err, info) { if (err) return done(err); info.should.have.property('count', 0); Person.count(function(err, count) { @@ -1440,7 +1440,7 @@ describe('manipulation', function() { it('should initialize object properly', function() { var hw = 'Hello word', now = Date.now(), - person = new Person({ name: hw }); + person = new Person({name: hw}); person.name.should.equal(hw); person.name = 'Goodbye, Lenin'; @@ -1453,7 +1453,7 @@ describe('manipulation', function() { before(function(done) { CustomModel = db.define('CustomModel1', { - createdAt: { type: Date, default: '$now' }, + createdAt: {type: Date, default: '$now'}, }); db.automigrate('CustomModel1', done); }); @@ -1477,7 +1477,7 @@ describe('manipulation', function() { before(function(done) { CustomModel = db.define('CustomModel2', { - now: { type: String, default: '$now' }, + now: {type: String, default: '$now'}, }); db.automigrate('CustomModel2', done); }); @@ -1499,7 +1499,7 @@ describe('manipulation', function() { before(function(done) { CustomModel = db.define('CustomModel3', { - now: { type: Date, defaultFn: 'now' }, + now: {type: Date, defaultFn: 'now'}, }); db.automigrate('CustomModel3', done); }); @@ -1521,7 +1521,7 @@ describe('manipulation', function() { before(function(done) { CustomModel = db.define('CustomModel4', { - guid: { type: String, defaultFn: 'guid' }, + guid: {type: String, defaultFn: 'guid'}, }); db.automigrate('CustomModel4', done); }); @@ -1540,7 +1540,7 @@ describe('manipulation', function() { before(function(done) { CustomModel = db.define('CustomModel5', { - guid: { type: String, defaultFn: 'uuid' }, + guid: {type: String, defaultFn: 'uuid'}, }); db.automigrate('CustomModel5', done); }); @@ -1559,7 +1559,7 @@ describe('manipulation', function() { before(function(done) { CustomModel = db.define('CustomModel5', { - guid: { type: String, defaultFn: 'uuidv4' }, + guid: {type: String, defaultFn: 'uuidv4'}, }); db.automigrate('CustomModel5', done); }); @@ -1588,7 +1588,7 @@ describe('manipulation', function() { function createModelWithShortId(cb) { ModelWithShortId = db.define('ModelWithShortId', { - shortid: { type: String, defaultFn: 'shortid' }, + shortid: {type: String, defaultFn: 'shortid'}, }); db.automigrate('ModelWithShortId', cb); } @@ -1603,67 +1603,67 @@ describe('manipulation', function() { describe('property value coercion', function() { it('should coerce boolean types properly', function() { - var p1 = new Person({ name: 'John', married: 'false' }); + var p1 = new Person({name: 'John', married: 'false'}); p1.married.should.equal(false); - p1 = new Person({ name: 'John', married: 'true' }); + p1 = new Person({name: 'John', married: 'true'}); p1.married.should.equal(true); - p1 = new Person({ name: 'John', married: '1' }); + p1 = new Person({name: 'John', married: '1'}); p1.married.should.equal(true); - p1 = new Person({ name: 'John', married: '0' }); + p1 = new Person({name: 'John', married: '0'}); p1.married.should.equal(false); - p1 = new Person({ name: 'John', married: true }); + p1 = new Person({name: 'John', married: true}); p1.married.should.equal(true); - p1 = new Person({ name: 'John', married: false }); + p1 = new Person({name: 'John', married: false}); p1.married.should.equal(false); - p1 = new Person({ name: 'John', married: 'null' }); + p1 = new Person({name: 'John', married: 'null'}); p1.married.should.equal(true); - p1 = new Person({ name: 'John', married: '' }); + p1 = new Person({name: 'John', married: ''}); p1.married.should.equal(false); - p1 = new Person({ name: 'John', married: 'X' }); + p1 = new Person({name: 'John', married: 'X'}); p1.married.should.equal(true); - p1 = new Person({ name: 'John', married: 0 }); + p1 = new Person({name: 'John', married: 0}); p1.married.should.equal(false); - p1 = new Person({ name: 'John', married: 1 }); + p1 = new Person({name: 'John', married: 1}); p1.married.should.equal(true); - p1 = new Person({ name: 'John', married: null }); + p1 = new Person({name: 'John', married: null}); p1.should.have.property('married', null); - p1 = new Person({ name: 'John', married: undefined }); + p1 = new Person({name: 'John', married: undefined}); p1.should.have.property('married', undefined); }); it('should coerce date types properly', function() { - var p1 = new Person({ name: 'John', dob: '2/1/2015' }); + var p1 = new Person({name: 'John', dob: '2/1/2015'}); p1.dob.should.eql(new Date('2/1/2015')); - p1 = new Person({ name: 'John', dob: '2/1/2015' }); + p1 = new Person({name: 'John', dob: '2/1/2015'}); p1.dob.should.eql(new Date('2/1/2015')); - p1 = new Person({ name: 'John', dob: '12' }); + p1 = new Person({name: 'John', dob: '12'}); p1.dob.should.eql(new Date('12')); - p1 = new Person({ name: 'John', dob: 12 }); + p1 = new Person({name: 'John', dob: 12}); p1.dob.should.eql(new Date(12)); - p1 = new Person({ name: 'John', dob: null }); + p1 = new Person({name: 'John', dob: null}); p1.should.have.property('dob', null); - p1 = new Person({ name: 'John', dob: undefined }); + p1 = new Person({name: 'John', dob: undefined}); p1.should.have.property('dob', undefined); try { - p1 = new Person({ name: 'John', dob: 'X' }); + p1 = new Person({name: 'John', dob: 'X'}); throw new Error('new Person() should have thrown'); } catch (e) { e.should.be.eql(new Error('Invalid date: X')); @@ -1702,11 +1702,11 @@ describe('manipulation', function() { it('should not update instances that do not satisfy the where condition', function(done) { - Person.update({ name: 'Harry Hoe' }, { name: 'Marta Moe' }, function(err, + Person.update({name: 'Harry Hoe'}, {name: 'Marta Moe'}, function(err, info) { if (err) return done(err); info.should.have.property('count', 0); - Person.find({ where: { name: 'Harry Hoe' }}, function(err, people) { + Person.find({where: {name: 'Harry Hoe'}}, function(err, people) { if (err) return done(err); people.should.be.empty; done(); @@ -1716,11 +1716,11 @@ describe('manipulation', function() { it('should only update instances that satisfy the where condition', function(done) { - Person.update({ name: 'Brett Boe' }, { name: 'Harry Hoe' }, function(err, + Person.update({name: 'Brett Boe'}, {name: 'Harry Hoe'}, function(err, info) { if (err) return done(err); info.should.have.property('count', 1); - Person.find({ where: { age: 19 }}, function(err, people) { + Person.find({where: {age: 19}}, function(err, people) { if (err) return done(err); people.should.have.length(1); people[0].name.should.equal('Harry Hoe'); @@ -1731,13 +1731,13 @@ describe('manipulation', function() { it('should update all instances when the where condition is not provided', function(done) { - Person.update({ name: 'Harry Hoe' }, function(err, info) { + Person.update({name: 'Harry Hoe'}, function(err, info) { if (err) return done(err); info.should.have.property('count', 5); - Person.find({ where: { name: 'Brett Boe' }}, function(err, people) { + Person.find({where: {name: 'Brett Boe'}}, function(err, people) { if (err) return done(err); people.should.be.empty; - Person.find({ where: { name: 'Harry Hoe' }}, function(err, people) { + Person.find({where: {name: 'Harry Hoe'}}, function(err, people) { if (err) return done(err); people.should.have.length(5); done(); @@ -1748,11 +1748,11 @@ describe('manipulation', function() { it('should ignore where conditions with undefined values', function(done) { - Person.update({ name: 'Brett Boe' }, { name: undefined, gender: 'male' }, + Person.update({name: 'Brett Boe'}, {name: undefined, gender: 'male'}, function(err, info) { if (err) return done(err); info.should.have.property('count', 1); - Person.find({ where: { name: 'Brett Boe' }}, function(err, people) { + Person.find({where: {name: 'Brett Boe'}}, function(err, people) { if (err) return done(err); people.should.have.length(1); people[0].name.should.equal('Brett Boe'); @@ -1763,7 +1763,7 @@ describe('manipulation', function() { it('should not coerce invalid values provided in where conditions', function(done) { - Person.update({ name: 'Brett Boe' }, { dob: 'Carla Coe' }, function(err) { + Person.update({name: 'Brett Boe'}, {dob: 'Carla Coe'}, function(err) { should.exist(err); err.message.should.equal('Invalid date: Carla Coe'); done(); @@ -1776,9 +1776,9 @@ describe('manipulation', function() { var Person; before('prepare "Person" model', function(done) { Person = ds.define('Person', { - id: { type: Number, id: true }, - name: { type: String }, - city: { type: String }, + id: {type: Number, id: true}, + name: {type: String}, + city: {type: String}, }); ds.automigrate('Person', done); }); @@ -1788,7 +1788,7 @@ describe('manipulation', function() { }); it('should preserve properties with dynamic setters on create', function(done) { - StubUser.upsertWithWhere({ password: 'foo' }, { password: 'foo' }, function(err, created) { + StubUser.upsertWithWhere({password: 'foo'}, {password: 'foo'}, function(err, created) { if (err) return done(err); created.password.should.equal('foo-FOO'); StubUser.findById(created.id, function(err, found) { @@ -1800,10 +1800,10 @@ describe('manipulation', function() { }); it('should preserve properties with dynamic setters on update', function(done) { - StubUser.create({ password: 'foo' }, function(err, created) { + StubUser.create({password: 'foo'}, function(err, created) { if (err) return done(err); - var data = { password: 'bar' }; - StubUser.upsertWithWhere({ id: created.id }, data, function(err, updated) { + var data = {password: 'bar'}; + StubUser.upsertWithWhere({id: created.id}, data, function(err, updated) { if (err) return done(err); updated.password.should.equal('bar-BAR'); StubUser.findById(created.id, function(err, found) { @@ -1817,7 +1817,7 @@ describe('manipulation', function() { it('should preserve properties with "undefined" value', function(done) { Person.create( - { id: 10, name: 'Ritz', city: undefined }, + {id: 10, name: 'Ritz', city: undefined}, function(err, instance) { if (err) return done(err); instance.toObject().should.have.properties({ @@ -1826,8 +1826,8 @@ describe('manipulation', function() { city: undefined, }); - Person.upsertWithWhere({ id: 10 }, - { name: 'updated name' }, + Person.upsertWithWhere({id: 10}, + {name: 'updated name'}, function(err, updated) { if (err) return done(err); var result = updated.toObject(); @@ -1842,9 +1842,9 @@ describe('manipulation', function() { }); it('should allow save() of the created instance', function(done) { - Person.upsertWithWhere({ id: 999 }, + Person.upsertWithWhere({id: 999}, // Todo @mountain: This seems a bug why in data object still I need to pass id? - { id: 999, name: 'a-name' }, + {id: 999, name: 'a-name'}, function(err, inst) { if (err) return done(err); inst.save(done); @@ -1852,8 +1852,8 @@ describe('manipulation', function() { }); it('works without options on create (promise variant)', function(done) { - var person = { id: 123, name: 'a', city: 'city a' }; - Person.upsertWithWhere({ id: 123 }, person) + var person = {id: 123, name: 'a', city: 'city a'}; + Person.upsertWithWhere({id: 123}, person) .then(function(p) { should.exist(p); p.should.be.instanceOf(Person); @@ -1874,8 +1874,8 @@ describe('manipulation', function() { }); it('works with options on create (promise variant)', function(done) { - var person = { id: 234, name: 'b', city: 'city b' }; - Person.upsertWithWhere({ id: 234 }, person, { validate: false }) + var person = {id: 234, name: 'b', city: 'city b'}; + Person.upsertWithWhere({id: 234}, person, {validate: false}) .then(function(p) { should.exist(p); p.should.be.instanceOf(Person); @@ -1896,13 +1896,13 @@ describe('manipulation', function() { }); it('works without options on update (promise variant)', function(done) { - var person = { id: 456, name: 'AAA', city: 'city AAA' }; + var person = {id: 456, name: 'AAA', city: 'city AAA'}; Person.create(person) .then(function(created) { created = created.toObject(); delete created.city; created.name = 'BBB'; - return Person.upsertWithWhere({ id: 456 }, created) + return Person.upsertWithWhere({id: 456}, created) .then(function(p) { should.exist(p); p.should.be.instanceOf(Person); @@ -1923,13 +1923,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); @@ -1951,7 +1951,7 @@ describe('manipulation', function() { it('fails the upsertWithWhere operation when data object is empty', function(done) { options = {}; - Person.upsertWithWhere({ name: 'John Lennon' }, {}, options, + Person.upsertWithWhere({name: 'John Lennon'}, {}, options, function(err) { err.message.should.equal('data object cannot be empty!'); done(); @@ -1959,7 +1959,7 @@ describe('manipulation', function() { }); it('creates a new record when no matching instance is found', function(done) { - Person.upsertWithWhere({ city: 'Florida' }, { name: 'Nick Carter', id: 1, city: 'Florida' }, + Person.upsertWithWhere({city: 'Florida'}, {name: 'Nick Carter', id: 1, city: 'Florida'}, function(err, created) { if (err) return done(err); Person.findById(1, function(err, data) { @@ -1975,11 +1975,11 @@ describe('manipulation', function() { it('fails the upsertWithWhere operation when multiple instances are ' + 'retrieved based on the filter criteria', function(done) { Person.create([ - { id: '2', name: 'Howie', city: 'Florida' }, - { id: '3', name: 'Kevin', city: 'Florida' }, + {id: '2', name: 'Howie', city: 'Florida'}, + {id: '3', name: 'Kevin', city: 'Florida'}, ], function(err, instance) { if (err) return done(err); - Person.upsertWithWhere({ city: 'Florida' }, { + Person.upsertWithWhere({city: 'Florida'}, { id: '4', name: 'Brian', }, function(err) { err.message.should.equal('There are multiple instances found.' + @@ -1992,12 +1992,12 @@ describe('manipulation', function() { it('updates the record when one matching instance is found ' + 'based on the filter criteria', function(done) { Person.create([ - { id: '5', name: 'Howie', city: 'Kentucky' }, + {id: '5', name: 'Howie', city: 'Kentucky'}, ], function(err, instance) { if (err) return done(err); - Person.upsertWithWhere({ city: 'Kentucky' }, { + Person.upsertWithWhere({city: 'Kentucky'}, { name: 'Brian', - }, { validate: false }, function(err, instance) { + }, {validate: false}, function(err, instance) { if (err) return done(err); Person.findById(5, function(err, data) { if (err) return done(err); @@ -2014,12 +2014,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 8bdf3581..5f2fa92f 100644 --- a/test/memory.test.js +++ b/test/memory.test.js @@ -64,7 +64,7 @@ describe('Memory connector', function() { it('should persist create', function(done) { var count = 0; async.eachSeries(['John1', 'John2', 'John3'], function(item, cb) { - User.create({ name: item }, function(err, result) { + User.create({name: item}, function(err, result) { ids.push(result.id); count++; readModels(function(err, json) { @@ -92,7 +92,7 @@ describe('Memory connector', function() { }); it('should persist upsert', function(done) { - User.upsert({ id: ids[1], name: 'John' }, function(err, result) { + User.upsert({id: ids[1], name: 'John'}, function(err, result) { if (err) { return done(err); } @@ -110,7 +110,7 @@ describe('Memory connector', function() { }); it('should persist update', function(done) { - User.update({ id: ids[1] }, { name: 'John1' }, + User.update({id: ids[1]}, {name: 'John1'}, function(err, result) { if (err) { return done(err); @@ -144,13 +144,13 @@ describe('Memory connector', function() { }); var User = ds.define('User', { - seq: { type: Number, index: true }, - name: { type: String, index: true, sort: true }, - email: { type: String, index: true }, - birthday: { type: Date, index: true }, - role: { type: String, index: true }, - order: { type: Number, index: true, sort: true }, - vip: { type: Boolean }, + seq: {type: Number, index: true}, + name: {type: String, index: true, sort: true}, + email: {type: String, index: true}, + birthday: {type: Date, index: true}, + role: {type: String, index: true}, + order: {type: Number, index: true, sort: true}, + vip: {type: Boolean}, address: { street: String, city: String, @@ -171,7 +171,7 @@ describe('Memory connector', function() { before(seed); it('should allow to find using like', function(done) { - User.find({ where: { name: { like: '%St%' }}}, function(err, posts) { + User.find({where: {name: {like: '%St%'}}}, function(err, posts) { should.not.exist(err); posts.should.have.property('length', 2); done(); @@ -179,7 +179,7 @@ describe('Memory connector', function() { }); it('should allow to find using like with regexp', function(done) { - User.find({ where: { name: { like: /.*St.*/ }}}, function(err, posts) { + User.find({where: {name: {like: /.*St.*/}}}, function(err, posts) { should.not.exist(err); posts.should.have.property('length', 2); done(); @@ -187,7 +187,7 @@ describe('Memory connector', function() { }); it('should support like for no match', function(done) { - User.find({ where: { name: { like: 'M%XY' }}}, function(err, posts) { + User.find({where: {name: {like: 'M%XY'}}}, function(err, posts) { should.not.exist(err); posts.should.have.property('length', 0); done(); @@ -195,7 +195,7 @@ describe('Memory connector', function() { }); it('should allow to find using nlike', function(done) { - User.find({ where: { name: { nlike: '%St%' }}}, function(err, posts) { + User.find({where: {name: {nlike: '%St%'}}}, function(err, posts) { should.not.exist(err); posts.should.have.property('length', 4); done(); @@ -203,7 +203,7 @@ describe('Memory connector', function() { }); it('should allow to find using nlike with regexp', function(done) { - User.find({ where: { name: { nlike: /.*St.*/ }}}, function(err, posts) { + User.find({where: {name: {nlike: /.*St.*/}}}, function(err, posts) { should.not.exist(err); posts.should.have.property('length', 4); done(); @@ -211,7 +211,7 @@ describe('Memory connector', function() { }); it('should support nlike for no match', function(done) { - User.find({ where: { name: { nlike: 'M%XY' }}}, function(err, posts) { + User.find({where: {name: {nlike: 'M%XY'}}}, function(err, posts) { should.not.exist(err); posts.should.have.property('length', 6); done(); @@ -219,56 +219,56 @@ describe('Memory connector', function() { }); it('should throw if the like value is not string or regexp', function(done) { - User.find({ where: { name: { like: 123 }}}, function(err, posts) { + User.find({where: {name: {like: 123}}}, function(err, posts) { should.exist(err); done(); }); }); it('should throw if the nlike value is not string or regexp', function(done) { - User.find({ where: { name: { nlike: 123 }}}, function(err, posts) { + User.find({where: {name: {nlike: 123}}}, function(err, posts) { should.exist(err); done(); }); }); it('should throw if the inq value is not an array', function(done) { - User.find({ where: { name: { inq: '12' }}}, function(err, posts) { + User.find({where: {name: {inq: '12'}}}, function(err, posts) { should.exist(err); done(); }); }); it('should throw if the nin value is not an array', function(done) { - User.find({ where: { name: { nin: '12' }}}, function(err, posts) { + User.find({where: {name: {nin: '12'}}}, function(err, posts) { should.exist(err); done(); }); }); it('should throw if the between value is not an array', function(done) { - User.find({ where: { name: { between: '12' }}}, function(err, posts) { + User.find({where: {name: {between: '12'}}}, function(err, posts) { should.exist(err); done(); }); }); it('should throw if the between value is not an array of length 2', function(done) { - User.find({ where: { name: { between: ['12'] }}}, function(err, posts) { + User.find({where: {name: {between: ['12']}}}, function(err, posts) { should.exist(err); done(); }); }); it('should successfully extract 5 users from the db', function(done) { - User.find({ where: { seq: { between: [1, 5] }}}, function(err, users) { + User.find({where: {seq: {between: [1, 5]}}}, function(err, users) { should(users.length).be.equal(5); done(); }); }); it('should successfully extract 1 user (Lennon) from the db', function(done) { - User.find({ where: { birthday: { between: [new Date(1970, 0), new Date(1990, 0)] }}}, + User.find({where: {birthday: {between: [new Date(1970, 0), new Date(1990, 0)]}}}, function(err, users) { should(users.length).be.equal(1); should(users[0].name).be.equal('John Lennon'); @@ -277,7 +277,7 @@ describe('Memory connector', function() { }); it('should successfully extract 2 users from the db', function(done) { - User.find({ where: { birthday: { between: [new Date(1940, 0), new Date(1990, 0)] }}}, + User.find({where: {birthday: {between: [new Date(1940, 0), new Date(1990, 0)]}}}, function(err, users) { should(users.length).be.equal(2); done(); @@ -285,7 +285,7 @@ describe('Memory connector', function() { }); it('should successfully extract 2 users using implied and', function(done) { - User.find({ where: { role: 'lead', vip: true }}, function(err, users) { + User.find({where: {role: 'lead', vip: true}}, function(err, users) { should(users.length).be.equal(2); should(users[0].name).be.equal('John Lennon'); should(users[1].name).be.equal('Paul McCartney'); @@ -298,7 +298,7 @@ describe('Memory connector', function() { User.find({ where: { name: 'John Lennon', - and: [{ role: 'lead' }, { vip: true }], + and: [{role: 'lead'}, {vip: true}], }, }, function(err, users) { should(users.length).be.equal(1); @@ -308,8 +308,8 @@ describe('Memory connector', function() { }); it('should successfully extract 2 users using date range', function(done) { - User.find({ where: { birthday: { between: - [new Date(1940, 0).toISOString(), new Date(1990, 0).toISOString()] }}}, + User.find({where: {birthday: {between: + [new Date(1940, 0).toISOString(), new Date(1990, 0).toISOString()]}}}, function(err, users) { should(users.length).be.equal(2); done(); @@ -317,7 +317,7 @@ describe('Memory connector', function() { }); it('should successfully extract 0 user from the db', function(done) { - User.find({ where: { birthday: { between: [new Date(1990, 0), Date.now()] }}}, + User.find({where: {birthday: {between: [new Date(1990, 0), Date.now()]}}}, function(err, users) { should(users.length).be.equal(0); done(); @@ -356,7 +356,7 @@ describe('Memory connector', function() { it('should successfully extract 5 users matching a neq filter over array values', function(done) { User.find({ where: { - 'children': { neq: 'Dhani' }, + 'children': {neq: 'Dhani'}, }, }, function(err, users) { should.not.exist(err); @@ -366,7 +366,7 @@ describe('Memory connector', function() { }); it('should count using date string', function(done) { - User.count({ birthday: { lt: new Date(1990, 0).toISOString() }}, + User.count({birthday: {lt: new Date(1990, 0).toISOString()}}, function(err, count) { should(count).be.equal(2); done(); @@ -374,7 +374,7 @@ describe('Memory connector', function() { }); it('should support order with multiple fields', function(done) { - User.find({ order: 'vip ASC, seq DESC' }, function(err, posts) { + User.find({order: 'vip ASC, seq DESC'}, function(err, posts) { should.not.exist(err); posts[0].seq.should.be.eql(4); posts[1].seq.should.be.eql(3); @@ -383,7 +383,7 @@ describe('Memory connector', function() { }); it('should sort undefined values to the end when ordered DESC', function(done) { - User.find({ order: 'vip ASC, order DESC' }, function(err, posts) { + User.find({order: 'vip ASC, order DESC'}, function(err, posts) { should.not.exist(err); posts[4].seq.should.be.eql(1); @@ -393,14 +393,14 @@ describe('Memory connector', function() { }); it('should throw if order has wrong direction', function(done) { - User.find({ order: 'seq ABC' }, function(err, posts) { + User.find({order: 'seq ABC'}, function(err, posts) { should.exist(err); done(); }); }); it('should support neq operator for number', function(done) { - User.find({ where: { seq: { neq: 4 }}}, function(err, users) { + User.find({where: {seq: {neq: 4}}}, function(err, users) { should.not.exist(err); users.length.should.be.equal(5); for (var i = 0; i < users.length; i++) { @@ -411,7 +411,7 @@ describe('Memory connector', function() { }); it('should support neq operator for string', function(done) { - User.find({ where: { role: { neq: 'lead' }}}, function(err, users) { + User.find({where: {role: {neq: 'lead'}}}, function(err, users) { should.not.exist(err); users.length.should.be.equal(4); for (var i = 0; i < users.length; i++) { @@ -424,7 +424,7 @@ describe('Memory connector', function() { }); it('should support neq operator for null', function(done) { - User.find({ where: { role: { neq: null }}}, function(err, users) { + User.find({where: {role: {neq: null}}}, function(err, users) { should.not.exist(err); users.length.should.be.equal(2); for (var i = 0; i < users.length; i++) { @@ -436,7 +436,7 @@ describe('Memory connector', function() { it('should work when a regex is provided without the regexp operator', function(done) { - User.find({ where: { name: /John.*/i }}, function(err, users) { + User.find({where: {name: /John.*/i}}, function(err, users) { should.not.exist(err); users.length.should.equal(1); users[0].name.should.equal('John Lennon'); @@ -445,7 +445,7 @@ describe('Memory connector', function() { }); it('should support the regexp operator with regex strings', function(done) { - User.find({ where: { name: { regexp: '^J' }}}, function(err, users) { + User.find({where: {name: {regexp: '^J'}}}, function(err, users) { should.not.exist(err); users.length.should.equal(1); users[0].name.should.equal('John Lennon'); @@ -454,7 +454,7 @@ describe('Memory connector', function() { }); it('should support the regexp operator with regex literals', function(done) { - User.find({ where: { name: { regexp: /^J/ }}}, function(err, users) { + User.find({where: {name: {regexp: /^J/}}}, function(err, users) { should.not.exist(err); users.length.should.equal(1); users[0].name.should.equal('John Lennon'); @@ -463,7 +463,7 @@ describe('Memory connector', function() { }); it('should support the regexp operator with regex objects', function(done) { - User.find({ where: { name: { regexp: new RegExp(/^J/) }}}, function(err, + User.find({where: {name: {regexp: new RegExp(/^J/)}}}, function(err, users) { should.not.exist(err); users.length.should.equal(1); @@ -473,7 +473,7 @@ describe('Memory connector', function() { }); it('should support nested property in query', function(done) { - User.find({ where: { 'address.city': 'San Jose' }}, function(err, users) { + User.find({where: {'address.city': 'San Jose'}}, function(err, users) { should.not.exist(err); users.length.should.be.equal(1); for (var i = 0; i < users.length; i++) { @@ -484,7 +484,7 @@ describe('Memory connector', function() { }); it('should support nested property with regex over arrays in query', function(done) { - User.find({ where: { 'friends.name': { regexp: /^Ringo/ }}}, function(err, users) { + User.find({where: {'friends.name': {regexp: /^Ringo/}}}, function(err, users) { should.not.exist(err); users.length.should.be.equal(2); users[0].name.should.be.equal('John Lennon'); @@ -494,7 +494,7 @@ describe('Memory connector', function() { }); it('should support nested property with gt in query', function(done) { - User.find({ where: { 'address.city': { gt: 'San' }}}, function(err, users) { + User.find({where: {'address.city': {gt: 'San'}}}, function(err, users) { should.not.exist(err); users.length.should.be.equal(2); for (var i = 0; i < users.length; i++) { @@ -505,7 +505,7 @@ describe('Memory connector', function() { }); it('should support nested property for order in query', function(done) { - User.find({ where: { 'address.state': 'CA' }, order: 'address.city DESC' }, + User.find({where: {'address.state': 'CA'}, order: 'address.city DESC'}, function(err, users) { should.not.exist(err); users.length.should.be.equal(2); @@ -516,8 +516,8 @@ describe('Memory connector', function() { }); it('should deserialize values after saving in upsert', function(done) { - User.findOne({ where: { seq: 1 }}, function(err, paul) { - User.updateOrCreate({ id: paul.id, name: 'Sir Paul McCartney' }, + User.findOne({where: {seq: 1}}, function(err, paul) { + User.updateOrCreate({id: paul.id, name: 'Sir Paul McCartney'}, function(err, sirpaul) { should.not.exist(err); sirpaul.birthday.should.be.instanceOf(Date); @@ -529,7 +529,7 @@ describe('Memory connector', function() { }); it('should support multi-level nested array property in query', function(done) { - User.find({ where: { 'address.tags.tag': 'business' }}, function(err, users) { + User.find({where: {'address.tags.tag': 'business'}}, function(err, users) { should.not.exist(err); users.length.should.be.equal(1); users[0].address.tags[0].tag.should.be.equal('business'); @@ -553,14 +553,14 @@ describe('Memory connector', function() { state: 'CA', zipCode: '95131', tags: [ - { tag: 'business' }, - { tag: 'rent' }, + {tag: 'business'}, + {tag: 'rent'}, ], }, friends: [ - { name: 'Paul McCartney' }, - { name: 'George Harrison' }, - { name: 'Ringo Starr' }, + {name: 'Paul McCartney'}, + {name: 'George Harrison'}, + {name: 'Ringo Starr'}, ], children: ['Sean', 'Julian'], }, @@ -579,16 +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 +611,32 @@ describe('Memory connector', function() { var Tool = ds.createModel('Tool', { name: String, - }, { memory: { collection: 'Product' }}); + }, {memory: {collection: 'Product'}}); var Widget = ds.createModel('Widget', { name: String, - }, { memory: { collection: 'Product' }}); + }, {memory: {collection: 'Product'}}); ds.connector.getCollection('Tool').should.equal('Product'); ds.connector.getCollection('Widget').should.equal('Product'); async.series([ function(next) { - Tool.create({ name: 'Tool A' }, next); + Tool.create({name: 'Tool A'}, next); }, function(next) { - Tool.create({ name: 'Tool B' }, next); + Tool.create({name: 'Tool B'}, next); }, function(next) { - Widget.create({ name: 'Widget A' }, next); + Widget.create({name: 'Widget A'}, next); }, ], function(err) { Product.find(function(err, products) { should.not.exist(err); products.should.have.length(3); - products[0].toObject().should.eql({ name: 'Tool A', id: 1 }); - products[1].toObject().should.eql({ name: 'Tool B', id: 2 }); - products[2].toObject().should.eql({ name: 'Widget A', id: 3 }); + products[0].toObject().should.eql({name: 'Tool A', id: 1}); + products[1].toObject().should.eql({name: 'Tool B', id: 2}); + products[2].toObject().should.eql({name: 'Widget A', id: 3}); done(); }); }); @@ -724,7 +724,7 @@ describe('Memory connector', function() { describe('findOrCreate', function() { var ds, Cars; before(function() { - ds = new DataSource({ connector: 'memory' }); + ds = new DataSource({connector: 'memory'}); Cars = ds.define('Cars', { color: String, }); @@ -733,8 +733,8 @@ describe('Memory connector', function() { it('should create a specific object once and in the subsequent calls it should find it', function(done) { var creationNum = 0; async.times(100, function(n, next) { - var initialData = { color: 'white' }; - var query = { 'where': initialData }; + var initialData = {color: 'white'}; + var query = {'where': initialData}; Cars.findOrCreate(query, initialData, function(err, car, created) { if (created) creationNum++; next(err, car); @@ -867,7 +867,7 @@ describe('Memory connector', function() { }); describe('Optimized connector', function() { - var ds = new DataSource({ connector: Memory }); + var ds = new DataSource({connector: Memory}); require('./persistence-hooks.suite')(ds, should, { replaceOrCreateReportsNewInstance: true, @@ -875,7 +875,7 @@ describe('Optimized connector', function() { }); describe('Unoptimized connector', function() { - var ds = new DataSource({ connector: Memory }); + var ds = new DataSource({connector: Memory}); // disable optimized methods ds.connector.updateOrCreate = false; @@ -891,7 +891,7 @@ describe('Memory connector with options', function() { var ds, savedOptions = {}, Post; before(function() { - ds = new DataSource({ connector: 'memory' }); + ds = new DataSource({connector: 'memory'}); ds.connector.create = function(model, data, options, cb) { savedOptions.create = options; process.nextTick(function() { @@ -902,14 +902,14 @@ describe('Memory connector with options', function() { ds.connector.update = function(model, where, data, options, cb) { savedOptions.update = options; process.nextTick(function() { - cb(null, { count: 1 }); + cb(null, {count: 1}); }); }; ds.connector.all = function(model, filter, options, cb) { savedOptions.find = options; process.nextTick(function() { - cb(null, [{ title: 't1', content: 'c1' }]); + cb(null, [{title: 't1', content: 'c1'}]); }); }; @@ -920,15 +920,15 @@ describe('Memory connector with options', function() { }); it('should receive options from the find method', function(done) { - var opts = { transaction: 'tx1' }; - Post.find({ where: { title: 't1' }}, opts, function(err, p) { + var opts = {transaction: 'tx1'}; + Post.find({where: {title: 't1'}}, opts, function(err, p) { savedOptions.find.should.be.eql(opts); done(err); }); }); it('should receive options from the find method', function(done) { - var opts = { transaction: 'tx2' }; + var opts = {transaction: 'tx2'}; Post.find({}, opts, function(err, p) { savedOptions.find.should.be.eql(opts); done(err); @@ -936,7 +936,7 @@ describe('Memory connector with options', function() { }); it('should treat first object arg as filter for find', function(done) { - var filter = { title: 't1' }; + var filter = {title: 't1'}; Post.find(filter, function(err, p) { savedOptions.find.should.be.eql({}); done(err); @@ -944,16 +944,16 @@ describe('Memory connector with options', function() { }); it('should receive options from the create method', function(done) { - var opts = { transaction: 'tx3' }; - Post.create({ title: 't1', content: 'c1' }, opts, function(err, p) { + var opts = {transaction: 'tx3'}; + Post.create({title: 't1', content: 'c1'}, opts, function(err, p) { savedOptions.create.should.be.eql(opts); done(err); }); }); it('should receive options from the update method', function(done) { - var opts = { transaction: 'tx4' }; - Post.update({ title: 't1' }, { content: 'c1 --> c2' }, + var opts = {transaction: 'tx4'}; + Post.update({title: 't1'}, {content: 'c1 --> c2'}, opts, function(err, p) { savedOptions.update.should.be.eql(opts); done(err); @@ -975,7 +975,7 @@ describe('Memory connector with observers', function() { var events = []; ds.connector.execute = function(command, params, options, cb) { var self = this; - var context = { command: command, params: params, options: options }; + var context = {command: command, params: params, options: options}; self.notifyObserversOf('before execute', context, function(err) { process.nextTick(function() { if (err) return cb(err); @@ -997,7 +997,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 672c3b74..c64b3927 100644 --- a/test/mixins.test.js +++ b/test/mixins.test.js @@ -15,8 +15,8 @@ var modelBuilder = new ModelBuilder(); var mixins = modelBuilder.mixins; function timestamps(Model, options) { - Model.defineProperty('createdAt', { type: Date }); - Model.defineProperty('updatedAt', { type: Date }); + Model.defineProperty('createdAt', {type: Date}); + Model.defineProperty('updatedAt', {type: Date}); var originalBeforeSave = Model.beforeSave; Model.beforeSave = function(next, data) { @@ -62,34 +62,34 @@ describe('Model class', function() { it('should apply a mixin class', function() { var Address = modelBuilder.define('Address', { - street: { type: 'string', required: true }, - city: { type: 'string', required: true }, + street: {type: 'string', required: true}, + city: {type: 'string', required: true}, }); - var memory = new DataSource('mem', { connector: Memory }, modelBuilder); - var Item = memory.createModel('Item', { name: 'string' }, { - mixins: { Address: true }, + var memory = new DataSource('mem', {connector: Memory}, modelBuilder); + var Item = memory.createModel('Item', {name: 'string'}, { + mixins: {Address: true}, }); var properties = Item.definition.properties; - properties.street.should.eql({ type: String, required: true }); - properties.city.should.eql({ type: String, required: true }); + properties.street.should.eql({type: String, required: true}); + properties.city.should.eql({type: String, required: true}); }); it('should apply mixins', function(done) { - var memory = new DataSource('mem', { connector: Memory }, modelBuilder); - var Item = memory.createModel('Item', { name: 'string' }, { + var memory = new DataSource('mem', {connector: Memory}, modelBuilder); + var Item = memory.createModel('Item', {name: 'string'}, { mixins: { - TimeStamp: true, Demo: { value: true }, + TimeStamp: true, Demo: {value: true}, Multi: [ - { key: 'foo', value: 'bar' }, - { key: 'fox', value: 'baz' }, + {key: 'foo', value: 'bar'}, + {key: 'fox', value: 'baz'}, ], }, }); - Item.mixin('Example', { foo: 'bar' }); + Item.mixin('Example', {foo: 'bar'}); Item.demoMixin.should.be.true; @@ -97,13 +97,13 @@ describe('Model class', function() { Item.multiMixin.fox.should.equal('baz'); var properties = Item.definition.properties; - properties.createdAt.should.eql({ type: Date }); - properties.updatedAt.should.eql({ type: Date }); + properties.createdAt.should.eql({type: Date}); + properties.updatedAt.should.eql({type: Date}); - Item.create({ name: 'Item 1' }, function(err, inst) { + Item.create({name: 'Item 1'}, function(err, inst) { inst.createdAt.should.be.a.date; inst.updatedAt.should.be.a.date; - inst.example().should.eql({ foo: 'bar' }); + inst.example().should.eql({foo: 'bar'}); done(); }); }); @@ -113,12 +113,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/model-definition.test.js b/test/model-definition.test.js index 65d7494c..f3289943 100644 --- a/test/model-definition.test.js +++ b/test/model-definition.test.js @@ -17,7 +17,7 @@ var ModelDefinition = require('../lib/model-definition'); describe('ModelDefinition class', function() { var memory; beforeEach(function() { - memory = new DataSource({ connector: Memory }); + memory = new DataSource({connector: Memory}); }); it('should be able to define plain models', function(done) { @@ -66,7 +66,7 @@ describe('ModelDefinition class', function() { var json = User.toJSON(); - User.defineProperty('id', { type: 'number', id: true }); + User.defineProperty('id', {type: 'number', id: true}); assert.equal(User.properties.name.type, String); assert.equal(User.properties.bio.type, ModelBuilder.Text); assert.equal(User.properties.approved.type, Boolean); @@ -76,7 +76,7 @@ describe('ModelDefinition class', function() { assert.equal(User.properties.id.type, Number); json = User.toJSON(); - assert.deepEqual(json.properties.id, { type: 'Number', id: true }); + assert.deepEqual(json.properties.id, {type: 'Number', id: true}); done(); }); @@ -114,10 +114,10 @@ describe('ModelDefinition class', function() { assert.equal(json.properties.joinedAt.type, 'Date'); assert.equal(json.properties.age.type, 'Number'); - assert.deepEqual(json.properties.address.type, { street: { type: 'String' }, - city: { type: 'String' }, - zipCode: { type: 'String' }, - state: { type: 'String' }}); + assert.deepEqual(json.properties.address.type, {street: {type: 'String'}, + city: {type: 'String'}, + zipCode: {type: 'String'}, + state: {type: 'String'}}); done(); }); @@ -206,7 +206,7 @@ describe('ModelDefinition class', function() { var modelBuilder = new ModelBuilder(); var User = new ModelDefinition(modelBuilder, 'User', { - userId: { type: String, id: true }, + userId: {type: String, id: true}, name: 'string', bio: ModelBuilder.Text, approved: Boolean, @@ -223,8 +223,8 @@ describe('ModelDefinition class', function() { var modelBuilder = new ModelBuilder(); var User = new ModelDefinition(modelBuilder, 'User', { - userId: { type: String, id: 2 }, - userType: { type: String, id: 1 }, + userId: {type: String, id: 2}, + userType: {type: String, id: 1}, name: 'string', bio: ModelBuilder.Text, approved: Boolean, @@ -245,9 +245,9 @@ describe('ModelDefinition class', function() { var modelBuilder = new ModelBuilder(); var User = new ModelDefinition(modelBuilder, 'User', { - userId: { type: String, id: true, oracle: { column: 'ID' }}, + userId: {type: String, id: true, oracle: {column: 'ID'}}, name: 'string', - }, { oracle: { table: 'USER' }}); + }, {oracle: {table: 'USER'}}); assert.equal(User.tableName('oracle'), 'USER'); assert.equal(User.tableName('mysql'), 'User'); @@ -278,7 +278,7 @@ describe('ModelDefinition class', function() { it('should ignore inherited options.base', function() { var modelBuilder = memory.modelBuilder; var base = modelBuilder.define('base'); - var child = base.extend('child', {}, { base: 'base' }); + var child = base.extend('child', {}, {base: 'base'}); var grandChild = child.extend('grand-child'); assert.equal('child', grandChild.base.modelName); assert(grandChild.prototype instanceof child); @@ -287,7 +287,7 @@ describe('ModelDefinition class', function() { it('should ignore inherited options.super', function() { var modelBuilder = memory.modelBuilder; var base = modelBuilder.define('base'); - var child = base.extend('child', {}, { super: 'base' }); + var child = base.extend('child', {}, {super: 'base'}); var grandChild = child.extend('grand-child'); assert.equal('child', grandChild.base.modelName); assert(grandChild.prototype instanceof child); @@ -310,7 +310,7 @@ describe('ModelDefinition class', function() { it('should not serialize protected properties of nested models into JSON', function(done) { var modelBuilder = memory.modelBuilder; var Parent = memory.createModel('parent'); - var Child = memory.createModel('child', {}, { protected: ['protectedProperty'] }); + var Child = memory.createModel('child', {}, {protected: ['protectedProperty']}); Parent.hasMany(Child); Parent.create({ name: 'parent', @@ -319,7 +319,7 @@ describe('ModelDefinition class', function() { name: 'child', protectedProperty: 'protectedValue', }, function(err, child) { - Parent.find({ include: 'children' }, function(err, parents) { + Parent.find({include: 'children'}, function(err, parents) { var serialized = parents[0].toJSON(); var child = serialized.children[0]; assert.equal(child.name, 'child'); @@ -350,7 +350,7 @@ describe('ModelDefinition class', function() { it('should not serialize hidden properties of nested models into JSON', function(done) { var modelBuilder = memory.modelBuilder; var Parent = memory.createModel('parent'); - var Child = memory.createModel('child', {}, { hidden: ['secret'] }); + var Child = memory.createModel('child', {}, {hidden: ['secret']}); Parent.hasMany(Child); Parent.create({ name: 'parent', @@ -359,7 +359,7 @@ describe('ModelDefinition class', function() { name: 'child', secret: 'secret', }, function(err, child) { - Parent.find({ include: 'children' }, function(err, parents) { + Parent.find({include: 'children'}, function(err, parents) { var serialized = parents[0].toJSON(); var child = serialized.children[0]; assert.equal(child.name, 'child'); @@ -374,7 +374,7 @@ describe('ModelDefinition class', function() { var message = 'deprecation not reported'; process.once('deprecation', function(err) { message = err.message; }); - memory.createModel('Dotted', { 'dot.name': String }); + memory.createModel('Dotted', {'dot.name': String}); message.should.match(/Dotted.*dot\.name/); }); @@ -384,7 +384,7 @@ describe('ModelDefinition class', function() { process.once('deprecation', function(err) { message = err.message; }); var Model = memory.createModel('DynamicDotted'); - Model.create({ 'dot.name': 'dot.value' }, function(err) { + Model.create({'dot.name': 'dot.value'}, function(err) { if (err) return done(err); message.should.match(/Dotted.*dot\.name/); done(); diff --git a/test/operation-hooks.suite/embeds-many-create.suite.js b/test/operation-hooks.suite/embeds-many-create.suite.js index 53973fe3..86afae7b 100644 --- a/test/operation-hooks.suite/embeds-many-create.suite.js +++ b/test/operation-hooks.suite/embeds-many-create.suite.js @@ -18,7 +18,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 +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', {}); @@ -55,7 +55,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 +111,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..3babfd25 100644 --- a/test/operation-hooks.suite/embeds-many-destroy.suite.js +++ b/test/operation-hooks.suite/embeds-many-destroy.suite.js @@ -18,7 +18,7 @@ module.exports = function(dataSource, should, connectorCapabilities) { var ctxRecorder, hookMonitor, expectedError; beforeEach(function sharedSetup() { ctxRecorder = new ContextRecorder('hook not called'); - hookMonitor = new HookMonitor({ includeModelName: true }); + hookMonitor = new HookMonitor({includeModelName: true}); expectedError = new Error('test error'); }); @@ -27,9 +27,9 @@ module.exports = function(dataSource, should, connectorCapabilities) { beforeEach(function setupDatabase() { Embedded = dataSource.createModel('Embedded', { // Set id.generated to false to honor client side values - id: { type: String, id: true, generated: false, default: uid.next }, - name: { type: String, required: true }, - extra: { type: String, required: false }, + id: {type: String, id: true, generated: false, default: uid.next}, + name: {type: String, required: true}, + extra: {type: String, required: false}, }); Owner = dataSource.createModel('Owner', {}); @@ -53,7 +53,7 @@ module.exports = function(dataSource, should, connectorCapabilities) { ownerInstance = inst; }) .then(function() { - var item = new Embedded({ name: 'created' }); + var item = new Embedded({name: 'created'}); return ownerInstance.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..930c3ddb 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 @@ -18,7 +18,7 @@ module.exports = function(dataSource, should, connectorCapabilities) { var ctxRecorder, hookMonitor, expectedError; beforeEach(function setupHelpers() { ctxRecorder = new ContextRecorder('hook not called'); - hookMonitor = new HookMonitor({ includeModelName: true }); + hookMonitor = new HookMonitor({includeModelName: true}); expectedError = new Error('test error'); }); @@ -27,9 +27,9 @@ module.exports = function(dataSource, should, connectorCapabilities) { beforeEach(function setupDatabase() { Embedded = dataSource.createModel('Embedded', { // Set id.generated to false to honor client side values - id: { type: String, id: true, generated: false, default: uid.next }, - name: { type: String, required: true }, - extra: { type: String, required: false }, + id: {type: String, id: true, generated: false, default: uid.next}, + name: {type: String, required: true}, + extra: {type: String, required: false}, }); Owner = dataSource.createModel('Owner', {}); @@ -53,7 +53,7 @@ module.exports = function(dataSource, should, connectorCapabilities) { ownerInstance = inst; }) .then(function() { - var item = new Embedded({ name: 'created' }); + var item = new Embedded({name: 'created'}); return ownerInstance.embeddedList.create(item).then(function(it) { existingItem = it; }); @@ -68,7 +68,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 +125,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..bd9495ee 100644 --- a/test/operation-hooks.suite/embeds-one-create.suite.js +++ b/test/operation-hooks.suite/embeds-one-create.suite.js @@ -18,7 +18,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 +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', {}); @@ -55,7 +55,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 +106,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..1b425655 100644 --- a/test/operation-hooks.suite/embeds-one-destroy.suite.js +++ b/test/operation-hooks.suite/embeds-one-destroy.suite.js @@ -17,7 +17,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 +26,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 +52,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; }); diff --git a/test/operation-hooks.suite/embeds-one-update.suite.js b/test/operation-hooks.suite/embeds-one-update.suite.js index ec8d8e66..24d80ae4 100644 --- a/test/operation-hooks.suite/embeds-one-update.suite.js +++ b/test/operation-hooks.suite/embeds-one-update.suite.js @@ -17,7 +17,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 +26,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 +52,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 +63,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 +115,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/optional-validation.test.js b/test/optional-validation.test.js index e97edccb..545154a3 100644 --- a/test/optional-validation.test.js +++ b/test/optional-validation.test.js @@ -12,25 +12,25 @@ var ValidationError = j.ValidationError; var INITIAL_NAME = 'Bert'; var NEW_NAME = 'Ernie'; -var INVALID_DATA = { name: null }; -var VALID_DATA = { name: INITIAL_NAME }; +var INVALID_DATA = {name: null}; +var VALID_DATA = {name: INITIAL_NAME}; describe('optional-validation', function() { before(function(done) { db = getSchema(); ModelWithForceId = db.createModel( 'ModelWithForceId', - { name: String }, - { forceId: true }); + {name: String}, + {forceId: true}); User = db.define('User', { - seq: { type: Number, index: true }, - name: { type: String, index: true, sort: true }, - email: { type: String, index: true }, - birthday: { type: Date, index: true }, - role: { type: String, index: true }, - order: { type: Number, index: true, sort: true }, - vip: { type: Boolean }, - }, { forceId: true, strict: true }); + seq: {type: Number, index: true}, + name: {type: String, index: true, sort: true}, + email: {type: String, index: true}, + birthday: {type: Date, index: true}, + role: {type: String, index: true}, + order: {type: Number, index: true, sort: true}, + vip: {type: Boolean}, + }, {forceId: true, strict: true}); db.automigrate(['ModelWithForceId', 'User'], done); }); @@ -54,7 +54,7 @@ describe('optional-validation', function() { function expectCreateSuccess(data, done) { if (done === undefined && typeof data === 'function') { done = data; - data = { name: INITIAL_NAME }; + data = {name: INITIAL_NAME}; } return function(err, instance) { if (err) return done(err); @@ -71,7 +71,7 @@ describe('optional-validation', function() { function expectChangeSuccess(data, done) { if (done === undefined && typeof data === 'function') { done = data; - data = { name: NEW_NAME }; + data = {name: NEW_NAME}; } return function(err, instance) { if (err) return done(err); @@ -86,36 +86,36 @@ describe('optional-validation', function() { } function createUserAndChangeName(name, cb) { - User.create(VALID_DATA, { validate: true }, function(err, d) { + User.create(VALID_DATA, {validate: true}, function(err, d) { d.name = name; cb(err, d); }); } function createUser(cb) { - User.create(VALID_DATA, { validate: true }, cb); + User.create(VALID_DATA, {validate: true}, cb); } function callUpdateOrCreateWithExistingUserId(name, options, cb) { - User.create({ 'name': 'Groover' }, function(err, user) { + User.create({'name': 'Groover'}, function(err, user) { if (err) return cb(err); - var data = { name: name }; + var data = {name: name}; data.id = user.id; User.updateOrCreate(data, options, cb); }); } function getNewWhere() { - return { name: 'DoesNotExist' + (whereCount++) }; + return {name: 'DoesNotExist' + (whereCount++)}; } describe('forceId', function() { context('replaceAttributes', function() { it('should not fail if you do not pass the Primary key in data object', function(done) { - ModelWithForceId.create({ name: 'foo' }, function(err, created) { + ModelWithForceId.create({name: 'foo'}, function(err, created) { if (err) return done(err); - created.replaceAttributes({ name: 'bar' }, function(err, data) { + created.replaceAttributes({name: 'bar'}, function(err, data) { done(err); }); }); @@ -123,9 +123,9 @@ describe('optional-validation', function() { it('should fail if you pass the Primary key in data object', function(done) { - ModelWithForceId.create({ name: 'foo' }, function(err, created) { + ModelWithForceId.create({name: 'foo'}, function(err, created) { if (err) return done(err); - created.replaceAttributes({ name: 'bar', id: 999 }, + created.replaceAttributes({name: 'bar', id: 999}, function(err, data) { should.exist(err); done(); @@ -138,19 +138,19 @@ describe('optional-validation', function() { describe('no model setting', function() { describe('method create', function() { it('should throw on create with validate:true with invalid data', function(done) { - User.create(INVALID_DATA, { validate: true }, expectValidationError(done)); + User.create(INVALID_DATA, {validate: true}, expectValidationError(done)); }); it('should NOT throw on create with validate:false with invalid data', function(done) { - User.create(INVALID_DATA, { validate: false }, expectCreateSuccess(INVALID_DATA, done)); + User.create(INVALID_DATA, {validate: false}, expectCreateSuccess(INVALID_DATA, done)); }); it('should NOT throw on create with validate:true with valid data', function(done) { - User.create(VALID_DATA, { validate: true }, expectCreateSuccess(done)); + User.create(VALID_DATA, {validate: true}, expectCreateSuccess(done)); }); it('should NOT throw on create with validate:false with valid data', function(done) { - User.create(VALID_DATA, { validate: false }, expectCreateSuccess(done)); + User.create(VALID_DATA, {validate: false}, expectCreateSuccess(done)); }); it('should throw on create with invalid data', function(done) { @@ -164,7 +164,7 @@ describe('optional-validation', function() { describe('method findOrCreate', function() { it('should throw on findOrCreate with validate:true with invalid data', function(done) { - User.findOrCreate(getNewWhere(), INVALID_DATA, { validate: true }, expectValidationError(done)); + User.findOrCreate(getNewWhere(), INVALID_DATA, {validate: true}, expectValidationError(done)); }); it('should NOT throw on findOrCreate with validate:false with invalid ' + @@ -172,17 +172,17 @@ describe('optional-validation', function() { User.findOrCreate( getNewWhere(), INVALID_DATA, - { validate: false }, + {validate: false}, expectCreateSuccess(INVALID_DATA, done) ); }); it('should NOT throw on findOrCreate with validate:true with valid data', function(done) { - User.findOrCreate(getNewWhere(), VALID_DATA, { validate: true }, expectCreateSuccess(done)); + User.findOrCreate(getNewWhere(), VALID_DATA, {validate: true}, expectCreateSuccess(done)); }); it('should NOT throw on findOrCreate with validate:false with valid data', function(done) { - User.findOrCreate(getNewWhere(), VALID_DATA, { validate: false }, expectCreateSuccess(done)); + User.findOrCreate(getNewWhere(), VALID_DATA, {validate: false}, expectCreateSuccess(done)); }); it('should throw on findOrCreate with invalid data', function(done) { @@ -199,7 +199,7 @@ describe('optional-validation', function() { 'data', function(done) { callUpdateOrCreateWithExistingUserId( null, - { validate: true }, + {validate: true}, expectValidationError(done) ); }); @@ -208,17 +208,17 @@ describe('optional-validation', function() { 'invalid data', function(done) { callUpdateOrCreateWithExistingUserId( null, - { validate: false }, + {validate: false}, expectChangeSuccess(INVALID_DATA, done) ); }); it('should NOT throw on updateOrCreate(id) with validate:true with valid data', function(done) { - callUpdateOrCreateWithExistingUserId(NEW_NAME, { validate: true }, expectChangeSuccess(done)); + callUpdateOrCreateWithExistingUserId(NEW_NAME, {validate: true}, expectChangeSuccess(done)); }); it('should NOT throw on updateOrCreate(id) with validate:false with valid data', function(done) { - callUpdateOrCreateWithExistingUserId(NEW_NAME, { validate: false }, expectChangeSuccess(done)); + callUpdateOrCreateWithExistingUserId(NEW_NAME, {validate: false}, expectChangeSuccess(done)); }); // backwards compatible with validateUpsert @@ -234,25 +234,25 @@ describe('optional-validation', function() { describe('method save', function() { it('should throw on save with {validate:true} with invalid data', function(done) { createUserAndChangeName(null, function(err, d) { - d.save({ validate: true }, expectValidationError(done)); + d.save({validate: true}, expectValidationError(done)); }); }); it('should NOT throw on save with {validate:false} with invalid data', function(done) { createUserAndChangeName(null, function(err, d) { - d.save({ validate: false }, expectChangeSuccess(INVALID_DATA, done)); + d.save({validate: false}, expectChangeSuccess(INVALID_DATA, done)); }); }); it('should NOT throw on save with {validate:true} with valid data', function(done) { createUserAndChangeName(NEW_NAME, function(err, d) { - d.save({ validate: true }, expectChangeSuccess(done)); + d.save({validate: true}, expectChangeSuccess(done)); }); }); it('should NOT throw on save with {validate:false} with valid data', function(done) { createUserAndChangeName(NEW_NAME, function(err, d) { - d.save({ validate: false }, expectChangeSuccess(done)); + d.save({validate: false}, expectChangeSuccess(done)); }); }); @@ -272,25 +272,25 @@ describe('optional-validation', function() { describe('method updateAttributes', function() { it('should throw on updateAttributes with {validate:true} with invalid data', function(done) { createUser(function(err, d) { - d.updateAttributes(INVALID_DATA, { validate: true }, expectValidationError(done)); + d.updateAttributes(INVALID_DATA, {validate: true}, expectValidationError(done)); }); }); it('should NOT throw on updateAttributes with {validate:false} with invalid data', function(done) { createUser(function(err, d) { - d.updateAttributes(INVALID_DATA, { validate: false }, expectChangeSuccess(INVALID_DATA, done)); + d.updateAttributes(INVALID_DATA, {validate: false}, expectChangeSuccess(INVALID_DATA, done)); }); }); it('should NOT throw on updateAttributes with {validate:true} with valid data', function(done) { createUser(function(err, d) { - d.updateAttributes({ 'name': NEW_NAME }, { validate: true }, expectChangeSuccess(done)); + d.updateAttributes({'name': NEW_NAME}, {validate: true}, expectChangeSuccess(done)); }); }); it('should NOT throw on updateAttributes with {validate:false} with valid data', function(done) { createUser(function(err, d) { - d.updateAttributes({ 'name': NEW_NAME }, { validate: false }, expectChangeSuccess(done)); + d.updateAttributes({'name': NEW_NAME}, {validate: false}, expectChangeSuccess(done)); }); }); @@ -302,7 +302,7 @@ describe('optional-validation', function() { it('should NOT throw on updateAttributes(cb) with valid data', function(done) { createUser(function(err, d) { - d.updateAttributes({ 'name': NEW_NAME }, expectChangeSuccess(done)); + d.updateAttributes({'name': NEW_NAME}, expectChangeSuccess(done)); }); }); }); @@ -316,19 +316,19 @@ describe('optional-validation', function() { describe('method create', function() { it('should throw on create with validate:true with invalid data', function(done) { - User.create(INVALID_DATA, { validate: true }, expectValidationError(done)); + User.create(INVALID_DATA, {validate: true}, expectValidationError(done)); }); it('should NOT throw on create with validate:false with invalid data', function(done) { - User.create(INVALID_DATA, { validate: false }, expectCreateSuccess(INVALID_DATA, done)); + User.create(INVALID_DATA, {validate: false}, expectCreateSuccess(INVALID_DATA, done)); }); it('should NOT throw on create with validate:true with valid data', function(done) { - User.create(VALID_DATA, { validate: true }, expectCreateSuccess(done)); + User.create(VALID_DATA, {validate: true}, expectCreateSuccess(done)); }); it('should NOT throw on create with validate:false with valid data', function(done) { - User.create(VALID_DATA, { validate: false }, expectCreateSuccess(done)); + User.create(VALID_DATA, {validate: false}, expectCreateSuccess(done)); }); it('should NOT throw on create with invalid data', function(done) { @@ -342,24 +342,24 @@ describe('optional-validation', function() { describe('method findOrCreate', function() { it('should throw on findOrCreate with validate:true with invalid data', function(done) { - User.findOrCreate(getNewWhere(), INVALID_DATA, { validate: true }, expectValidationError(done)); + User.findOrCreate(getNewWhere(), INVALID_DATA, {validate: true}, expectValidationError(done)); }); it('should NOT throw on findOrCreate with validate:false with invalid data', function(done) { User.findOrCreate( getNewWhere(), INVALID_DATA, - { validate: false }, + {validate: false}, expectCreateSuccess(INVALID_DATA, done) ); }); it('should NOT throw on findOrCreate with validate:true with valid data', function(done) { - User.findOrCreate(getNewWhere(), VALID_DATA, { validate: true }, expectCreateSuccess(done)); + User.findOrCreate(getNewWhere(), VALID_DATA, {validate: true}, expectCreateSuccess(done)); }); it('should NOT throw on findOrCreate with validate:false with valid data', function(done) { - User.findOrCreate(getNewWhere(), VALID_DATA, { validate: false }, expectCreateSuccess(done)); + User.findOrCreate(getNewWhere(), VALID_DATA, {validate: false}, expectCreateSuccess(done)); }); it('should NOT throw on findOrCreate with invalid data', function(done) { @@ -380,7 +380,7 @@ describe('optional-validation', function() { 'data', function(done) { callUpdateOrCreateWithExistingUserId( null, - { validate: true }, + {validate: true}, expectValidationError(done) ); }); @@ -389,17 +389,17 @@ describe('optional-validation', function() { 'invalid data', function(done) { callUpdateOrCreateWithExistingUserId( null, - { validate: false }, + {validate: false}, expectChangeSuccess(INVALID_DATA, done) ); }); it('should NOT throw on updateOrCreate(id) with validate:true with valid data', function(done) { - callUpdateOrCreateWithExistingUserId(NEW_NAME, { validate: true }, expectChangeSuccess(done)); + callUpdateOrCreateWithExistingUserId(NEW_NAME, {validate: true}, expectChangeSuccess(done)); }); it('should NOT throw on updateOrCreate(id) with validate:false with valid data', function(done) { - callUpdateOrCreateWithExistingUserId(NEW_NAME, { validate: false }, expectChangeSuccess(done)); + callUpdateOrCreateWithExistingUserId(NEW_NAME, {validate: false}, expectChangeSuccess(done)); }); it('should NOT throw on updateOrCreate(id) with invalid data', function(done) { @@ -414,25 +414,25 @@ describe('optional-validation', function() { describe('method save', function() { it('should throw on save with {validate:true} with invalid data', function(done) { createUserAndChangeName(null, function(err, d) { - d.save({ validate: true }, expectValidationError(done)); + d.save({validate: true}, expectValidationError(done)); }); }); it('should NOT throw on save with {validate:false} with invalid data', function(done) { createUserAndChangeName(null, function(err, d) { - d.save({ validate: false }, expectChangeSuccess(INVALID_DATA, done)); + d.save({validate: false}, expectChangeSuccess(INVALID_DATA, done)); }); }); it('should NOT throw on save with {validate:true} with valid data', function(done) { createUserAndChangeName(NEW_NAME, function(err, d) { - d.save({ validate: true }, expectChangeSuccess(done)); + d.save({validate: true}, expectChangeSuccess(done)); }); }); it('should NOT throw on save with {validate:false} with valid data', function(done) { createUserAndChangeName(NEW_NAME, function(err, d) { - d.save({ validate: false }, expectChangeSuccess(done)); + d.save({validate: false}, expectChangeSuccess(done)); }); }); @@ -458,19 +458,19 @@ describe('optional-validation', function() { describe('method create', function() { it('should throw on create with validate:true with invalid data', function(done) { - User.create(INVALID_DATA, { validate: true }, expectValidationError(done)); + User.create(INVALID_DATA, {validate: true}, expectValidationError(done)); }); it('should NOT throw on create with validate:false with invalid data', function(done) { - User.create(INVALID_DATA, { validate: false }, expectCreateSuccess(INVALID_DATA, done)); + User.create(INVALID_DATA, {validate: false}, expectCreateSuccess(INVALID_DATA, done)); }); it('should NOT throw on create with validate:true with valid data', function(done) { - User.create(VALID_DATA, { validate: true }, expectCreateSuccess(done)); + User.create(VALID_DATA, {validate: true}, expectCreateSuccess(done)); }); it('should NOT throw on create with validate:false with valid data', function(done) { - User.create(VALID_DATA, { validate: false }, expectCreateSuccess(done)); + User.create(VALID_DATA, {validate: false}, expectCreateSuccess(done)); }); it('should throw on create with invalid data', function(done) { @@ -484,24 +484,24 @@ describe('optional-validation', function() { describe('method findOrCreate', function() { it('should throw on findOrCreate with validate:true with invalid data', function(done) { - User.findOrCreate(getNewWhere(), INVALID_DATA, { validate: true }, expectValidationError(done)); + User.findOrCreate(getNewWhere(), INVALID_DATA, {validate: true}, expectValidationError(done)); }); it('should NOT throw on findOrCreate with validate:false with invalid data', function(done) { User.findOrCreate( getNewWhere(), INVALID_DATA, - { validate: false }, + {validate: false}, expectCreateSuccess(INVALID_DATA, done) ); }); it('should NOT throw on findOrCreate with validate:true with valid data', function(done) { - User.findOrCreate(getNewWhere(), VALID_DATA, { validate: true }, expectCreateSuccess(done)); + User.findOrCreate(getNewWhere(), VALID_DATA, {validate: true}, expectCreateSuccess(done)); }); it('should NOT throw on findOrCreate with validate:false with valid data', function(done) { - User.findOrCreate(getNewWhere(), VALID_DATA, { validate: false }, expectCreateSuccess(done)); + User.findOrCreate(getNewWhere(), VALID_DATA, {validate: false}, expectCreateSuccess(done)); }); it('should throw on findOrCreate with invalid data', function(done) { @@ -518,7 +518,7 @@ describe('optional-validation', function() { 'data', function(done) { callUpdateOrCreateWithExistingUserId( null, - { validate: true }, + {validate: true}, expectValidationError(done) ); }); @@ -527,7 +527,7 @@ describe('optional-validation', function() { 'invalid data', function(done) { callUpdateOrCreateWithExistingUserId( null, - { validate: false }, + {validate: false}, expectChangeSuccess(INVALID_DATA, done) ); }); @@ -536,7 +536,7 @@ describe('optional-validation', function() { 'valid data', function(done) { callUpdateOrCreateWithExistingUserId( NEW_NAME, - { validate: true }, + {validate: true}, expectChangeSuccess(done) ); }); @@ -545,7 +545,7 @@ describe('optional-validation', function() { 'valid data', function(done) { callUpdateOrCreateWithExistingUserId( NEW_NAME, - { validate: false }, + {validate: false}, expectChangeSuccess(done) ); }); @@ -571,19 +571,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 e776f58b..40d7a3a3 100644 --- a/test/persistence-hooks.suite.js +++ b/test/persistence-hooks.suite.js @@ -30,14 +30,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 +53,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 +61,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 +74,7 @@ module.exports = function(dataSource, should, connectorCapabilities) { monitorHookExecution(); TestModel.find( - { where: { id: '1' }}, + {where: {id: '1'}}, function(err, list) { if (err) return done(err); @@ -88,8 +88,8 @@ module.exports = function(dataSource, should, connectorCapabilities) { it('triggers correct hooks when near filter is used', function(done) { monitorHookExecution(); - var query = { where: - { location: { near: '10,20', maxDistance: '10', unit: 'meters' }}, + var query = {where: + {location: {near: '10,20', maxDistance: '10', unit: 'meters'}}, }; TestModel.find(query, function(err, list) { @@ -102,8 +102,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(); @@ -116,8 +116,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(); @@ -127,11 +127,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(); @@ -141,10 +141,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(); }); @@ -161,7 +161,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(); }); @@ -175,10 +175,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(); }); @@ -186,11 +186,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(); @@ -203,7 +203,7 @@ module.exports = function(dataSource, should, connectorCapabilities) { })); TestModel.find( - { where: { id: 1 }}, + {where: {id: 1}}, function(err, list) { if (err) return done(err); @@ -223,7 +223,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(); @@ -236,7 +236,7 @@ module.exports = function(dataSource, should, connectorCapabilities) { monitorHookExecution(); TestModel.create( - { name: 'created' }, + {name: 'created'}, function(err, record, created) { if (err) return done(err); @@ -253,7 +253,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: { @@ -270,7 +270,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(); }); @@ -283,7 +283,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(); @@ -294,7 +294,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 @@ -303,11 +303,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, }), ]); @@ -318,9 +318,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(); }); }); @@ -329,14 +329,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(); @@ -354,7 +354,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); @@ -384,12 +384,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, })); @@ -400,7 +400,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(); @@ -418,7 +418,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); @@ -430,7 +430,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: { @@ -447,7 +447,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(); }); @@ -460,7 +460,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(); @@ -471,7 +471,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 @@ -480,11 +480,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, }), ]); @@ -503,7 +503,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); @@ -514,7 +514,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(); @@ -527,12 +527,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, @@ -546,8 +546,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); @@ -568,8 +568,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, { @@ -588,11 +588,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(); }); }); @@ -601,8 +601,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([ @@ -620,8 +620,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); @@ -646,8 +646,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(); @@ -658,8 +658,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(); @@ -671,8 +671,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); @@ -695,7 +695,7 @@ module.exports = function(dataSource, should, connectorCapabilities) { name: record.name, extra: null, }, - where: { name: existingInstance.name }, + where: {name: existingInstance.name}, })); done(); @@ -707,8 +707,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); @@ -726,7 +726,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, { @@ -735,7 +735,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(); @@ -749,8 +749,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); @@ -782,8 +782,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); @@ -818,8 +818,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); @@ -845,8 +845,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); @@ -865,8 +865,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(); @@ -880,8 +880,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); @@ -906,8 +906,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); @@ -920,8 +920,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, { @@ -940,8 +940,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'); @@ -954,10 +954,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(); }); @@ -965,7 +965,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(); }); @@ -1000,11 +1000,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(); }); }); @@ -1037,7 +1037,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(); }); }); @@ -1061,8 +1061,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(); @@ -1095,7 +1095,7 @@ module.exports = function(dataSource, should, connectorCapabilities) { extra: 'changed', }, isNewInstance: false, - options: { throws: false, validate: true }, + options: {throws: false, validate: true}, })); done(); @@ -1136,7 +1136,7 @@ module.exports = function(dataSource, should, connectorCapabilities) { extra: undefined, }, isNewInstance: false, - options: { throws: false, validate: true }, + options: {throws: false, validate: true}, })); done(); }); @@ -1149,8 +1149,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); @@ -1161,7 +1161,7 @@ module.exports = function(dataSource, should, connectorCapabilities) { extra: undefined, }, isNewInstance: true, - options: { throws: false, validate: true }, + options: {throws: false, validate: true}, })); done(); }); @@ -1196,7 +1196,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([ @@ -1214,12 +1214,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(); @@ -1229,7 +1229,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(); }); @@ -1242,7 +1242,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 @@ -1262,21 +1262,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', @@ -1299,7 +1299,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(); @@ -1308,21 +1308,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; @@ -1341,7 +1341,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); @@ -1352,7 +1352,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(); @@ -1364,11 +1364,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'}, isNewInstance: false, })); @@ -1379,7 +1379,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(); @@ -1396,7 +1396,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(); @@ -1407,7 +1407,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: { @@ -1424,7 +1424,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(); }); @@ -1437,7 +1437,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(); @@ -1453,7 +1453,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([ @@ -1469,7 +1469,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: { @@ -1486,7 +1486,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(); }); @@ -1499,7 +1499,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); @@ -1517,20 +1517,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, @@ -1552,7 +1552,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(); @@ -1561,21 +1561,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; @@ -1589,7 +1589,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); @@ -1600,7 +1600,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(); @@ -1612,7 +1612,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, { @@ -1629,7 +1629,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(); @@ -1641,7 +1641,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(); @@ -1652,7 +1652,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: { @@ -1669,7 +1669,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(); }); @@ -1682,7 +1682,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(); @@ -1696,7 +1696,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([ @@ -1714,7 +1714,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([ @@ -1732,11 +1732,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(); }); @@ -1746,11 +1746,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(); }); @@ -1760,7 +1760,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'); @@ -1770,19 +1770,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(); }); @@ -1791,20 +1791,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(); }); @@ -1815,12 +1815,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']); @@ -1832,7 +1832,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) { @@ -1840,16 +1840,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, })); } @@ -1861,7 +1861,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); @@ -1870,14 +1870,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, })); } @@ -1893,7 +1893,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'); @@ -1912,7 +1912,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'); @@ -1926,10 +1926,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(); }); }); @@ -1940,10 +1940,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(); }); }); @@ -1952,14 +1952,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', @@ -1988,12 +1988,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', @@ -2020,7 +2020,7 @@ 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); @@ -2039,7 +2039,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); ctxRecorder.records.should.eql(aCtxForModel(TestModel, { @@ -2056,7 +2056,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(); @@ -2067,7 +2067,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, { @@ -2086,7 +2086,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, { @@ -2110,7 +2110,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([ @@ -2128,7 +2128,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([ @@ -2146,11 +2146,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(); }); @@ -2160,11 +2160,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(); }); @@ -2174,7 +2174,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'); @@ -2184,19 +2184,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(); }); @@ -2205,20 +2205,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(); }); @@ -2229,12 +2229,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']); @@ -2244,7 +2244,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); @@ -2263,7 +2263,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); @@ -2288,7 +2288,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); @@ -2316,7 +2316,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'); @@ -2328,10 +2328,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(); }); }); @@ -2340,7 +2340,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); @@ -2357,7 +2357,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 @@ -2373,12 +2373,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', @@ -2406,7 +2406,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); @@ -2430,7 +2430,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); @@ -2452,7 +2452,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(); @@ -2463,7 +2463,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); @@ -2488,7 +2488,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); @@ -2514,10 +2514,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(); }); @@ -2528,14 +2528,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(); }); @@ -2552,10 +2552,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(); }); @@ -2566,14 +2566,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(); }); @@ -2606,7 +2606,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(); }); }); @@ -2614,10 +2614,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(); }); @@ -2640,7 +2640,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(); }); @@ -2648,7 +2648,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(); }); @@ -2668,7 +2668,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(); @@ -2677,7 +2677,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(); }); @@ -2711,7 +2711,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(); @@ -2721,10 +2721,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(); }); @@ -2752,13 +2752,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, }), ]); @@ -2769,7 +2769,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(); }); @@ -2786,12 +2786,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(); }); @@ -2799,20 +2799,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(); }); @@ -2823,13 +2823,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(); }); @@ -2837,13 +2837,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) { @@ -2859,14 +2859,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(); @@ -2879,8 +2879,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) { @@ -2894,8 +2894,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'); @@ -2907,13 +2907,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(); }); @@ -2923,9 +2923,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({ @@ -2939,8 +2939,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([ @@ -2961,8 +2961,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([ @@ -2984,12 +2984,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(); }); @@ -2998,12 +2998,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(); }); @@ -3013,12 +3013,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 }, - { name: 'new name' }, + TestModel.upsertWithWhere({id: existingInstance.id}, + {name: 'new name'}, function(err, instance) { if (err) return done(err); hookMonitor.names.should.eql(['access', 'before save']); @@ -3028,19 +3028,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(); }); @@ -3049,20 +3049,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(); }); @@ -3072,12 +3072,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', @@ -3089,7 +3089,7 @@ module.exports = function(dataSource, should, connectorCapabilities) { // null in `currentInstance`, wehere as in `existingInstance` they // are undefined; please see other tests for example see: // test for "PersistedModel.create triggers `persist` hook" - expectedContext.currentInstance = { id: existingInstance.id, name: 'first', extra: null }; + expectedContext.currentInstance = {id: existingInstance.id, name: 'first', extra: null}; } ctxRecorder.records.should.eql(expectedContext); done(); @@ -3099,18 +3099,18 @@ 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, { }); if (dataSource.connector.upsertWithWhere) { - expectedContext.data = { id: 'new-id', name: 'a name' }; - expectedContext.where = { id: 'new-id' }; + expectedContext.data = {id: 'new-id', name: 'a name'}; + expectedContext.where = {id: 'new-id'}; } else { - expectedContext.instance = { id: 'new-id', name: 'a name', extra: null }; + expectedContext.instance = {id: 'new-id', name: 'a name', extra: null}; expectedContext.isNewInstance = true; } ctxRecorder.records.should.eql(expectedContext); @@ -3124,8 +3124,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'); @@ -3143,8 +3143,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'); @@ -3155,11 +3155,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(); }); }); @@ -3167,11 +3167,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(); }); }); @@ -3179,12 +3179,12 @@ 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); var expectedContext = aCtxForModel(TestModel, { - data: { id: 'new-id', name: 'a name' }, + data: {id: 'new-id', name: 'a name'}, currentInstance: { id: 'new-id', name: 'a name', @@ -3192,7 +3192,7 @@ module.exports = function(dataSource, should, connectorCapabilities) { }, }); if (dataSource.connector.upsertWithWhere) { - expectedContext.where = { id: 'new-id' }; + expectedContext.where = {id: 'new-id'}; } else { expectedContext.isNewInstance = true; } @@ -3205,12 +3205,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', @@ -3232,12 +3232,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(); @@ -3247,8 +3247,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); var expectedContext = aCtxForModel(TestModel, { @@ -3265,8 +3265,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(); @@ -3276,8 +3276,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, { @@ -3295,8 +3295,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: { @@ -3334,11 +3334,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 bf52a212..999b8347 100644 --- a/test/relations.test.js +++ b/test/relations.test.js @@ -30,19 +30,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); @@ -100,9 +100,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) { @@ -119,9 +119,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) @@ -138,9 +138,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); }); }); @@ -155,7 +155,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); @@ -170,12 +170,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); @@ -191,7 +191,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); @@ -205,9 +205,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); }); }); @@ -222,7 +222,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); @@ -236,9 +236,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); }); }); @@ -268,10 +268,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); }); }); @@ -292,13 +292,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); @@ -317,9 +317,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); }); }); @@ -330,7 +330,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(); @@ -342,12 +342,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); @@ -358,7 +358,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); @@ -374,9 +374,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); }); }); @@ -397,10 +397,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); @@ -422,7 +422,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); @@ -442,7 +442,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); @@ -465,10 +465,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); }); }); @@ -488,13 +488,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); @@ -511,7 +511,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(); @@ -521,7 +521,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(); @@ -531,7 +531,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(); @@ -541,7 +541,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(); @@ -557,16 +557,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); @@ -587,7 +587,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); @@ -603,7 +603,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(); @@ -620,7 +620,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, }}, @@ -644,7 +644,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, }}) @@ -660,9 +660,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); }); }); @@ -684,12 +684,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); @@ -710,9 +710,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); }); }); @@ -720,19 +720,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); @@ -747,10 +747,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); }); }); @@ -771,13 +771,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); @@ -796,8 +796,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() { @@ -807,7 +807,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); @@ -824,9 +824,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() @@ -838,7 +838,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); @@ -859,9 +859,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); }); }); @@ -882,10 +882,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); }); @@ -906,7 +906,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); @@ -926,7 +926,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) @@ -952,11 +952,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); }); }); @@ -976,13 +976,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); @@ -999,8 +999,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); @@ -1014,9 +1014,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) { @@ -1031,10 +1031,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); @@ -1049,12 +1049,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); @@ -1071,7 +1071,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); @@ -1092,7 +1092,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) @@ -1125,29 +1125,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'); @@ -1167,52 +1167,52 @@ describe('relations', function() { 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 @@ -1221,23 +1221,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'); @@ -1250,12 +1250,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', @@ -1270,15 +1270,15 @@ describe('relations', function() { 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); @@ -1290,8 +1290,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); @@ -1307,12 +1307,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', @@ -1327,14 +1327,14 @@ describe('relations', function() { 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); @@ -1345,7 +1345,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'); @@ -1357,12 +1357,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); @@ -1374,7 +1374,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) { @@ -1390,17 +1390,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); @@ -1409,11 +1409,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'); @@ -1426,11 +1426,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'); @@ -1466,7 +1466,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'); @@ -1478,7 +1478,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); @@ -1583,24 +1583,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); @@ -1611,9 +1611,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); @@ -1624,9 +1624,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); @@ -1667,7 +1667,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); @@ -1690,7 +1690,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); @@ -1702,7 +1702,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(); @@ -1714,7 +1714,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); @@ -1729,13 +1729,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, }); @@ -1769,9 +1769,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()); @@ -1782,9 +1782,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()); @@ -1795,9 +1795,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()); @@ -1838,7 +1838,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); @@ -1850,7 +1850,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); @@ -1862,7 +1862,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(); @@ -1873,7 +1873,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(); @@ -1888,20 +1888,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', @@ -1937,9 +1937,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); @@ -1950,9 +1950,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); @@ -1991,7 +1991,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) { @@ -2004,7 +2004,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) { @@ -2017,7 +2017,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'); @@ -2029,9 +2029,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'); @@ -2040,7 +2040,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); @@ -2052,7 +2052,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) { @@ -2066,7 +2066,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(); @@ -2081,38 +2081,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'); @@ -2123,13 +2123,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(); @@ -2139,10 +2139,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(); @@ -2192,7 +2192,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); @@ -2206,7 +2206,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; @@ -2238,7 +2238,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) { @@ -2249,7 +2249,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) { @@ -2332,7 +2332,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'); @@ -2342,7 +2342,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); @@ -2371,8 +2371,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'); @@ -2383,7 +2383,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'); @@ -2407,13 +2407,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); @@ -2429,13 +2429,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); @@ -2451,13 +2451,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; @@ -2478,7 +2478,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); @@ -2491,7 +2491,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'); @@ -2578,19 +2578,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'); @@ -2615,8 +2615,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'); @@ -2652,18 +2652,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); @@ -2703,14 +2703,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); @@ -2733,11 +2733,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); @@ -2754,11 +2754,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); @@ -2775,11 +2775,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(); }) @@ -2804,7 +2804,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(); @@ -2816,7 +2816,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'); @@ -2826,13 +2826,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'); @@ -2885,7 +2885,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(); }) @@ -2936,18 +2936,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); @@ -2965,7 +2965,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); @@ -2975,7 +2975,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); @@ -2986,8 +2986,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); @@ -2999,11 +2999,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(); }) @@ -3023,7 +3023,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); }) @@ -3064,7 +3064,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'); @@ -3073,11 +3073,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); @@ -3135,7 +3135,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, }); @@ -3143,7 +3143,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', }); @@ -3153,11 +3153,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); @@ -3203,8 +3203,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() { @@ -3217,11 +3217,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(); @@ -3239,9 +3239,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(); @@ -3261,8 +3261,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() { @@ -3275,10 +3275,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); @@ -3295,8 +3295,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); @@ -3304,7 +3304,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); @@ -3331,7 +3331,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); @@ -3364,7 +3364,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() @@ -3394,7 +3394,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) { @@ -3434,13 +3434,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); @@ -3459,14 +3459,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); @@ -3494,19 +3494,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); @@ -3551,7 +3551,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); @@ -3561,26 +3561,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(); }); @@ -3591,7 +3591,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()); @@ -3600,7 +3600,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'); @@ -3625,10 +3625,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(); @@ -3640,7 +3640,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(); }); }); @@ -3664,9 +3664,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; @@ -3675,12 +3675,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(); }); @@ -3691,7 +3691,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()); @@ -3700,7 +3700,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); @@ -3737,10 +3737,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(); @@ -3752,7 +3752,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); }); @@ -3782,7 +3782,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'; @@ -3792,7 +3792,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(); @@ -3831,21 +3831,21 @@ describe('relations', function() { 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'); @@ -3854,9 +3854,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'); @@ -3866,9 +3866,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'); @@ -3882,11 +3882,11 @@ 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', { - 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 +3897,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'); @@ -3913,10 +3913,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); @@ -3928,7 +3928,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; @@ -3941,8 +3941,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); @@ -3954,7 +3954,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); @@ -3987,7 +3987,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); @@ -4032,7 +4032,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'); @@ -4043,7 +4043,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(); @@ -4066,11 +4066,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(); }); @@ -4096,7 +4096,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(); @@ -4107,7 +4107,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(); @@ -4134,9 +4134,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; @@ -4149,27 +4149,27 @@ 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, }); db.automigrate(['Person'], done); }); 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(); }); @@ -4183,8 +4183,8 @@ describe('relations', function() { before(function(done) { tmp = getTransientDataSource(); // 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); @@ -4196,10 +4196,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'); @@ -4222,7 +4222,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']); @@ -4233,7 +4233,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'); @@ -4262,9 +4262,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)', @@ -4274,9 +4274,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(); @@ -4285,7 +4285,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'); @@ -4297,25 +4297,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'); @@ -4325,10 +4325,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(); @@ -4336,8 +4336,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'); @@ -4357,8 +4357,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); @@ -4368,14 +4368,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(); @@ -4383,7 +4383,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(); @@ -4391,7 +4391,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(); @@ -4399,14 +4399,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); @@ -4424,7 +4424,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'); @@ -4447,8 +4447,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(); @@ -4457,8 +4457,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']); @@ -4476,33 +4476,33 @@ 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 }); + Category = db.define('Category', {name: String}); + Job = db.define('Job', {name: String}); + Link = db.define('Link', {name: String, notes: String}); }); 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) { job1 = p; - Job.create({ name: 'Job 2' }, function(err, p) { + Job.create({name: 'Job 2'}, function(err, p) { job2 = p; - Job.create({ name: 'Job 3' }, function(err, p) { + Job.create({name: 'Job 3'}, function(err, p) { job3 = p; done(); }); @@ -4511,7 +4511,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) { var link = cat.items.build(); link.job(job1); var link = cat.items.build(); @@ -4631,10 +4631,10 @@ 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) { 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) { jobId = p.id; cat.links[0].id.should.eql(p.id); cat.links[0].name.should.equal('Job 1'); // denormalized @@ -4649,7 +4649,7 @@ describe('relations', function() { Category.findById(category.id, function(err, cat) { 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 @@ -4666,7 +4666,7 @@ describe('relations', function() { it('should update items on scope - and save parent', function(done) { Category.findById(category.id, function(err, cat) { var link = cat.items.at(0); - link.updateAttributes({ notes: 'Updated notes...' }, function(err, link) { + link.updateAttributes({notes: 'Updated notes...'}, function(err, link) { link.notes.should.equal('Updated notes...'); done(); }); @@ -4677,7 +4677,7 @@ describe('relations', function() { Category.findById(category.id, function(err, cat) { 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(); }); @@ -4708,12 +4708,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'); @@ -4725,22 +4725,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(); }); @@ -4748,8 +4748,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); @@ -4812,7 +4812,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'); @@ -4840,8 +4840,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); }); @@ -4859,9 +4859,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, }}); @@ -4873,9 +4873,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(); }); @@ -4883,10 +4883,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]); @@ -4947,7 +4947,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); @@ -5006,7 +5006,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); @@ -5047,7 +5047,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); @@ -5069,7 +5069,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'); @@ -5111,10 +5111,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; @@ -5124,11 +5124,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]); @@ -5201,7 +5201,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); @@ -5270,7 +5270,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) { @@ -5317,7 +5317,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); @@ -5343,7 +5343,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(); @@ -5394,8 +5394,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); }); @@ -5419,7 +5419,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); @@ -5431,10 +5431,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(); }); }); @@ -5443,8 +5443,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) { @@ -5462,8 +5462,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/scope.test.js b/test/scope.test.js index 9f79eeb2..5cbe4ff2 100644 --- a/test/scope.test.js +++ b/test/scope.test.js @@ -12,7 +12,7 @@ describe('scope', function() { before(function() { db = getSchema(); Railway = db.define('Railway', { - URID: { type: String, index: true }, + URID: {type: String, index: true}, }, { scopes: { highSpeed: { @@ -23,11 +23,11 @@ describe('scope', function() { }, }); Station = db.define('Station', { - USID: { type: String, index: true }, - capacity: { type: Number, index: true }, - thoughput: { type: Number, index: true }, - isActive: { type: Boolean, index: true }, - isUndeground: { type: Boolean, index: true }, + USID: {type: String, index: true}, + capacity: {type: Number, index: true}, + thoughput: {type: Number, index: true}, + isActive: {type: Boolean, index: true}, + isUndeground: {type: Boolean, index: true}, }); }); @@ -43,7 +43,7 @@ describe('scope', function() { }); it('should define scope with query', function(done) { - Station.scope('active', { where: { isActive: true }}); + Station.scope('active', {where: {isActive: true}}); Station.scopes.should.have.property('active'); Station.active.create(function(err, station) { should.not.exist(err); @@ -55,8 +55,8 @@ describe('scope', function() { }); it('should allow scope chaining', function(done) { - Station.scope('active', { where: { isActive: true }}); - Station.scope('subway', { where: { isUndeground: true }}); + Station.scope('active', {where: {isActive: true}}); + Station.scope('subway', {where: {isUndeground: true}}); Station.active.subway.create(function(err, station) { should.not.exist(err); should.exist(station); @@ -67,9 +67,9 @@ describe('scope', function() { }); it('should query all', function(done) { - Station.scope('active', { where: { isActive: true }}); - Station.scope('inactive', { where: { isActive: false }}); - Station.scope('ground', { where: { isUndeground: true }}); + Station.scope('active', {where: {isActive: true}}); + Station.scope('inactive', {where: {isActive: false}}); + Station.scope('ground', {where: {isUndeground: true}}); Station.active.ground.create(function() { Station.inactive.ground.create(function() { Station.ground.inactive(function(err, ss) { @@ -81,7 +81,7 @@ describe('scope', function() { }); it('should not cache any results', function(done) { - Station.scope('active', { where: { isActive: true }}); + Station.scope('active', {where: {isActive: true}}); Station.active.create(function(err, s) { if (err) return done(err); s.isActive.should.be.true; @@ -107,10 +107,10 @@ describe('scope - order', function() { before(function() { db = getSchema(); Station = db.define('Station', { - name: { type: String, index: true }, - order: { type: Number, index: true }, + name: {type: String, index: true}, + order: {type: Number, index: true}, }); - Station.scope('reverse', { order: 'order DESC' }); + Station.scope('reverse', {order: 'order DESC'}); }); beforeEach(function(done) { @@ -118,15 +118,15 @@ describe('scope - order', function() { }); beforeEach(function(done) { - Station.create({ name: 'a', order: 1 }, done); + Station.create({name: 'a', order: 1}, done); }); beforeEach(function(done) { - Station.create({ name: 'b', order: 2 }, done); + Station.create({name: 'b', order: 2}, done); }); beforeEach(function(done) { - Station.create({ name: 'c', order: 3 }, done); + Station.create({name: 'c', order: 3}, done); }); it('should define scope with default order', function(done) { @@ -142,7 +142,7 @@ describe('scope - order', function() { }); it('should override default scope order', function(done) { - Station.reverse({ order: 'order ASC' }, function(err, stations) { + Station.reverse({order: 'order ASC'}, function(err, stations) { stations[0].name.should.equal('a'); stations[0].order.should.equal(1); stations[1].name.should.equal('b'); @@ -160,15 +160,15 @@ describe('scope - filtered count, updateAll and destroyAll', function() { before(function() { db = getSchema(); Station = db.define('Station', { - name: { type: String, index: true }, - order: { type: Number, index: true }, - active: { type: Boolean, index: true, default: true }, - flagged: { type: Boolean, index: true, default: false }, + name: {type: String, index: true}, + order: {type: Number, index: true}, + active: {type: Boolean, index: true, default: true}, + flagged: {type: Boolean, index: true, default: false}, }); - Station.scope('ordered', { order: 'order' }); - Station.scope('active', { where: { active: true }}); - Station.scope('inactive', { where: { active: false }}); - Station.scope('flagged', { where: { flagged: true }}); + Station.scope('ordered', {order: 'order'}); + Station.scope('active', {where: {active: true}}); + Station.scope('inactive', {where: {active: false}}); + Station.scope('flagged', {where: {flagged: true}}); }); beforeEach(function(done) { @@ -176,22 +176,22 @@ describe('scope - filtered count, updateAll and destroyAll', function() { }); beforeEach(function(done) { - Station.create({ name: 'b', order: 2, active: false }, done); + Station.create({name: 'b', order: 2, active: false}, done); }); beforeEach(function(done) { - Station.create({ name: 'a', order: 1 }, function(err, inst) { + Station.create({name: 'a', order: 1}, function(err, inst) { stationA = inst; done(); }); }); beforeEach(function(done) { - Station.create({ name: 'd', order: 4, active: false }, done); + Station.create({name: 'd', order: 4, active: false}, done); }); beforeEach(function(done) { - Station.create({ name: 'c', order: 3 }, done); + Station.create({name: 'c', order: 3}, done); }); it('should find all - verify', function(done) { @@ -215,7 +215,7 @@ describe('scope - filtered count, updateAll and destroyAll', function() { }); it('should find one - with filter', function(done) { - Station.active.findOne({ where: { name: 'c' }}, function(err, station) { + Station.active.findOne({where: {name: 'c'}}, function(err, station) { should.not.exist(err); station.name.should.equal('c'); done(); @@ -255,7 +255,7 @@ describe('scope - filtered count, updateAll and destroyAll', function() { }); it('should count filtered - active', function(done) { - Station.active.count({ order: { gt: 1 }}, function(err, count) { + Station.active.count({order: {gt: 1}}, function(err, count) { should.not.exist(err); count.should.equal(1); done(); @@ -263,7 +263,7 @@ describe('scope - filtered count, updateAll and destroyAll', function() { }); it('should count filtered - inactive', function(done) { - Station.inactive.count({ order: 2 }, function(err, count) { + Station.inactive.count({order: 2}, function(err, count) { should.not.exist(err); count.should.equal(1); done(); @@ -271,7 +271,7 @@ describe('scope - filtered count, updateAll and destroyAll', function() { }); it('should allow updateAll', function(done) { - Station.inactive.updateAll({ flagged: true }, function(err, result) { + Station.inactive.updateAll({flagged: true}, function(err, result) { should.not.exist(err); result.count.should.equal(2); verify(); @@ -287,7 +287,7 @@ describe('scope - filtered count, updateAll and destroyAll', function() { }); it('should allow filtered updateAll', function(done) { - Station.ordered.updateAll({ active: true }, { flagged: true }, function(err, result) { + Station.ordered.updateAll({active: true}, {flagged: true}, function(err, result) { should.not.exist(err); result.count.should.equal(2); verify(); @@ -303,7 +303,7 @@ describe('scope - filtered count, updateAll and destroyAll', function() { }); it('should allow filtered destroyAll', function(done) { - Station.ordered.destroyAll({ active: false }, function(err) { + Station.ordered.destroyAll({active: false}, function(err) { should.not.exist(err); verify(); }); @@ -327,15 +327,15 @@ describe('scope - dynamic target class', function() { before(function() { db = getSchema(); - Image = db.define('Image', { name: String }); - Video = db.define('Video', { name: String }); + Image = db.define('Image', {name: String}); + Video = db.define('Video', {name: String}); - Collection = db.define('Collection', { name: String, modelName: String }); + Collection = db.define('Collection', {name: String, modelName: String}); Collection.scope('items', function() { return {}; // could return a scope based on `this` (receiver) - }, null, {}, { isStatic: false, modelTo: function(receiver) { + }, null, {}, {isStatic: false, modelTo: function(receiver) { return db.models[receiver.modelName]; - } }); + }}); }); beforeEach(function(done) { @@ -347,27 +347,27 @@ describe('scope - dynamic target class', function() { }); beforeEach(function(done) { - Collection.create({ name: 'Images', modelName: 'Image' }, done); + Collection.create({name: 'Images', modelName: 'Image'}, done); }); beforeEach(function(done) { - Collection.create({ name: 'Videos', modelName: 'Video' }, done); + Collection.create({name: 'Videos', modelName: 'Video'}, done); }); beforeEach(function(done) { - Collection.create({ name: 'Things', modelName: 'Unknown' }, done); + Collection.create({name: 'Things', modelName: 'Unknown'}, done); }); beforeEach(function(done) { - Image.create({ name: 'Image A' }, done); + Image.create({name: 'Image A'}, done); }); beforeEach(function(done) { - Video.create({ name: 'Video A' }, done); + Video.create({name: 'Video A'}, done); }); it('should deduce modelTo at runtime - Image', function(done) { - Collection.findOne({ where: { modelName: 'Image' }}, function(err, coll) { + Collection.findOne({where: {modelName: 'Image'}}, function(err, coll) { should.not.exist(err); coll.name.should.equal('Images'); coll.items(function(err, items) { @@ -381,7 +381,7 @@ describe('scope - dynamic target class', function() { }); it('should deduce modelTo at runtime - Video', function(done) { - Collection.findOne({ where: { modelName: 'Video' }}, function(err, coll) { + Collection.findOne({where: {modelName: 'Video'}}, function(err, coll) { should.not.exist(err); coll.name.should.equal('Videos'); coll.items(function(err, items) { @@ -395,7 +395,7 @@ describe('scope - dynamic target class', function() { }); it('should throw if modelTo is invalid', function(done) { - Collection.findOne({ where: { name: 'Things' }}, function(err, coll) { + Collection.findOne({where: {name: 'Things'}}, function(err, coll) { should.not.exist(err); coll.modelName.should.equal('Unknown'); (function() { @@ -411,16 +411,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/transient.test.js b/test/transient.test.js index f2d4c999..def9da00 100644 --- a/test/transient.test.js +++ b/test/transient.test.js @@ -18,14 +18,14 @@ var getTransientDataSource = function(settings) { describe('Transient connector', function() { before(function() { db = getTransientDataSource(); - TransientModel = db.define('TransientModel', {}, { idInjection: false }); + TransientModel = db.define('TransientModel', {}, {idInjection: false}); - Person = TransientModel.extend('Person', { name: String }); + Person = TransientModel.extend('Person', {name: String}); Person.attachTo(db); - Widget = db.define('Widget', { name: String }); + Widget = db.define('Widget', {name: String}); Item = db.define('Item', { - id: { type: Number, id: true }, name: String, + id: {type: Number, id: true}, name: String, }); }); @@ -33,9 +33,9 @@ describe('Transient connector', function() { should.not.exist(Person.definition.properties.id); should.exist(Person.definition.properties.name); - Person.create({ name: 'Wilma' }, function(err, inst) { + Person.create({name: 'Wilma'}, function(err, inst) { should.not.exist(err); - inst.toObject().should.eql({ name: 'Wilma' }); + inst.toObject().should.eql({name: 'Wilma'}); Person.count(function(err, count) { should.not.exist(err); @@ -51,7 +51,7 @@ describe('Transient connector', function() { Widget.definition.properties.id.type.should.equal(String); - Widget.create({ name: 'Thing' }, function(err, inst) { + Widget.create({name: 'Thing'}, function(err, inst) { should.not.exist(err); inst.id.should.match(/^[0-9a-fA-F]{24}$/); inst.name.should.equal('Thing'); @@ -70,7 +70,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 61da2dad..30aaab3f 100644 --- a/test/util.test.js +++ b/test/util.test.js @@ -29,10 +29,10 @@ describe('util.fieldsToArray', function() { sample({}).expect(undefined); sample('foo').expect(['foo']); sample(['foo']).expect(['foo']); - sample({ 'foo': 1 }).expect(['foo']); - sample({ 'bat': true }).expect(['bat']); - sample({ 'bat': 0 }).expect(['foo', 'bar', 'baz']); - sample({ 'bat': false }).expect(['foo', 'bar', 'baz']); + sample({'foo': 1}).expect(['foo']); + sample({'bat': true}).expect(['bat']); + sample({'bat': 0}).expect(['foo', 'bar', 'baz']); + sample({'bat': false}).expect(['foo', 'bar', 'baz']); }); it('should exclude unknown properties', function() { @@ -41,23 +41,23 @@ describe('util.fieldsToArray', function() { sample({}, true).expect(undefined); sample('foo', true).expect(['foo']); sample(['foo', 'unknown'], true).expect(['foo']); - sample({ 'foo': 1, unknown: 1 }, true).expect(['foo']); - sample({ 'bat': true, unknown: true }, true).expect(['bat']); - sample({ 'bat': 0 }, true).expect(['foo', 'bar', 'baz']); - sample({ 'bat': false }, true).expect(['foo', 'bar', 'baz']); + sample({'foo': 1, unknown: 1}, true).expect(['foo']); + sample({'bat': true, unknown: true}, true).expect(['bat']); + sample({'bat': 0}, true).expect(['foo', 'bar', 'baz']); + sample({'bat': false}, true).expect(['foo', 'bar', 'baz']); }); }); describe('util.removeUndefined', function() { it('Remove undefined values from the query object', function() { - var q1 = { where: { x: 1, y: undefined }}; - should.deepEqual(removeUndefined(q1), { where: { x: 1 }}); + var q1 = {where: {x: 1, y: undefined}}; + should.deepEqual(removeUndefined(q1), {where: {x: 1}}); - var q2 = { where: { x: 1, y: 2 }}; - should.deepEqual(removeUndefined(q2), { where: { x: 1, y: 2 }}); + var q2 = {where: {x: 1, y: 2}}; + should.deepEqual(removeUndefined(q2), {where: {x: 1, y: 2}}); - var q3 = { where: { x: 1, y: { in: [2, undefined] }}}; - should.deepEqual(removeUndefined(q3), { where: { x: 1, y: { in: [2] }}}); + var q3 = {where: {x: 1, y: {in: [2, undefined]}}}; + should.deepEqual(removeUndefined(q3), {where: {x: 1, y: {in: [2]}}}); should.equal(removeUndefined(null), null); @@ -66,14 +66,14 @@ describe('util.removeUndefined', function() { should.equal(removeUndefined('x'), 'x'); var date = new Date(); - var q4 = { where: { x: 1, y: date }}; - should.deepEqual(removeUndefined(q4), { where: { x: 1, y: date }}); + var q4 = {where: {x: 1, y: date}}; + should.deepEqual(removeUndefined(q4), {where: {x: 1, y: date}}); // test handling of undefined - var q5 = { where: { x: 1, y: undefined }}; - should.deepEqual(removeUndefined(q5, 'nullify'), { where: { x: 1, y: null }}); + var q5 = {where: {x: 1, y: undefined}}; + should.deepEqual(removeUndefined(q5, 'nullify'), {where: {x: 1, y: null}}); - var q6 = { where: { x: 1, y: undefined }}; + var q6 = {where: {x: 1, y: undefined}}; (function() { removeUndefined(q6, 'throw'); }).should.throw(/`undefined` in query/); }); }); @@ -138,71 +138,71 @@ describe('util.parseSettings', function() { describe('mergeSettings', function() { it('should merge settings correctly', function() { - var src = { base: 'User', - relations: { accessTokens: { model: 'accessToken', type: 'hasMany', - foreignKey: 'userId' }, - account: { model: 'account', type: 'belongsTo' }}, + var src = {base: 'User', + relations: {accessTokens: {model: 'accessToken', type: 'hasMany', + foreignKey: 'userId'}, + account: {model: 'account', type: 'belongsTo'}}, acls: [ - { accessType: '*', + {accessType: '*', permission: 'DENY', principalType: 'ROLE', - principalId: '$everyone' }, - { accessType: '*', + principalId: '$everyone'}, + {accessType: '*', permission: 'ALLOW', principalType: 'ROLE', property: 'login', - principalId: '$everyone' }, - { permission: 'ALLOW', + principalId: '$everyone'}, + {permission: 'ALLOW', property: 'findById', principalType: 'ROLE', - principalId: '$owner' }, - ] }; - var tgt = { strict: false, + principalId: '$owner'}, + ]}; + var tgt = {strict: false, acls: [ - { principalType: 'ROLE', + {principalType: 'ROLE', principalId: '$everyone', permission: 'ALLOW', - property: 'create' }, - { principalType: 'ROLE', + property: 'create'}, + {principalType: 'ROLE', principalId: '$owner', permission: 'ALLOW', - property: 'removeById' }, + property: 'removeById'}, ], maxTTL: 31556926, - ttl: 1209600 }; + ttl: 1209600}; var dst = mergeSettings(tgt, src); - var expected = { strict: false, + var expected = {strict: false, acls: [ - { principalType: 'ROLE', + {principalType: 'ROLE', principalId: '$everyone', permission: 'ALLOW', - property: 'create' }, - { principalType: 'ROLE', + property: 'create'}, + {principalType: 'ROLE', principalId: '$owner', permission: 'ALLOW', - property: 'removeById' }, - { accessType: '*', + property: 'removeById'}, + {accessType: '*', permission: 'DENY', principalType: 'ROLE', - principalId: '$everyone' }, - { accessType: '*', + principalId: '$everyone'}, + {accessType: '*', permission: 'ALLOW', principalType: 'ROLE', property: 'login', - principalId: '$everyone' }, - { permission: 'ALLOW', + principalId: '$everyone'}, + {permission: 'ALLOW', property: 'findById', principalType: 'ROLE', - principalId: '$owner' }, + principalId: '$owner'}, ], maxTTL: 31556926, ttl: 1209600, base: 'User', - relations: { accessTokens: { model: 'accessToken', type: 'hasMany', - foreignKey: 'userId' }, - account: { model: 'account', type: 'belongsTo' }}}; + relations: {accessTokens: {model: 'accessToken', type: 'hasMany', + foreignKey: 'userId'}, + account: {model: 'account', type: 'belongsTo'}}}; should.deepEqual(dst.acls, expected.acls, 'Merged settings should match the expectation'); }); @@ -210,12 +210,12 @@ describe('mergeSettings', function() { describe('sortObjectsByIds', function() { var items = [ - { id: 1, name: 'a' }, - { id: 2, name: 'b' }, - { id: 3, name: 'c' }, - { id: 4, name: 'd' }, - { id: 5, name: 'e' }, - { id: 6, name: 'f' }, + {id: 1, name: 'a'}, + {id: 2, name: 'b'}, + {id: 3, name: 'c'}, + {id: 4, name: 'd'}, + {id: 5, name: 'e'}, + {id: 6, name: 'f'}, ]; it('should sort', function() { @@ -248,8 +248,8 @@ describe('util.mergeIncludes', function() { var baseInclude = 'relation1'; var updateInclude = 'relation2'; var expectedInclude = [ - { relation2: true }, - { relation1: true }, + {relation2: true}, + {relation1: true}, ]; checkInputOutput(baseInclude, updateInclude, expectedInclude); }); @@ -258,18 +258,18 @@ describe('util.mergeIncludes', function() { var baseInclude = 'relation1'; var updateInclude = ['relation2']; var expectedInclude = [ - { relation2: true }, - { relation1: true }, + {relation2: true}, + {relation1: true}, ]; checkInputOutput(baseInclude, updateInclude, expectedInclude); }); it('Merge string & object values to object', function() { var baseInclude = ['relation1']; - var updateInclude = { relation2: 'relation2Include' }; + var updateInclude = {relation2: 'relation2Include'}; var expectedInclude = [ - { relation2: 'relation2Include' }, - { relation1: true }, + {relation2: 'relation2Include'}, + {relation1: true}, ]; checkInputOutput(baseInclude, updateInclude, expectedInclude); }); @@ -278,37 +278,37 @@ describe('util.mergeIncludes', function() { var baseInclude = ['relation1']; var updateInclude = ['relation2']; var expectedInclude = [ - { relation2: true }, - { relation1: true }, + {relation2: true}, + {relation1: true}, ]; checkInputOutput(baseInclude, updateInclude, expectedInclude); }); it('Merge array & object values to object', function() { var baseInclude = ['relation1']; - var updateInclude = { relation2: 'relation2Include' }; + var updateInclude = {relation2: 'relation2Include'}; var expectedInclude = [ - { relation2: 'relation2Include' }, - { relation1: true }, + {relation2: 'relation2Include'}, + {relation1: true}, ]; checkInputOutput(baseInclude, updateInclude, expectedInclude); }); it('Merge object & object values to object', function() { - var baseInclude = { relation1: 'relation1Include' }; - var updateInclude = { relation2: 'relation2Include' }; + var baseInclude = {relation1: 'relation1Include'}; + var updateInclude = {relation2: 'relation2Include'}; var expectedInclude = [ - { relation2: 'relation2Include' }, - { relation1: 'relation1Include' }, + {relation2: 'relation2Include'}, + {relation1: 'relation1Include'}, ]; checkInputOutput(baseInclude, updateInclude, expectedInclude); }); it('Override property collision with update value', function() { - var baseInclude = { relation1: 'baseValue' }; - var updateInclude = { relation1: 'updateValue' }; + var baseInclude = {relation1: 'baseValue'}; + var updateInclude = {relation1: 'updateValue'}; var expectedInclude = [ - { relation1: 'updateValue' }, + {relation1: 'updateValue'}, ]; checkInputOutput(baseInclude, updateInclude, expectedInclude); }); @@ -316,9 +316,9 @@ describe('util.mergeIncludes', function() { it('Merge string includes & include with relation syntax properly', function() { var baseInclude = 'relation1'; - var updateInclude = { relation: 'relation1' }; + var updateInclude = {relation: 'relation1'}; var expectedInclude = [ - { relation: 'relation1' }, + {relation: 'relation1'}, ]; checkInputOutput(baseInclude, updateInclude, expectedInclude); }); @@ -327,10 +327,10 @@ describe('util.mergeIncludes', function() { var baseInclude = 'relation1'; var updateInclude = { relation: 'relation1', - scope: { include: 'relation2' }, + scope: {include: 'relation2'}, }; var expectedInclude = [ - { relation: 'relation1', scope: { include: 'relation2' }}, + {relation: 'relation1', scope: {include: 'relation2'}}, ]; checkInputOutput(baseInclude, updateInclude, expectedInclude); }); @@ -341,39 +341,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 09d16fe3..9a5464ea 100644 --- a/test/validations.test.js +++ b/test/validations.test.js @@ -41,8 +41,8 @@ describe('validations', function() { updatedAt: Date, }); Entry = db.define('Entry', { - id: { type: 'string', id: true, generated: false }, - name: { type: 'string' }, + id: {type: 'string', id: true, generated: false}, + name: {type: 'string'}, }); Entry.validatesUniquenessOf('id'); db.automigrate(done); @@ -62,7 +62,7 @@ describe('validations', function() { describe('commons', function() { describe('skipping', function() { it('should NOT skip when `if` is fulfilled', function() { - User.validatesPresenceOf('pendingPeriod', { if: 'createdByAdmin' }); + User.validatesPresenceOf('pendingPeriod', {if: 'createdByAdmin'}); var user = new User; user.createdByAdmin = true; user.isValid().should.be.false; @@ -72,7 +72,7 @@ describe('validations', function() { }); it('should skip when `if` is NOT fulfilled', function() { - User.validatesPresenceOf('pendingPeriod', { if: 'createdByAdmin' }); + User.validatesPresenceOf('pendingPeriod', {if: 'createdByAdmin'}); var user = new User; user.createdByAdmin = false; user.isValid().should.be.true; @@ -82,7 +82,7 @@ describe('validations', function() { }); it('should NOT skip when `unless` is fulfilled', function() { - User.validatesPresenceOf('pendingPeriod', { unless: 'createdByAdmin' }); + User.validatesPresenceOf('pendingPeriod', {unless: 'createdByAdmin'}); var user = new User; user.createdByAdmin = false; user.isValid().should.be.false; @@ -92,7 +92,7 @@ describe('validations', function() { }); it('should skip when `unless` is NOT fulfilled', function() { - User.validatesPresenceOf('pendingPeriod', { unless: 'createdByAdmin' }); + User.validatesPresenceOf('pendingPeriod', {unless: 'createdByAdmin'}); var user = new User; user.createdByAdmin = true; user.isValid().should.be.true; @@ -107,7 +107,7 @@ describe('validations', function() { User.validateAsync('pendingPeriod', function(err, done) { if (!this.pendingPeriod) err(); done(); - }, { if: 'createdByAdmin', code: 'presence', message: 'can\'t be blank' }); + }, {if: 'createdByAdmin', code: 'presence', message: 'can\'t be blank'}); var user = new User; user.createdByAdmin = false; user.isValid(function(valid) { @@ -121,7 +121,7 @@ describe('validations', function() { User.validateAsync('pendingPeriod', function(err, done) { if (!this.pendingPeriod) err(); done(); - }, { if: 'createdByAdmin', code: 'presence', message: 'can\'t be blank' }); + }, {if: 'createdByAdmin', code: 'presence', message: 'can\'t be blank'}); var user = new User; user.createdByAdmin = true; user.isValid(function(valid) { @@ -135,7 +135,7 @@ describe('validations', function() { User.validateAsync('pendingPeriod', function(err, done) { if (!this.pendingPeriod) err(); done(); - }, { unless: 'createdByAdmin', code: 'presence', message: 'can\'t be blank' }); + }, {unless: 'createdByAdmin', code: 'presence', message: 'can\'t be blank'}); var user = new User; user.createdByAdmin = true; user.isValid(function(valid) { @@ -149,7 +149,7 @@ describe('validations', function() { User.validateAsync('pendingPeriod', function(err, done) { if (!this.pendingPeriod) err(); done(); - }, { unless: 'createdByAdmin', code: 'presence', message: 'can\'t be blank' }); + }, {unless: 'createdByAdmin', code: 'presence', message: 'can\'t be blank'}); var user = new User; user.createdByAdmin = false; user.isValid(function(valid) { @@ -166,7 +166,7 @@ describe('validations', function() { User.validatesPresenceOf('name'); User.create(function(e, u) { should.exist(e); - User.create({ name: 'Valid' }, function(e, d) { + User.create({name: 'Valid'}, function(e, d) { should.not.exist(e); done(); }); @@ -176,7 +176,7 @@ describe('validations', function() { it('should work on update', function(done) { delete User.validations; User.validatesPresenceOf('name'); - User.create({ name: 'Valid' }, function(e, d) { + User.create({name: 'Valid'}, function(e, d) { d.updateAttribute('name', null, function(e) { should.exist(e); e.should.be.instanceOf(Error); @@ -194,7 +194,7 @@ describe('validations', function() { User.validatesPresenceOf('name'); // It's important to pass an id value, otherwise DAO falls back // to regular create() - User.updateOrCreate({ id: 999 }, done); + User.updateOrCreate({id: 999}, done); }); it('should be skipped by upsert when disabled via settings', function(done) { @@ -208,7 +208,7 @@ describe('validations', function() { Customer.settings.validateUpsert = false; // It's important to pass an id value, otherwise DAO falls back // to regular create() - Customer.updateOrCreate({ id: 999 }, done); + Customer.updateOrCreate({id: 999}, done); }); }); @@ -218,7 +218,7 @@ describe('validations', function() { User.settings.validateUpsert = true; // It's important to pass an id value, otherwise DAO falls back // to regular create() - User.upsert({ id: 999 }, function(err, u) { + User.upsert({id: 999}, function(err, u) { if (!err) return done(new Error('Validation should have failed.')); err.should.be.instanceOf(ValidationError); done(); @@ -273,7 +273,7 @@ describe('validations', function() { }); it('should return validation metadata', function() { - var expected = { name: [{ validation: 'presence', options: {}}] }; + var expected = {name: [{validation: 'presence', options: {}}]}; delete User.validations; User.validatesPresenceOf('name'); var validations = User.validations; @@ -286,12 +286,12 @@ describe('validations', function() { it('should work on update with options', function(done) { delete User.validations; User.validatesPresenceOf('name'); - User.create({ name: 'Valid' }, function(e, d) { - d.updateAttribute('name', null, { options: 'options' }, function(e) { + User.create({name: 'Valid'}, function(e, d) { + d.updateAttribute('name', null, {options: 'options'}, function(e) { should.exist(e); e.should.be.instanceOf(Error); e.should.be.instanceOf(ValidationError); - d.updateAttribute('name', 'Vasiliy', { options: 'options' }, function(e) { + d.updateAttribute('name', 'Vasiliy', {options: 'options'}, function(e) { should.not.exist(e); done(); }); @@ -302,7 +302,7 @@ describe('validations', function() { it('should work on update without options', function(done) { delete User.validations; User.validatesPresenceOf('name'); - User.create({ name: 'Valid' }, function(e, d) { + User.create({name: 'Valid'}, function(e, d) { d.updateAttribute('name', null, function(e) { should.exist(e); e.should.be.instanceOf(Error); @@ -320,7 +320,7 @@ describe('validations', function() { User.validatesPresenceOf('name'); User.create(function(e, u) { should.exist(e); - User.create({ name: 'Valid' }, { options: 'options' }, function(e, d) { + User.create({name: 'Valid'}, {options: 'options'}, function(e, d) { should.not.exist(e); done(); }); @@ -332,7 +332,7 @@ describe('validations', function() { User.validatesPresenceOf('name'); User.create(function(e, u) { should.exist(e); - User.create({ name: 'Valid' }, function(e, d) { + User.create({name: 'Valid'}, function(e, d) { should.not.exist(e); done(); }); @@ -345,8 +345,8 @@ describe('validations', function() { User.validatesPresenceOf('name', 'email'); var validations = User.validations; - validations.name.should.eql([{ validation: 'presence', options: {}}]); - validations.email.should.eql([{ validation: 'presence', options: {}}]); + validations.name.should.eql([{validation: 'presence', options: {}}]); + validations.email.should.eql([{validation: 'presence', options: {}}]); var u = new User; u.isValid().should.not.be.true; @@ -375,7 +375,7 @@ describe('validations', function() { }); it('should skip validation by property (if/unless)', function() { - User.validatesPresenceOf('domain', { unless: 'createdByScript' }); + User.validatesPresenceOf('domain', {unless: 'createdByScript'}); var user = new User(getValidAttributes()); user.isValid().should.be.true; @@ -391,12 +391,12 @@ describe('validations', function() { describe('absence', function() { it('should validate absence', function() { - User.validatesAbsenceOf('reserved', { if: 'locked' }); - var u = new User({ reserved: 'foo', locked: true }); + User.validatesAbsenceOf('reserved', {if: 'locked'}); + var u = new User({reserved: 'foo', locked: true}); u.isValid().should.not.be.true; u.reserved = null; u.isValid().should.be.true; - var u = new User({ reserved: 'foo', locked: false }); + var u = new User({reserved: 'foo', locked: false}); u.isValid().should.be.true; }); }); @@ -404,11 +404,11 @@ describe('validations', function() { describe('uniqueness', function() { it('should validate uniqueness', function(done) { User.validatesUniquenessOf('email'); - var u = new User({ email: 'hey' }); + var u = new User({email: 'hey'}); Boolean(u.isValid(function(valid) { valid.should.be.true; u.save(function() { - var u2 = new User({ email: 'hey' }); + var u2 = new User({email: 'hey'}); u2.isValid(function(valid) { valid.should.be.false; done(); @@ -419,7 +419,7 @@ describe('validations', function() { it('should handle same object modification', function(done) { User.validatesUniquenessOf('email'); - var u = new User({ email: 'hey' }); + var u = new User({email: 'hey'}); Boolean(u.isValid(function(valid) { valid.should.be.true; u.save(function() { @@ -439,23 +439,23 @@ describe('validations', function() { siteId: String, email: String, }); - SiteUser.validatesUniquenessOf('email', { scopedTo: ['siteId'] }); + SiteUser.validatesUniquenessOf('email', {scopedTo: ['siteId']}); async.waterfall([ function automigrate(next) { db.automigrate(next); }, function createSite1User(next) { SiteUser.create( - { siteId: 1, email: EMAIL }, + {siteId: 1, email: EMAIL}, next); }, function createSite2User(user1, next) { SiteUser.create( - { siteId: 2, email: EMAIL }, + {siteId: 2, email: EMAIL}, next); }, function validateDuplicateUser(user2, next) { - var user3 = new SiteUser({ siteId: 1, email: EMAIL }); + var user3 = new SiteUser({siteId: 1, email: EMAIL}); user3.isValid(function(valid) { valid.should.be.false; next(); @@ -471,11 +471,11 @@ describe('validations', function() { it('should skip blank values', function(done) { User.validatesUniquenessOf('email'); - var u = new User({ email: ' ' }); + var u = new User({email: ' '}); Boolean(u.isValid(function(valid) { valid.should.be.true; u.save(function() { - var u2 = new User({ email: null }); + var u2 = new User({email: null}); u2.isValid(function(valid) { valid.should.be.true; done(); @@ -489,7 +489,7 @@ describe('validations', function() { if: function() { return true; }, unless: function() { return false; }, }); - var u = new User({ email: 'hello' }); + var u = new User({email: 'hello'}); Boolean(u.isValid(function(valid) { valid.should.be.true; done(); @@ -497,8 +497,8 @@ describe('validations', function() { }); it('should work with id property on create', function(done) { - Entry.create({ id: 'entry' }, function(err, entry) { - var e = new Entry({ id: 'entry' }); + Entry.create({id: 'entry'}, function(err, entry) { + var e = new Entry({id: 'entry'}); Boolean(e.isValid(function(valid) { valid.should.be.false; done(); @@ -521,26 +521,26 @@ describe('validations', function() { it('should overwrite default blank message with custom format message'); it('should skip missing values when allowing null', function() { - User.validatesFormatOf('email', { with: /^\S+@\S+\.\S+$/, allowNull: true }); + User.validatesFormatOf('email', {with: /^\S+@\S+\.\S+$/, allowNull: true}); var u = new User({}); u.isValid().should.be.true; }); it('should skip null values when allowing null', function() { - User.validatesFormatOf('email', { with: /^\S+@\S+\.\S+$/, allowNull: true }); - var u = new User({ email: null }); + User.validatesFormatOf('email', {with: /^\S+@\S+\.\S+$/, allowNull: true}); + var u = new User({email: null}); u.isValid().should.be.true; }); it('should not skip missing values', function() { - User.validatesFormatOf('email', { with: /^\S+@\S+\.\S+$/ }); + User.validatesFormatOf('email', {with: /^\S+@\S+\.\S+$/}); var u = new User({}); u.isValid().should.be.false; }); it('should not skip null values', function() { - User.validatesFormatOf('email', { with: /^\S+@\S+\.\S+$/ }); - var u = new User({ email: null }); + User.validatesFormatOf('email', {with: /^\S+@\S+\.\S+$/}); + var u = new User({email: null}); u.isValid().should.be.false; }); }); @@ -565,10 +565,10 @@ describe('validations', function() { it('should validate using custom sync validation', function() { User.validate('email', function(err) { if (this.email === 'hello') err(); - }, { code: 'invalid-email' }); - var u = new User({ email: 'hello' }); + }, {code: 'invalid-email'}); + var u = new User({email: 'hello'}); Boolean(u.isValid()).should.be.false; - u.errors.codes.should.eql({ email: ['invalid-email'] }); + u.errors.codes.should.eql({email: ['invalid-email']}); }); it('should validate and return detailed error messages', function() { @@ -578,10 +578,10 @@ describe('validations', function() { err(false); // false: prevent global error message } }); - var u = new User({ email: 'hello' }); + var u = new User({email: 'hello'}); Boolean(u.isValid()).should.be.false; - u.errors.should.eql({ email: ['Cannot be `hello`'] }); - u.errors.codes.should.eql({ email: ['invalid-email'] }); + u.errors.should.eql({email: ['Cannot be `hello`']}); + u.errors.codes.should.eql({email: ['invalid-email']}); }); it('should validate using custom async validation', function(done) { @@ -591,7 +591,7 @@ describe('validations', function() { if: function() { return true; }, unless: function() { return false; }, }); - var u = new User({ email: 'hello' }); + var u = new User({email: 'hello'}); Boolean(u.isValid(function(valid) { valid.should.be.true; done(); @@ -618,26 +618,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] } ]).'); });