diff --git a/examples/app-noschema.js b/examples/app-noschema.js index 830af704..0da64cfc 100644 --- a/examples/app-noschema.js +++ b/examples/app-noschema.js @@ -10,36 +10,36 @@ var introspectType = require('../lib/introspection')(ModelBuilder); var ds = new DataSource('memory'); // Create a open model that doesn't require a schema -var Application = ds.createModel('Schemaless', {}, {strict: false}); +var Application = ds.createModel('Schemaless', {}, { strict: false }); var application = { owner: 'rfeng', name: 'MyApp1', description: 'My first app', pushSettings: [ - { "platform": "apns", - "apns": { - "pushOptions": { - "gateway": "gateway.sandbox.push.apple.com", - "cert": "credentials/apns_cert_dev.pem", - "key": "credentials/apns_key_dev.pem" + { 'platform': 'apns', + 'apns': { + 'pushOptions': { + 'gateway': 'gateway.sandbox.push.apple.com', + 'cert': 'credentials/apns_cert_dev.pem', + 'key': 'credentials/apns_key_dev.pem', }, - "feedbackOptions": { - "gateway": "feedback.sandbox.push.apple.com", - "cert": "credentials/apns_cert_dev.pem", - "key": "credentials/apns_key_dev.pem", - "batchFeedback": true, - "interval": 300 - } - }} - ]} + 'feedbackOptions': { + 'gateway': 'feedback.sandbox.push.apple.com', + 'cert': 'credentials/apns_cert_dev.pem', + 'key': 'credentials/apns_key_dev.pem', + 'batchFeedback': true, + 'interval': 300, + }, + }}, + ] }; console.log(new Application(application).toObject()); -Application.create(application, function (err, app1) { +Application.create(application, function(err, app1) { console.log('Created: ', app1.toObject()); - Application.findById(app1.id, function (err, app2) { + Application.findById(app1.id, function(err, app2) { console.log('Found: ', app2.toObject()); }); }); @@ -55,30 +55,30 @@ var user = { city: 'San Jose', state: 'CA', zipcode: '95131', - country: 'US' + country: 'US', }, friends: ['John', 'Mary'], emails: [ - {label: 'work', id: 'x@sample.com'}, - {label: 'home', id: 'x@home.com'} + { label: 'work', id: 'x@sample.com' }, + { label: 'home', id: 'x@home.com' }, ], - tags: [] + tags: [], }; // Introspect the JSON document to generate a schema var schema = introspectType(user); // Create a model for the generated schema -var User = ds.createModel('User', schema, {idInjection: true}); +var User = ds.createModel('User', schema, { idInjection: true }); // Use the model for CRUD var obj = new User(user); console.log(obj.toObject()); -User.create(user, function (err, u1) { +User.create(user, function(err, u1) { console.log('Created: ', u1.toObject()); - User.findById(u1.id, function (err, u2) { + User.findById(u1.id, function(err, u2) { console.log('Found: ', u2.toObject()); }); }); diff --git a/examples/app.js b/examples/app.js index 8a96baec..f4392ec7 100644 --- a/examples/app.js +++ b/examples/app.js @@ -9,11 +9,11 @@ var modelBuilder = new ModelBuilder(); var Post = modelBuilder.define('Post', { title: { type: String, length: 255 }, content: { type: ModelBuilder.Text }, - date: { type: Date, default: function () { + date: { type: Date, default: function() { return new Date(); } }, timestamp: { type: Number, default: Date.now }, - published: { type: Boolean, default: false, index: true } + published: { type: Boolean, default: false, index: true }, }); // simpler way to describe model @@ -22,24 +22,24 @@ var User = modelBuilder.define('User', { bio: ModelBuilder.Text, approved: Boolean, joinedAt: Date, - age: Number + age: Number, }); -var Group = modelBuilder.define('Group', {group: String}); +var Group = modelBuilder.define('Group', { group: String }); // define any custom method -User.prototype.getNameAndAge = function () { +User.prototype.getNameAndAge = function() { return this.name + ', ' + this.age; }; -var user = new User({name: 'Joe'}); +var user = new User({ name: 'Joe' }); console.log(user); console.log(modelBuilder.models); console.log(modelBuilder.definitions); User.mixin(Group); -var user = new User({name: 'Ray', group: 'Admin'}); +var user = new User({ name: 'Ray', group: 'Admin' }); console.log(user); diff --git a/examples/datasource-app.js b/examples/datasource-app.js index df142bfe..fe9e656e 100644 --- a/examples/datasource-app.js +++ b/examples/datasource-app.js @@ -11,11 +11,11 @@ var ds = new DataSource('memory'); var Post = ds.define('Post', { title: { type: String, length: 255 }, content: { type: DataSource.Text }, - date: { type: Date, default: function () { + date: { type: Date, default: function() { return new Date; } }, timestamp: { type: Number, default: Date.now }, - published: { type: Boolean, default: false, index: true } + published: { type: Boolean, default: false, index: true }, }); // simplier way to describe model @@ -24,31 +24,31 @@ var User = ds.define('User', { bio: DataSource.Text, approved: Boolean, joinedAt: Date, - age: Number + age: Number, }); -var Group = ds.define('Group', {name: String}); +var Group = ds.define('Group', { name: String }); // define any custom method -User.prototype.getNameAndAge = function () { +User.prototype.getNameAndAge = function() { return this.name + ', ' + this.age; }; -var user = new User({name: 'Joe'}); +var user = new User({ name: 'Joe' }); console.log(user); // console.log(ds.models); // console.log(ds.definitions); // setup relationships -User.hasMany(Post, {as: 'posts', foreignKey: 'userId'}); +User.hasMany(Post, { as: 'posts', foreignKey: 'userId' }); // creates instance methods: // user.posts(conds) // user.posts.build(data) // like new Post({userId: user.id}); // user.posts.create(data) // build and save -Post.belongsTo(User, {as: 'author', foreignKey: 'userId'}); +Post.belongsTo(User, { as: 'author', foreignKey: 'userId' }); // creates instance methods: // post.author(callback) -- getter when called with function // post.author() -- sync getter when called without params @@ -56,46 +56,46 @@ Post.belongsTo(User, {as: 'author', foreignKey: 'userId'}); User.hasAndBelongsToMany('groups'); -var user2 = new User({name: 'Smith', age: 14}); -user2.save(function (err) { +var user2 = new User({ name: 'Smith', age: 14 }); +user2.save(function(err) { console.log(user2); - var post = user2.posts.build({title: 'Hello world'}); - post.save(function (err, data) { + var post = user2.posts.build({ title: 'Hello world' }); + post.save(function(err, data) { console.log(err ? err : data); }); }); -Post.findOne({where: {published: false}, order: 'date DESC'}, function (err, data) { +Post.findOne({ where: { published: false }, order: 'date DESC' }, function(err, data) { console.log(data); }); -User.create({name: 'Jeff', age: 12}, function (err, data) { +User.create({ name: 'Jeff', age: 12 }, function(err, data) { if (err) { console.log(err); return; } console.log(data); - var post = data.posts.build({title: 'My Post'}); + var post = data.posts.build({ title: 'My Post' }); console.log(post); }); -User.create({name: 'Ray'}, function (err, data) { +User.create({ name: 'Ray' }, function(err, data) { console.log(data); }); -User.scope('minors', {where: {age: {lte: 16}}, include: 'posts'}); -User.minors(function (err, kids) { +User.scope('minors', { where: { age: { lte: 16 }}, include: 'posts' }); +User.minors(function(err, kids) { console.log('Kids: ', kids); }); -var Article = ds.define('Article', {title: String}); -var Tag = ds.define('Tag', {name: String}); +var Article = ds.define('Article', { title: String }); +var Tag = ds.define('Tag', { name: String }); Article.hasAndBelongsToMany('tags'); -Article.create(function (e, article) { - article.tags.create({name: 'popular'}, function (err, data) { - Article.findOne(function (e, article) { - article.tags(function (e, tags) { +Article.create(function(e, article) { + article.tags.create({ name: 'popular' }, function(err, data) { + Article.findOne(function(e, article) { + article.tags(function(e, tags) { console.log(tags); }); }); @@ -106,17 +106,17 @@ Article.create(function (e, article) { var modelBuilder = new ModelBuilder(); Color = modelBuilder.define('Color', { - name: String + name: String, }); // attach ds.attach(Color); -Color.create({name: 'red'}); -Color.create({name: 'green'}); -Color.create({name: 'blue'}); +Color.create({ name: 'red' }); +Color.create({ name: 'green' }); +Color.create({ name: 'blue' }); -Color.all(function (err, colors) { +Color.all(function(err, colors) { console.log(colors); }); diff --git a/examples/inclusion.js b/examples/inclusion.js index 5bca6398..148f98b1 100644 --- a/examples/inclusion.js +++ b/examples/inclusion.js @@ -8,54 +8,54 @@ var jdb = require('../index'); var User, Post, Passport, City, Street, Building; var nbSchemaRequests = 0; -setup(function () { +setup(function() { - Passport.find({include: 'owner'}, function (err, passports) { + Passport.find({ include: 'owner' }, function(err, passports) { console.log('passports.owner', passports); }); - User.find({include: 'posts'}, function (err, users) { + User.find({ include: 'posts' }, function(err, users) { console.log('users.posts', users); }); - Passport.find({include: {owner: 'posts'}}, function (err, passports) { + Passport.find({ include: { owner: 'posts' }}, function(err, passports) { console.log('passports.owner.posts', passports); }); Passport.find({ - include: {owner: {posts: 'author'}} - }, function (err, passports) { + include: { owner: { posts: 'author' }}, + }, function(err, passports) { console.log('passports.owner.posts.author', passports); }); - User.find({include: ['posts', 'passports']}, function (err, users) { + User.find({ include: ['posts', 'passports'] }, function(err, users) { console.log('users.passports && users.posts', users); }); }); function setup(done) { - var db = new jdb.DataSource({connector: 'memory'}); + var db = new jdb.DataSource({ connector: 'memory' }); City = db.define('City'); Street = db.define('Street'); Building = db.define('Building'); User = db.define('User', { name: String, - age: Number + age: Number, }); Passport = db.define('Passport', { - number: String + number: String, }); Post = db.define('Post', { - title: String + title: String, }); - Passport.belongsTo('owner', {model: User}); - User.hasMany('passports', {foreignKey: 'ownerId'}); - User.hasMany('posts', {foreignKey: 'userId'}); - Post.belongsTo('author', {model: User, foreignKey: 'userId'}); + Passport.belongsTo('owner', { model: User }); + User.hasMany('passports', { foreignKey: 'ownerId' }); + User.hasMany('posts', { foreignKey: 'userId' }); + Post.belongsTo('author', { model: User, foreignKey: 'userId' }); - db.automigrate(function () { + db.automigrate(function() { var createdUsers = []; var createdPassports = []; var createdPosts = []; @@ -64,13 +64,13 @@ function setup(done) { clearAndCreate( User, [ - {name: 'User A', age: 21}, - {name: 'User B', age: 22}, - {name: 'User C', age: 23}, - {name: 'User D', age: 24}, - {name: 'User E', age: 25} + { name: 'User A', age: 21 }, + { name: 'User B', age: 22 }, + { name: 'User C', age: 23 }, + { name: 'User D', age: 24 }, + { name: 'User E', age: 25 }, ], - function (items) { + function(items) { createdUsers = items; createPassports(); } @@ -81,11 +81,11 @@ function setup(done) { clearAndCreate( Passport, [ - {number: '1', ownerId: createdUsers[0].id}, - {number: '2', ownerId: createdUsers[1].id}, - {number: '3'} + { number: '1', ownerId: createdUsers[0].id }, + { number: '2', ownerId: createdUsers[1].id }, + { number: '3' }, ], - function (items) { + function(items) { createdPassports = items; createPosts(); } @@ -96,13 +96,13 @@ function setup(done) { clearAndCreate( Post, [ - {title: 'Post A', userId: createdUsers[0].id}, - {title: 'Post B', userId: createdUsers[0].id}, - {title: 'Post C', userId: createdUsers[0].id}, - {title: 'Post D', userId: createdUsers[1].id}, - {title: 'Post E'} + { title: 'Post A', userId: createdUsers[0].id }, + { title: 'Post B', userId: createdUsers[0].id }, + { title: 'Post C', userId: createdUsers[0].id }, + { title: 'Post D', userId: createdUsers[1].id }, + { title: 'Post E' }, ], - function (items) { + function(items) { createdPosts = items; done(); } @@ -114,7 +114,7 @@ function setup(done) { function clearAndCreate(model, data, callback) { var createdItems = []; - model.destroyAll(function () { + model.destroyAll(function() { nextItem(null, null); }); diff --git a/examples/nesting-schema.js b/examples/nesting-schema.js index e7c8ac37..0588dba5 100644 --- a/examples/nesting-schema.js +++ b/examples/nesting-schema.js @@ -18,21 +18,21 @@ var User = modelBuilder.define('User', { city: String, state: String, zipCode: String, - country: String + country: String, }, emails: [ { label: String, - email: String - } + email: String, + }, ], - friends: [String] + friends: [String], }); -var user = new User({name: 'Joe', age: 20, address: {street: '123 Main St', 'city': 'San Jose', state: 'CA'}, +var user = new User({ name: 'Joe', age: 20, address: { street: '123 Main St', 'city': 'San Jose', state: 'CA' }, emails: [ - {label: 'work', email: 'xyz@sample.com'} + { label: 'work', email: 'xyz@sample.com' }, ], - friends: ['John', 'Mary']}); + friends: ['John', 'Mary'] }); console.log(user); console.log(user.toObject()); diff --git a/examples/relations.js b/examples/relations.js index f4afd159..6374497f 100644 --- a/examples/relations.js +++ b/examples/relations.js @@ -9,55 +9,55 @@ var ds = new DataSource('memory'); var Order = ds.createModel('Order', { items: [String], orderDate: Date, - qty: Number + qty: Number, }); var Customer = ds.createModel('Customer', { - name: String + name: String, }); Order.belongsTo(Customer); var order1, order2, order3; -Customer.create({name: 'John'}, function (err, customer) { - Order.create({customerId: customer.id, orderDate: new Date(), items: ['Book']}, function (err, order) { +Customer.create({ name: 'John' }, function(err, customer) { + Order.create({ customerId: customer.id, orderDate: new Date(), items: ['Book'] }, function(err, order) { order1 = order; order.customer(console.log); order.customer(true, console.log); - Customer.create({name: 'Mary'}, function (err, customer2) { + Customer.create({ name: 'Mary' }, function(err, customer2) { order.customer(customer2); order.customer(console.log); }); }); - Order.create({orderDate: new Date(), items: ['Phone']}, function (err, order) { + Order.create({ orderDate: new Date(), items: ['Phone'] }, function(err, order) { - order.customer.create({name: 'Smith'}, function(err, customer2) { + order.customer.create({ name: 'Smith' }, function(err, customer2) { console.log(order, customer2); order.save(function(err, order) { order2 = order; }); }); - var customer3 = order.customer.build({name: 'Tom'}); + var customer3 = order.customer.build({ name: 'Tom' }); console.log('Customer 3', customer3); }); }); -Customer.hasMany(Order, {as: 'orders', foreignKey: 'customerId'}); +Customer.hasMany(Order, { as: 'orders', foreignKey: 'customerId' }); -Customer.create({name: 'Ray'}, function (err, customer) { - Order.create({customerId: customer.id, qty: 3, orderDate: new Date()}, function (err, order) { +Customer.create({ name: 'Ray' }, function(err, customer) { + Order.create({ customerId: customer.id, qty: 3, orderDate: new Date() }, function(err, order) { order3 = order; customer.orders(console.log); - customer.orders.create({orderDate: new Date(), qty: 4}, function (err, order) { + customer.orders.create({ orderDate: new Date(), qty: 4 }, function(err, order) { console.log(order); - Customer.include([customer], 'orders', function (err, results) { + Customer.include([customer], 'orders', function(err, results) { console.log('Results: ', results); }); - customer.orders({where: {qty: 4}}, function(err, results) { + customer.orders({ where: { qty: 4 }}, function(err, results) { console.log('customer.orders', results); }); customer.orders.findById(order3.id, console.log); @@ -67,43 +67,43 @@ Customer.create({name: 'Ray'}, function (err, customer) { }); var Physician = ds.createModel('Physician', { - name: String + name: String, }); var Patient = ds.createModel('Patient', { - name: String + name: String, }); var Appointment = ds.createModel('Appointment', { physicianId: Number, patientId: Number, - appointmentDate: Date + appointmentDate: Date, }); Appointment.belongsTo(Patient); Appointment.belongsTo(Physician); -Physician.hasMany(Patient, {through: Appointment}); -Patient.hasMany(Physician, {through: Appointment}); +Physician.hasMany(Patient, { through: Appointment }); +Patient.hasMany(Physician, { through: Appointment }); -Physician.create({name: 'Dr John'}, function (err, physician1) { - Physician.create({name: 'Dr Smith'}, function (err, physician2) { - Patient.create({name: 'Mary'}, function (err, patient1) { - Patient.create({name: 'Ben'}, function (err, patient2) { - Appointment.create({appointmentDate: new Date(), physicianId: physician1.id, patientId: patient1.id}, - function (err, appt1) { - Appointment.create({appointmentDate: new Date(), physicianId: physician1.id, patientId: patient2.id}, - function (err, appt2) { +Physician.create({ name: 'Dr John' }, function(err, physician1) { + Physician.create({ name: 'Dr Smith' }, function(err, physician2) { + Patient.create({ name: 'Mary' }, function(err, patient1) { + Patient.create({ name: 'Ben' }, function(err, patient2) { + Appointment.create({ appointmentDate: new Date(), physicianId: physician1.id, patientId: patient1.id }, + function(err, appt1) { + Appointment.create({ appointmentDate: new Date(), physicianId: physician1.id, patientId: patient2.id }, + function(err, appt2) { physician1.patients(console.log); - physician1.patients({where: {name: 'Mary'}}, console.log); + physician1.patients({ where: { name: 'Mary' }}, console.log); patient1.physicians(console.log); // Build an appointment? - var patient3 = patient1.physicians.build({name: 'Dr X'}); + var patient3 = patient1.physicians.build({ name: 'Dr X' }); console.log('Physician 3: ', patient3, patient3.constructor.modelName); // Create a physician? - patient1.physicians.create({name: 'Dr X'}, function(err, patient4) { + patient1.physicians.create({ name: 'Dr X' }, function(err, patient4) { console.log('Physician 4: ', patient4, patient4.constructor.modelName); }); @@ -116,32 +116,32 @@ Physician.create({name: 'Dr John'}, function (err, physician1) { }); var Assembly = ds.createModel('Assembly', { - name: String + name: String, }); var Part = ds.createModel('Part', { - partNumber: String + partNumber: String, }); Assembly.hasAndBelongsToMany(Part); Part.hasAndBelongsToMany(Assembly); -Assembly.create({name: 'car'}, function (err, assembly) { - Part.create({partNumber: 'engine'}, function (err, part) { - assembly.parts.add(part, function (err) { +Assembly.create({ name: 'car' }, function(err, assembly) { + Part.create({ partNumber: 'engine' }, function(err, part) { + assembly.parts.add(part, function(err) { assembly.parts(function(err, parts) { console.log('Parts: ', parts); }); // Build an part? - var part3 = assembly.parts.build({partNumber: 'door'}); + var part3 = assembly.parts.build({ partNumber: 'door' }); console.log('Part3: ', part3, part3.constructor.modelName); // Create a part? - assembly.parts.create({partNumber: 'door'}, function(err, part4) { + assembly.parts.create({ partNumber: 'door' }, function(err, part4) { console.log('Part4: ', part4, part4.constructor.modelName); - Assembly.find({include: 'parts'}, function(err, assemblies) { + Assembly.find({ include: 'parts' }, function(err, assemblies) { console.log('Assemblies: ', assemblies); }); }); diff --git a/index.js b/index.js index 298e4ab0..a20d104d 100644 --- a/index.js +++ b/index.js @@ -10,12 +10,12 @@ exports.GeoPoint = require('./lib/geo.js').GeoPoint; exports.ValidationError = require('./lib/validations.js').ValidationError; Object.defineProperty(exports, 'version', { - get: function() {return require('./package.json').version;} + get: function() { return require('./package.json').version; }, }); var commonTest = './test/common_test'; Object.defineProperty(exports, 'test', { - get: function() {return require(commonTest);} + get: function() { return require(commonTest); }, }); exports.Transaction = require('loopback-connector').Transaction; diff --git a/lib/connectors/memory.js b/lib/connectors/memory.js index b3b39497..0464876f 100644 --- a/lib/connectors/memory.js +++ b/lib/connectors/memory.js @@ -49,7 +49,7 @@ Memory.prototype.getTypes = function() { return ['db', 'nosql', 'memory']; }; -Memory.prototype.connect = function (callback) { +Memory.prototype.connect = function(callback) { if (this.isTransaction) { this.onTransactionExec = callback; } else { @@ -58,17 +58,17 @@ Memory.prototype.connect = function (callback) { }; function serialize(obj) { - if(obj === null || obj === undefined) { + if (obj === null || obj === undefined) { return obj; } return JSON.stringify(obj); } function deserialize(dbObj) { - if(dbObj === null || dbObj === undefined) { + if (dbObj === null || dbObj === undefined) { return dbObj; } - if(typeof dbObj === 'string') { + if (typeof dbObj === 'string') { return JSON.parse(dbObj); } else { return dbObj; @@ -81,12 +81,12 @@ Memory.prototype.getCollection = function(model) { model = modelClass.settings.memory.collection || model; } return model; -} +}; Memory.prototype.initCollection = function(model) { this.collection(model, {}); this.collectionSeq(model, 1); -} +}; Memory.prototype.collection = function(model, val) { model = this.getCollection(model); @@ -106,14 +106,14 @@ Memory.prototype.loadFromFile = function(callback) { var localStorage = hasLocalStorage && this.settings.localStorage; if (self.settings.file) { - fs.readFile(self.settings.file, {encoding: 'utf8', flag: 'r'}, function (err, data) { + fs.readFile(self.settings.file, { encoding: 'utf8', flag: 'r' }, function(err, data) { if (err && err.code !== 'ENOENT') { callback && callback(err); } else { parseAndLoad(data); } }); - } else if(localStorage) { + } else if (localStorage) { var data = window.localStorage.getItem(localStorage); data = data || '{}'; parseAndLoad(data); @@ -125,14 +125,14 @@ Memory.prototype.loadFromFile = function(callback) { if (data) { try { data = JSON.parse(data.toString()); - } catch(e) { + } catch (e) { return callback(e); } self.ids = data.ids || {}; self.cache = data.models || {}; } else { - if(!self.cache) { + if (!self.cache) { self.ids = {}; self.cache = {}; } @@ -145,22 +145,22 @@ Memory.prototype.loadFromFile = function(callback) { * Flush the cache into the json file if necessary * @param {Function} callback */ -Memory.prototype.saveToFile = function (result, callback) { +Memory.prototype.saveToFile = function(result, callback) { var self = this; var file = this.settings.file; var hasLocalStorage = typeof window !== 'undefined' && window.localStorage; var localStorage = hasLocalStorage && this.settings.localStorage; if (file) { - if(!self.writeQueue) { + if (!self.writeQueue) { // Create a queue for writes - self.writeQueue = async.queue(function (task, cb) { + self.writeQueue = async.queue(function(task, cb) { // Flush out the models/ids var data = JSON.stringify({ ids: self.ids, - models: self.cache + models: self.cache, }, null, ' '); - fs.writeFile(self.settings.file, data, function (err) { + fs.writeFile(self.settings.file, data, function(err) { cb(err); task.callback && task.callback(err, task.data); }); @@ -169,20 +169,20 @@ Memory.prototype.saveToFile = function (result, callback) { // Enqueue the write self.writeQueue.push({ data: result, - callback: callback + callback: callback, }); } else if (localStorage) { // Flush out the models/ids var data = JSON.stringify({ ids: self.ids, - models: self.cache + models: self.cache, }, null, ' '); window.localStorage.setItem(localStorage, data); - process.nextTick(function () { + process.nextTick(function() { callback && callback(null, result); }); } else { - process.nextTick(function () { + process.nextTick(function() { callback && callback(null, result); }); } @@ -191,7 +191,7 @@ Memory.prototype.saveToFile = function (result, callback) { Memory.prototype.define = function defineModel(definition) { this.constructor.super_.prototype.define.apply(this, [].slice.call(arguments)); var m = definition.model.modelName; - if(!this.collection(m)) this.initCollection(m); + if (!this.collection(m)) this.initCollection(m); }; Memory.prototype._createSync = function(model, data, fn) { @@ -235,15 +235,15 @@ Memory.prototype.create = function create(model, data, options, callback) { }); }; -Memory.prototype.updateOrCreate = function (model, data, options, callback) { +Memory.prototype.updateOrCreate = function(model, data, options, callback) { var self = this; - this.exists(model, self.getIdValue(model, data), options, function (err, exists) { + this.exists(model, self.getIdValue(model, data), options, function(err, exists) { if (exists) { self.save(model, data, options, function(err, data) { callback(err, data, { isNewInstance: false }); }); } else { - self.create(model, data, options, function (err, id) { + self.create(model, data, options, function(err, id) { self.setIdValue(model, data, id); callback(err, data, { isNewInstance: true }); }); @@ -256,7 +256,7 @@ Memory.prototype.findOrCreate = function(model, filter, data, callback) { var nodes = self._findAllSkippingIncludes(model, filter); var found = nodes[0]; - if(!found) { + if (!found) { // Calling _createSync to update the collection in a sync way and to guarantee to create it in the same turn of even loop return self._createSync(model, data, function(err, id) { if (err) return callback(err); @@ -272,7 +272,7 @@ Memory.prototype.findOrCreate = function(model, filter, data, callback) { callback(null, found, false); }); } - + self._models[model].model.include(nodes[0], filter.include, {}, function(err, nodes) { process.nextTick(function() { if (err) return callback(err); @@ -297,13 +297,13 @@ Memory.prototype.save = function save(model, data, options, callback) { }; Memory.prototype.exists = function exists(model, id, options, callback) { - process.nextTick(function () { + process.nextTick(function() { callback(null, this.collection(model) && this.collection(model).hasOwnProperty(id)); }.bind(this)); }; Memory.prototype.find = function find(model, id, options, callback) { - process.nextTick(function () { + process.nextTick(function() { callback(null, id in this.collection(model) && this.fromDb(model, this.collection(model)[id])); }.bind(this)); }; @@ -314,7 +314,7 @@ Memory.prototype.destroy = function destroy(model, id, options, callback) { this.saveToFile({ count: exists ? 1 : 0 }, callback); }; -Memory.prototype.fromDb = function (model, data) { +Memory.prototype.fromDb = function(model, data) { if (!data) return null; data = deserialize(data); var props = this._models[model].properties; @@ -357,7 +357,7 @@ function getValue(obj, path) { } Memory.prototype._findAllSkippingIncludes = function(model, filter) { - var nodes = Object.keys(this.collection(model)).map(function (key) { + var nodes = Object.keys(this.collection(model)).map(function(key) { return this.fromDb(model, this.collection(model)[key]); }.bind(this)); @@ -371,17 +371,17 @@ Memory.prototype._findAllSkippingIncludes = function(model, filter) { // do we need some sorting? if (filter.order) { var orders = filter.order; - if (typeof filter.order === "string") { + if (typeof filter.order === 'string') { orders = [filter.order]; } - orders.forEach(function (key, i) { + orders.forEach(function(key, i) { var reverse = 1; var m = key.match(/\s+(A|DE)SC$/i); if (m) { key = key.replace(/\s+(A|DE)SC/i, ''); if (m[1].toLowerCase() === 'de') reverse = -1; } - orders[i] = {"key": key, "reverse": reverse}; + orders[i] = { 'key': key, 'reverse': reverse }; }); nodes = nodes.sort(sorting.bind(orders)); } @@ -408,7 +408,7 @@ Memory.prototype._findAllSkippingIncludes = function(model, filter) { nodes = nodes.slice(skip, skip + limit); } return nodes; - + function sorting(a, b) { var undefinedA, undefinedB; @@ -448,18 +448,18 @@ function applyFilter(filter) { return where; } var keys = Object.keys(where); - return function (obj) { + return function(obj) { return keys.every(function(key) { - if(key === 'and' || key === 'or') { - if(Array.isArray(where[key])) { - if(key === 'and') { + if (key === 'and' || key === 'or') { + if (Array.isArray(where[key])) { + if (key === 'and') { return where[key].every(function(cond) { - return applyFilter({where: cond})(obj); + return applyFilter({ where: cond })(obj); }); } - if(key === 'or') { + if (key === 'or') { return where[key].some(function(cond) { - return applyFilter({where: cond})(obj); + return applyFilter({ where: cond })(obj); }); } } @@ -475,8 +475,8 @@ function applyFilter(filter) { if (matcher.neq !== undefined && value.length <= 0) { return true; } - return value.some(function (v, i) { - var filter = {where: {}}; + return value.some(function(v, i) { + var filter = { where: {}}; filter.where[i] = matcher; return applyFilter(filter)(value); }); @@ -492,15 +492,15 @@ function applyFilter(filter) { var dotIndex = key.indexOf('.'); var subValue = obj[key.substring(0, dotIndex)]; if (dotIndex !== -1 && Array.isArray(subValue)) { - var subFilter = {where: {}}; - var subKey = key.substring(dotIndex+1); + var subFilter = { where: {}}; + var subKey = key.substring(dotIndex + 1); subFilter.where[subKey] = where[key]; return subValue.some(applyFilter(subFilter)); } return false; }); - } + }; function toRegExp(pattern) { if (pattern instanceof RegExp) { @@ -509,7 +509,7 @@ function applyFilter(filter) { var regex = ''; // Escaping user input to be treated as a literal string within a regular expression // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions#Writing_a_Regular_Expression_Pattern - pattern = pattern.replace(/([.*+?^=!:${}()|\[\]\/\\])/g, "\\$1"); + pattern = pattern.replace(/([.*+?^=!:${}()|\[\]\/\\])/g, '\\$1'); for (var i = 0, n = pattern.length; i < n; i++) { var char = pattern.charAt(i); if (char === '\\') { @@ -526,8 +526,7 @@ function applyFilter(filter) { regex += '\\.'; } else if (char === '*') { regex += '\\*'; - } - else { + } else { regex += char; } } @@ -567,13 +566,12 @@ function applyFilter(filter) { return compare(example.neq, value) !== 0; } - if ('between' in example ) { - return ( testInEquality({gte:example.between[0]}, value) && - testInEquality({lte:example.between[1]}, value) ); + if ('between' in example) { + return (testInEquality({ gte: example.between[0] }, value) && + testInEquality({ lte: example.between[1] }, value)); } if (example.like || example.nlike) { - var like = example.like || example.nlike; if (typeof like === 'string') { like = toRegExp(like); @@ -592,8 +590,8 @@ function applyFilter(filter) { } } // not strict equality - return (example !== null ? example.toString() : example) - == (value != null ? value.toString() : value); + return (example !== null ? example.toString() : example) == + (value != null ? value.toString() : value); } /** @@ -604,7 +602,7 @@ function applyFilter(filter) { * @private */ function compare(val1, val2) { - if(val1 == null || val2 == null) { + if (val1 == null || val2 == null) { // Either val1 or val2 is null or undefined return val1 == val2 ? 0 : NaN; } @@ -647,8 +645,8 @@ Memory.prototype.destroyAll = function destroyAll(model, where, options, callbac var filter = null; var count = 0; if (where) { - filter = applyFilter({where: where}); - Object.keys(cache).forEach(function (id) { + filter = applyFilter({ where: where }); + Object.keys(cache).forEach(function(id) { if (!filter || filter(this.fromDb(model, cache[id]))) { count++; delete cache[id]; @@ -665,13 +663,13 @@ Memory.prototype.count = function count(model, where, options, callback) { var cache = this.collection(model); var data = Object.keys(cache); if (where) { - var filter = {where: where}; - data = data.map(function (id) { + var filter = { where: where }; + data = data.map(function(id) { return this.fromDb(model, cache[id]); }.bind(this)); data = data.filter(applyFilter(filter)); } - process.nextTick(function () { + process.nextTick(function() { callback(null, data.length); }); }; @@ -682,11 +680,11 @@ Memory.prototype.update = var cache = this.collection(model); var filter = null; where = where || {}; - filter = applyFilter({where: where}); + filter = applyFilter({ where: where }); var ids = Object.keys(cache); var count = 0; - async.each(ids, function (id, done) { + async.each(ids, function(id, done) { var inst = self.fromDb(model, cache[id]); if (!filter || filter(inst)) { count++; @@ -697,9 +695,9 @@ Memory.prototype.update = } else { process.nextTick(done); } - }, function (err) { + }, function(err) { if (err) return cb(err); - self.saveToFile({count: count}, cb); + self.saveToFile({ count: count }, cb); }); }; @@ -745,16 +743,16 @@ Memory.prototype.replaceById = function(model, id, data, options, cb) { } var newModelData = {}; - for(var key in data) { + for (var key in data) { var val = data[key]; - if(typeof val === 'function') { + if (typeof val === 'function') { continue; // Skip methods } newModelData[key] = val; } this.collection(model)[id] = serialize(newModelData); - this.saveToFile(newModelData, function (err) { + this.saveToFile(newModelData, function(err) { cb(err, self.fromDb(model, newModelData)); }); }; @@ -763,13 +761,13 @@ Memory.prototype.replaceOrCreate = function(model, data, options, callback) { var self = this; var idName = self.idNames(model)[0]; var idValue = self.getIdValue(model, data); - var filter = {where: {}}; + var filter = { where: {}}; filter.where[idName] = idValue; var nodes = self._findAllSkippingIncludes(model, filter); var found = nodes[0]; if (!found) { - // Calling _createSync to update the collection in a sync way and + // Calling _createSync to update the collection in a sync way and // to guarantee to create it in the same turn of even loop return self._createSync(model, data, function(err, id) { if (err) return process.nextTick(function() { cb(err); }); @@ -782,24 +780,24 @@ Memory.prototype.replaceOrCreate = function(model, data, options, callback) { var id = self.getIdValue(model, data); self.collection(model)[id] = serialize(data); self.saveToFile(data, function(err) { - callback(err, self.fromDb(model, data), {isNewInstance: false}); + callback(err, self.fromDb(model, data), { isNewInstance: false }); }); }; -Memory.prototype.transaction = function () { +Memory.prototype.transaction = function() { return new Memory(this); }; -Memory.prototype.exec = function (callback) { +Memory.prototype.exec = function(callback) { this.onTransactionExec(); setTimeout(callback, 50); }; -Memory.prototype.buildNearFilter = function (filter) { +Memory.prototype.buildNearFilter = function(filter) { // noop -} +}; -Memory.prototype.automigrate = function (models, cb) { +Memory.prototype.automigrate = function(models, cb) { var self = this; if ((!cb) && ('function' === typeof models)) { @@ -831,7 +829,7 @@ Memory.prototype.automigrate = function (models, cb) { self.initCollection(m); }); if (cb) process.nextTick(cb); -} +}; function merge(base, update) { if (!base) { @@ -839,9 +837,9 @@ function merge(base, update) { } // We cannot use Object.keys(update) if the update is an instance of the model // class as the properties are defined at the ModelClass.prototype level - for(var key in update) { + for (var key in update) { var val = update[key]; - if(typeof val === 'function') { + if (typeof val === 'function') { continue; // Skip methods } base[key] = val; diff --git a/lib/connectors/transient.js b/lib/connectors/transient.js index d1ef9967..fa39a01e 100644 --- a/lib/connectors/transient.js +++ b/lib/connectors/transient.js @@ -47,7 +47,7 @@ Transient.prototype.getTypes = function() { return ['db', 'nosql', 'transient']; }; -Transient.prototype.connect = function (callback) { +Transient.prototype.connect = function(callback) { if (this.isTransaction) { this.onTransactionExec = callback; } else { @@ -63,26 +63,26 @@ Transient.prototype.generateId = function(model, data, idName) { if (idType === Number) { return Math.floor(Math.random() * 10000); // max. 4 digits } else { - return crypto.randomBytes(Math.ceil(24/2)) + return crypto.randomBytes(Math.ceil(24 / 2)) .toString('hex') // convert to hexadecimal format .slice(0, 24); // return required number of characters } }; Transient.prototype.exists = function exists(model, id, callback) { - process.nextTick(function () { callback(null, false); }.bind(this)); + process.nextTick(function() { callback(null, false); }.bind(this)); }; Transient.prototype.find = function find(model, id, callback) { - process.nextTick(function () { callback(null, null); }.bind(this)); + process.nextTick(function() { callback(null, null); }.bind(this)); }; Transient.prototype.all = function all(model, filter, callback) { - process.nextTick(function () { callback(null, []); }); + process.nextTick(function() { callback(null, []); }); }; Transient.prototype.count = function count(model, callback, where) { - process.nextTick(function () { callback(null, 0); }); + process.nextTick(function() { callback(null, 0); }); }; Transient.prototype.create = function create(model, data, callback) { @@ -103,8 +103,8 @@ Transient.prototype.save = function save(model, data, callback) { Transient.prototype.update = Transient.prototype.updateAll = function updateAll(model, where, data, cb) { var count = 0; - this.flush('update', {count: count}, cb); -}; + this.flush('update', { count: count }, cb); + }; Transient.prototype.updateAttributes = function updateAttributes(model, id, data, cb) { if (!id) { @@ -136,15 +136,15 @@ Transient.prototype.destroyAll = function destroyAll(model, where, callback) { * Flush the cache - noop. * @param {Function} callback */ -Transient.prototype.flush = function (action, result, callback) { - process.nextTick(function () { callback && callback(null, result); }); +Transient.prototype.flush = function(action, result, callback) { + process.nextTick(function() { callback && callback(null, result); }); }; -Transient.prototype.transaction = function () { +Transient.prototype.transaction = function() { return new Transient(this); }; -Transient.prototype.exec = function (callback) { +Transient.prototype.exec = function(callback) { this.onTransactionExec(); setTimeout(callback, 50); }; diff --git a/lib/dao.js b/lib/dao.js index ebe9f00d..0bc0b586 100644 --- a/lib/dao.js +++ b/lib/dao.js @@ -42,7 +42,7 @@ function DataAccessObject() { if (DataAccessObject._mixins) { var self = this; var args = arguments; - DataAccessObject._mixins.forEach(function (m) { + DataAccessObject._mixins.forEach(function(m) { m.call(self, args); }); } @@ -106,7 +106,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; } @@ -121,7 +121,7 @@ function isWhereByGivenId(Model, where, idValue) { return where[pk] === idValue; } -DataAccessObject._forDB = function (data) { +DataAccessObject._forDB = function(data) { if (!(this.getDataSource().isRelational && this.getDataSource().isRelational())) { return data; } @@ -177,7 +177,7 @@ DataAccessObject.lookupModel = function(data) { */ DataAccessObject.getConnector = function() { return this.getDataSource().connector; -} +}; // Empty callback function function noCallback(err, result) { @@ -202,7 +202,7 @@ function noCallback(err, result) { * - err (null or Error) * - instance (null or Model) */ -DataAccessObject.create = function (data, options, cb) { +DataAccessObject.create = function(data, options, cb) { var connectionPromise = stillConnecting(this.getDataSource(), this, arguments); if (connectionPromise) { return connectionPromise; @@ -251,7 +251,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) { @@ -296,7 +296,7 @@ DataAccessObject.create = function (data, options, cb) { instance: obj, isNewInstance: true, hookState: hookState, - options: options + options: options, }; Model.notifyObserversOf('before save', context, function(err) { if (err) return cb(err); @@ -312,9 +312,9 @@ DataAccessObject.create = function (data, options, cb) { if (options.validate === undefined && Model.settings.automaticValidation === false) { return create(); } - + // validation required - obj.isValid(function (valid) { + obj.isValid(function(valid) { if (valid) { create(); } else { @@ -324,8 +324,8 @@ DataAccessObject.create = function (data, options, cb) { }); function create() { - obj.trigger('create', function (createDone) { - obj.trigger('save', function (saveDone) { + obj.trigger('create', function(createDone) { + obj.trigger('save', function(saveDone) { var _idName = idName(Model); var modelName = Model.modelName; var val = removeUndefined(obj.toObject(true)); @@ -347,7 +347,7 @@ DataAccessObject.create = function (data, options, cb) { data: val, isNewInstance: true, hookState: hookState, - options: options + options: options, }; Model.notifyObserversOf('loaded', context, function(err) { if (err) return cb(err); @@ -356,11 +356,11 @@ DataAccessObject.create = function (data, options, cb) { // with the changes made through persist/loaded hooks. To preserve // backwards compatibility, we introduced a new setting updateOnLoad, // which if set, will apply these changes to the model instance too. - if(Model.settings.updateOnLoad) { + if (Model.settings.updateOnLoad) { obj.setAttributes(context.data); } - saveDone.call(obj, function () { - createDone.call(obj, function () { + saveDone.call(obj, function() { + createDone.call(obj, function() { if (err) { return cb(err, obj); } @@ -369,12 +369,12 @@ DataAccessObject.create = function (data, options, cb) { instance: obj, isNewInstance: true, hookState: hookState, - options: options + options: options, }; Model.notifyObserversOf('after save', context, function(err) { cb(err, obj); - if(!err) Model.emit('changed', obj); + if (!err) Model.emit('changed', obj); }); }); }); @@ -387,7 +387,7 @@ DataAccessObject.create = function (data, options, cb) { isNewInstance: true, currentInstance: obj, hookState: hookState, - options: options + options: options, }; Model.notifyObserversOf('persist', context, function(err) { if (err) return cb(err); @@ -409,13 +409,13 @@ DataAccessObject.create = function (data, options, cb) { }; function stillConnecting(dataSource, obj, args) { - if (typeof args[args.length-1] === 'function') { + if (typeof args[args.length - 1] === 'function') { return dataSource.ready(obj, args); } // promise variant var promiseArgs = Array.prototype.slice.call(args); - promiseArgs.callee = args.callee + promiseArgs.callee = args.callee; var cb = utils.createPromiseCallback(); promiseArgs.push(cb); if (dataSource.ready(obj, promiseArgs)) { @@ -483,21 +483,21 @@ DataAccessObject.upsert = function(data, options, cb) { Model: Model, query: byIdQuery(Model, id), hookState: hookState, - options: options + options: options, }; Model.notifyObserversOf('access', context, doUpdateOrCreate); function doUpdateOrCreate(err, ctx) { if (err) return cb(err); - var isOriginalQuery = isWhereByGivenId(Model, ctx.query.where, id) + var isOriginalQuery = isWhereByGivenId(Model, ctx.query.where, id); if (connector.updateOrCreate && isOriginalQuery) { var context = { Model: Model, where: ctx.query.where, data: data, hookState: hookState, - options: options + options: options, }; Model.notifyObserversOf('before save', context, function(err, ctx) { if (err) return cb(err); @@ -522,7 +522,7 @@ DataAccessObject.upsert = function(data, options, cb) { doValidate = Model.settings.automaticValidation; } } else { - doValidate = Model.settings.validateUpsert + doValidate = Model.settings.validateUpsert; } } else { doValidate = options.validate; @@ -554,7 +554,7 @@ DataAccessObject.upsert = function(data, options, cb) { data: update, currentInstance: inst, hookState: ctx.hookState, - options: options + options: options, }; Model.notifyObserversOf('persist', context, function(err) { if (err) return done(err); @@ -570,7 +570,7 @@ DataAccessObject.upsert = function(data, options, cb) { Model: Model, data: data, hookState: ctx.hookState, - options: options + options: options, }; Model.notifyObserversOf('loaded', context, function(err) { if (err) return cb(err); @@ -584,7 +584,7 @@ DataAccessObject.upsert = function(data, options, cb) { } if (err) { cb(err, obj); - if(!err) { + if (!err) { Model.emit('changed', inst); } } else { @@ -593,12 +593,12 @@ DataAccessObject.upsert = function(data, options, cb) { instance: obj, isNewInstance: info ? info.isNewInstance : undefined, hookState: hookState, - options: options + options: options, }; Model.notifyObserversOf('after save', context, function(err) { cb(err, obj); - if(!err) { + if (!err) { Model.emit('changed', inst); } }); @@ -607,11 +607,11 @@ DataAccessObject.upsert = function(data, options, cb) { } }); } else { - var opts = {notify: false}; + var opts = { notify: false }; if (ctx.options && ctx.options.transaction) { opts.transaction = ctx.options.transaction; } - Model.findOne({where: ctx.query.where}, opts, function (err, inst){ + Model.findOne({ where: ctx.query.where }, opts, function(err, inst) { if (err) { return cb(err); } @@ -674,20 +674,20 @@ DataAccessObject.replaceOrCreate = function replaceOrCreate(data, options, cb) { if (id === undefined || id === null) { return this.create(data, options, cb); } - + var inst; if (data instanceof Model) { inst = data; } else { inst = new Model(data); } - - var strict = inst.__strict; + + var strict = inst.__strict; var context = { Model: Model, query: byIdQuery(Model, id), hookState: hookState, - options: options + options: options, }; Model.notifyObserversOf('access', context, doReplaceOrCreate); @@ -701,7 +701,7 @@ DataAccessObject.replaceOrCreate = function replaceOrCreate(data, options, cb) { Model: Model, instance: inst, hookState: hookState, - options: options + options: options, }; Model.notifyObserversOf('before save', context, function(err, ctx) { if (err) return cb(err); @@ -712,7 +712,7 @@ DataAccessObject.replaceOrCreate = function replaceOrCreate(data, options, cb) { validateAndCallConnector(); } - function validateAndCallConnector(err){ + function validateAndCallConnector(err) { if (err) return cb(err); Model.applyProperties(update, inst); Model = Model.lookupModel(update); @@ -741,7 +741,7 @@ DataAccessObject.replaceOrCreate = function replaceOrCreate(data, options, cb) { data: update, currentInstance: inst, hookState: ctx.hookState, - options: options + options: options, }; Model.notifyObserversOf('persist', context, function(err) { if (err) return done(err); @@ -755,7 +755,7 @@ DataAccessObject.replaceOrCreate = function replaceOrCreate(data, options, cb) { data: data, isNewInstance: info ? info.isNewInstance : undefined, hookState: ctx.hookState, - options: options + options: options, }; Model.notifyObserversOf('loaded', context, function(err) { if (err) return cb(err); @@ -775,7 +775,7 @@ DataAccessObject.replaceOrCreate = function replaceOrCreate(data, options, cb) { instance: obj, isNewInstance: info ? info.isNewInstance : undefined, hookState: hookState, - options: options + options: options, }; Model.notifyObserversOf('after save', context, function(err) { @@ -789,11 +789,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 @@ -838,14 +838,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') { @@ -856,7 +856,7 @@ DataAccessObject.findOrCreate = function findOrCreate(query, data, options, cb) } cb = cb || utils.createPromiseCallback(); - query = query || {where: {}}; + query = query || { where: {}}; data = data || {}; options = options || {}; @@ -879,7 +879,7 @@ DataAccessObject.findOrCreate = function findOrCreate(query, data, options, cb) data: data, isNewInstance: created, hookState: hookState, - options: options + options: options, }; Model.notifyObserversOf('loaded', context, function(err) { if (err) return cb(err); @@ -887,8 +887,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) { @@ -897,7 +897,7 @@ DataAccessObject.findOrCreate = function findOrCreate(query, data, options, cb) instance: obj, isNewInstance: true, hookState: hookState, - options: options + options: options, }; Model.notifyObserversOf('after save', context, function(err) { if (cb.promise) { @@ -926,7 +926,7 @@ DataAccessObject.findOrCreate = function findOrCreate(query, data, options, cb) isNewInstance: true, currentInstance : currentInstance, hookState: hookState, - options: options + options: options, }; Model.notifyObserversOf('persist', context, function(err) { @@ -946,7 +946,7 @@ DataAccessObject.findOrCreate = function findOrCreate(query, data, options, cb) try { this._normalize(query); } catch (err) { - process.nextTick(function () { + process.nextTick(function() { cb(err); }); return cb.promise; @@ -958,9 +958,9 @@ DataAccessObject.findOrCreate = function findOrCreate(query, data, options, cb) Model: Model, query: query, hookState: hookState, - options: options + options: options, }; - Model.notifyObserversOf('access', context, function (err, ctx) { + Model.notifyObserversOf('access', context, function(err, ctx) { if (err) return cb(err); var query = ctx.query; @@ -977,8 +977,8 @@ DataAccessObject.findOrCreate = function findOrCreate(query, data, options, cb) instance: obj, isNewInstance: true, hookState: hookState, - options: options - }; + options: options, + }; Model.notifyObserversOf('before save', context, function(err, ctx) { if (err) return cb(err); @@ -996,7 +996,7 @@ DataAccessObject.findOrCreate = function findOrCreate(query, data, options, cb) } // validation required - obj.isValid(function (valid) { + obj.isValid(function(valid) { if (valid) { _findOrCreate(query, data, obj); } else { @@ -1006,7 +1006,7 @@ DataAccessObject.findOrCreate = function findOrCreate(query, data, options, cb) }); }); } else { - Model.findOne(query, options, function (err, record) { + Model.findOne(query, options, function(err, record) { if (err) return cb(err); if (record) { if (cb.promise) { @@ -1015,7 +1015,7 @@ DataAccessObject.findOrCreate = function findOrCreate(query, data, options, cb) return cb(null, record, false); } } - Model.create(data, options, function (err, record) { + Model.create(data, options, function(err, record) { if (cb.promise) { cb(err, [record, record != null]); } else { @@ -1172,21 +1172,21 @@ DataAccessObject.findByIds = function(ids, query, options, cb) { if (isPKMissing(this, cb)) { return cb.promise; } else if (ids.length === 0) { - process.nextTick(function(){cb(null, []);}); + process.nextTick(function() { cb(null, []); }); return cb.promise; } - var filter = { where: {} }; + var filter = { where: {}}; var pk = idName(this); filter.where[pk] = { inq: [].concat(ids) }; mergeQuery(filter, query || {}); // to know if the result need to be sorted by ids or not // this variable need to be initialized before the call to find, because filter is updated during the call with an order - var toSortObjectsByIds = filter.order ? false : true ; + var toSortObjectsByIds = filter.order ? false : true; this.find(filter, options, function(err, results) { - cb(err, toSortObjectsByIds ? utils.sortObjectsByIds(pk, ids, results) : results ); + cb(err, toSortObjectsByIds ? utils.sortObjectsByIds(pk, ids, results) : results); }); return cb.promise; }; @@ -1203,7 +1203,7 @@ function convertNullToNotFoundError(ctx, cb) { } // alias function for backwards compat. -DataAccessObject.all = function () { +DataAccessObject.all = function() { return DataAccessObject.find.apply(this, arguments); }; @@ -1215,13 +1215,13 @@ DataAccessObject.all = function () { DataAccessObject._getSetting = function(key) { // Check for settings in model var m = this.definition; - if(m && m.settings && m.settings[key]) { - return m.settings[key] + if (m && m.settings && m.settings[key]) { + return m.settings[key]; } // Check for settings in connector var ds = this.getDataSource(); - if(ds && ds.settings && ds.settings[key]) { + if (ds && ds.settings && ds.settings[key]) { return ds.settings[key]; } @@ -1239,7 +1239,7 @@ var operators = { neq: '!=', like: 'LIKE', nlike: 'NOT LIKE', - regexp: 'REGEXP' + regexp: 'REGEXP', }; /* @@ -1248,7 +1248,7 @@ var operators = { * @returns {Object} The normalized filter object * @private */ -DataAccessObject._normalize = function (filter) { +DataAccessObject._normalize = function(filter) { if (!filter) { return undefined; } @@ -1369,7 +1369,7 @@ function NumberType(val) { * @returns {Object} The coerced where clause * @private */ -DataAccessObject._coerce = function (where) { +DataAccessObject._coerce = function(where) { var self = this; if (!where) { return where; @@ -1447,7 +1447,7 @@ DataAccessObject._coerce = function (where) { if (op in val) { val = val[op]; operator = op; - switch(operator) { + switch (operator) { case 'inq': case 'nin': if (!Array.isArray(val)) { @@ -1612,7 +1612,7 @@ DataAccessObject.find = function find(query, options, cb) { try { this._normalize(query); } catch (err) { - process.nextTick(function () { + process.nextTick(function() { cb(err); }); return cb.promise; @@ -1636,7 +1636,7 @@ DataAccessObject.find = function find(query, options, cb) { Model: self, query: query, hookState: hookState, - options: options + options: options, }; self.notifyObserversOf('access', context, function(err, ctx) { if (err) return cb(err); @@ -1651,7 +1651,7 @@ DataAccessObject.find = function find(query, options, cb) { memory.define({ properties: self.dataSource.definitions[self.modelName].properties, settings: self.dataSource.definitions[self.modelName].settings, - model: self + model: self, }); data.forEach(function(obj) { @@ -1685,7 +1685,7 @@ DataAccessObject.find = function find(query, options, cb) { async.each(data, function(item, callback) { var d = item;//data[i]; var Model = self.lookupModel(d); - var obj = new Model(d, {fields: query.fields, applySetters: false, persisted: true}); + var obj = new Model(d, { fields: query.fields, applySetters: false, persisted: true }); if (query && query.include) { if (query.collect) { @@ -1723,7 +1723,7 @@ DataAccessObject.find = function find(query, options, cb) { instance: obj, isNewInstance: false, hookState: hookState, - options: options + options: options, }; Model.notifyObserversOf('loaded', context, function(err) { @@ -1765,7 +1765,7 @@ DataAccessObject.find = function find(query, options, cb) { Model: this, query: query, hookState: hookState, - options: options + options: options, }; this.notifyObserversOf('access', context, function(err, ctx) { if (err) return cb(err); @@ -1813,7 +1813,7 @@ DataAccessObject.findOne = function findOne(query, options, cb) { assert(typeof cb === 'function', 'The cb argument must be a function'); query.limit = 1; - this.find(query, options, function (err, collection) { + this.find(query, options, function(err, collection) { if (err || !collection || !collection.length > 0) return cb(err, null); cb(err, collection[0]); }); @@ -1876,7 +1876,7 @@ DataAccessObject.remove = DataAccessObject.deleteAll = DataAccessObject.destroyA Model: Model, where: whereIsEmpty(where) ? {} : where, hookState: hookState, - options: options + options: options, }; if (options.notify === false) { @@ -1887,21 +1887,21 @@ DataAccessObject.remove = DataAccessObject.deleteAll = DataAccessObject.destroyA Model: Model, query: query, hookState: hookState, - options: options + options: options, }; Model.notifyObserversOf('access', context, function(err, ctx) { + if (err) return cb(err); + var context = { + Model: Model, + where: ctx.query.where, + hookState: hookState, + options: options, + }; + Model.notifyObserversOf('before delete', context, function(err, ctx) { if (err) return cb(err); - var context = { - Model: Model, - where: ctx.query.where, - hookState: hookState, - options: options - }; - Model.notifyObserversOf('before delete', context, function(err, ctx) { - if (err) return cb(err); - doDelete(ctx.where); - }); + doDelete(ctx.where); }); + }); } function doDelete(where) { @@ -1941,7 +1941,7 @@ DataAccessObject.remove = DataAccessObject.deleteAll = DataAccessObject.destroyA Model: Model, where: where, hookState: hookState, - options: options + options: options, }; Model.notifyObserversOf('after delete', context, function(err) { cb(err, info); @@ -1955,7 +1955,7 @@ DataAccessObject.remove = DataAccessObject.deleteAll = DataAccessObject.destroyA function whereIsEmpty(where) { return !where || - (typeof where === 'object' && Object.keys(where).length === 0) + (typeof where === 'object' && Object.keys(where).length === 0); } /** @@ -2030,7 +2030,7 @@ DataAccessObject.removeById = DataAccessObject.destroyById = DataAccessObject.de * @param {Object} [options] Options * @param {Function} cb Callback, called with (err, count) */ -DataAccessObject.count = function (where, options, cb) { +DataAccessObject.count = function(where, options, cb) { var connectionPromise = stillConnecting(this.getDataSource(), this, arguments); if (connectionPromise) { return connectionPromise; @@ -2075,7 +2075,7 @@ DataAccessObject.count = function (where, options, cb) { where = removeUndefined(where); where = this._coerce(where); } catch (err) { - process.nextTick(function () { + process.nextTick(function() { cb(err); }); return cb.promise; @@ -2085,7 +2085,7 @@ DataAccessObject.count = function (where, options, cb) { Model: Model, query: { where: where }, hookState: hookState, - options: options + options: options, }; this.notifyObserversOf('access', context, function(err, ctx) { if (err) return cb(err); @@ -2112,7 +2112,7 @@ DataAccessObject.count = function (where, options, cb) { * @property {Boolean} throws Default is false. * @param {Function} cb Callback function with err and object arguments */ -DataAccessObject.prototype.save = function (options, cb) { +DataAccessObject.prototype.save = function(options, cb) { var connectionPromise = stillConnecting(this.getDataSource(), this, arguments); if (connectionPromise) { return connectionPromise; @@ -2158,7 +2158,7 @@ DataAccessObject.prototype.save = function (options, cb) { Model: Model, instance: inst, hookState: hookState, - options: options + options: options, }; Model.notifyObserversOf('before save', context, function(err) { if (err) return cb(err); @@ -2172,7 +2172,7 @@ DataAccessObject.prototype.save = function (options, cb) { return save(); } - inst.isValid(function (valid) { + inst.isValid(function(valid) { if (valid) { save(); } else { @@ -2187,8 +2187,8 @@ DataAccessObject.prototype.save = function (options, cb) { // then save function save() { - inst.trigger('save', function (saveDone) { - inst.trigger('update', function (updateDone) { + inst.trigger('save', function(saveDone) { + inst.trigger('update', function(updateDone) { data = removeUndefined(data); function saveCallback(err, unusedData, result) { if (err) { @@ -2200,7 +2200,7 @@ DataAccessObject.prototype.save = function (options, cb) { data: data, isNewInstance: result && result.isNewInstance, hookState: hookState, - options: options + options: options, }; Model.notifyObserversOf('loaded', context, function(err) { if (err) return cb(err); @@ -2212,14 +2212,14 @@ DataAccessObject.prototype.save = function (options, cb) { instance: inst, isNewInstance: result && result.isNewInstance, hookState: hookState, - options: options + options: options, }; Model.notifyObserversOf('after save', context, function(err) { if (err) return cb(err, inst); - updateDone.call(inst, function () { - saveDone.call(inst, function () { + updateDone.call(inst, function() { + saveDone.call(inst, function() { cb(err, inst); - if(!err) { + if (!err) { Model.emit('changed', inst); } }); @@ -2234,7 +2234,7 @@ DataAccessObject.prototype.save = function (options, cb) { where: byIdQuery(Model, getIdValue(Model, inst)).where, currentInstance: inst, hookState: hookState, - options: options + options: options, }; Model.notifyObserversOf('persist', context, function(err) { @@ -2271,7 +2271,7 @@ DataAccessObject.prototype.save = function (options, cb) { * @param {Function} cb Callback, called with (err, info) */ DataAccessObject.update = -DataAccessObject.updateAll = function (where, data, options, cb) { +DataAccessObject.updateAll = function(where, data, options, cb) { var connectionPromise = stillConnecting(this.getDataSource(), this, arguments); if (connectionPromise) { return connectionPromise; @@ -2328,7 +2328,7 @@ DataAccessObject.updateAll = function (where, data, options, cb) { Model: Model, query: { where: where }, hookState: hookState, - options: options + options: options, }; Model.notifyObserversOf('access', context, function(err, ctx) { if (err) return cb(err); @@ -2337,7 +2337,7 @@ DataAccessObject.updateAll = function (where, data, options, cb) { where: ctx.query.where, data: data, hookState: hookState, - options: options + options: options, }; Model.notifyObserversOf('before save', context, function(err, ctx) { @@ -2353,7 +2353,7 @@ DataAccessObject.updateAll = function (where, data, options, cb) { data = removeUndefined(data); data = Model._coerce(data); } catch (err) { - return process.nextTick(function () { + return process.nextTick(function() { cb(err); }); } @@ -2366,7 +2366,7 @@ DataAccessObject.updateAll = function (where, data, options, cb) { where: where, data: data, hookState: hookState, - options: options + options: options, }; Model.notifyObserversOf('after save', context, function(err, ctx) { return cb(err, info); @@ -2378,7 +2378,7 @@ DataAccessObject.updateAll = function (where, data, options, cb) { where: where, data: data, hookState: hookState, - options: options + options: options, }; Model.notifyObserversOf('persist', context, function(err, ctx) { if (err) return cb (err); @@ -2393,7 +2393,7 @@ DataAccessObject.updateAll = function (where, data, options, cb) { return cb.promise; }; -DataAccessObject.prototype.isNewRecord = function () { +DataAccessObject.prototype.isNewRecord = function() { return !this.__persisted; }; @@ -2401,7 +2401,7 @@ DataAccessObject.prototype.isNewRecord = function () { * Return connector of current record * @private */ -DataAccessObject.prototype.getConnector = function () { +DataAccessObject.prototype.getConnector = function() { return this.getDataSource().connector; }; @@ -2415,7 +2415,7 @@ DataAccessObject.prototype.getConnector = function () { */ DataAccessObject.prototype.remove = DataAccessObject.prototype.delete = - DataAccessObject.prototype.destroy = function (options, cb) { + DataAccessObject.prototype.destroy = function(options, cb) { var connectionPromise = stillConnecting(this.getDataSource(), this, arguments); if (connectionPromise) { return connectionPromise; @@ -2446,23 +2446,23 @@ DataAccessObject.prototype.remove = Model: Model, query: byIdQuery(Model, id), hookState: hookState, - options: options + options: options, }; Model.notifyObserversOf('access', context, function(err, ctx) { + if (err) return cb(err); + var context = { + Model: Model, + where: ctx.query.where, + instance: inst, + hookState: hookState, + options: options, + }; + Model.notifyObserversOf('before delete', context, function(err, ctx) { if (err) return cb(err); - var context = { - Model: Model, - where: ctx.query.where, - instance: inst, - hookState: hookState, - options: options - }; - Model.notifyObserversOf('before delete', context, function(err, ctx) { - if (err) return cb(err); - doDeleteInstance(ctx.where); - }); + doDeleteInstance(ctx.where); }); + }); function doDeleteInstance(where) { if (!isWhereByGivenId(Model, where, id)) { @@ -2483,7 +2483,7 @@ DataAccessObject.prototype.remove = where: where, instance: inst, hookState: hookState, - options: options + options: options, }; Model.notifyObserversOf('after delete', context, function(err) { cb(err, info); @@ -2493,7 +2493,7 @@ DataAccessObject.prototype.remove = return; } - inst.trigger('destroy', function (destroyed) { + inst.trigger('destroy', function(destroyed) { function destroyCallback(err, info) { if (err) return cb(err); var deleted = info && info.count > 0; @@ -2510,7 +2510,7 @@ DataAccessObject.prototype.remove = where: where, instance: inst, hookState: hookState, - options: options + options: options, }; Model.notifyObserversOf('after delete', context, function(err) { cb(err, info); @@ -2650,18 +2650,18 @@ DataAccessObject.replaceById = function(id, data, options, cb) { process.nextTick(function() { cb(err); }); return cb.promise; } - + var context = { Model: Model, instance: inst, isNewInstance: false, hookState: hookState, - options: options + options: options, }; Model.notifyObserversOf('before save', context, function(err, ctx) { if (err) return cb(err); - + data = inst.toObject(false); if (strict) { @@ -2673,7 +2673,7 @@ DataAccessObject.replaceById = function(id, data, options, cb) { function validateAndCallConnector(err, data) { if (err) return cb(err); data = removeUndefined(data); - // update instance's properties + // update instance's properties inst.setAttributes(data); var doValidate = true; @@ -2685,20 +2685,20 @@ DataAccessObject.replaceById = function(id, data, options, cb) { doValidate = options.validate; } - if (doValidate){ - inst.isValid(function (valid) { + if (doValidate) { + inst.isValid(function(valid) { if (!valid) return cb(new ValidationError(inst), inst); callConnector(); }, data); } else { - callConnector(); + callConnector(); } function callConnector() { var idNames = Model.definition.idNames(); var propKeys = Object.keys(Model.definition.properties); - var nonIdsPropKeys = propKeys.filter(function(i) {return idNames.indexOf(i) < 0;}); + var nonIdsPropKeys = propKeys.filter(function(i) { return idNames.indexOf(i) < 0; }); for (var i = 0; i < nonIdsPropKeys.length; i++) { var p = nonIdsPropKeys[i]; inst[p] = null; @@ -2706,7 +2706,7 @@ DataAccessObject.replaceById = function(id, data, options, cb) { copyData(data, inst); var typedData = convertSubsetOfPropertiesByType(inst, data); context.data = typedData; - + function replaceCallback(err, data) { if (err) return cb(err); @@ -2715,7 +2715,7 @@ DataAccessObject.replaceById = function(id, data, options, cb) { hookState: hookState, data: context.data, isNewInstance:false, - options: options + options: options, }; Model.notifyObserversOf('loaded', ctx, function(err) { if (err) return cb(err); @@ -2728,7 +2728,7 @@ DataAccessObject.replaceById = function(id, data, options, cb) { instance: inst, isNewInstance: false, hookState: hookState, - options: options + options: options, }; Model.notifyObserversOf('after save', context, function(err) { if (!err) Model.emit('changed', inst); @@ -2745,12 +2745,12 @@ DataAccessObject.replaceById = function(id, data, options, cb) { isNewInstance:false, currentInstance: inst, hookState: hookState, - options: options + options: options, }; Model.notifyObserversOf('persist', ctx, function(err) { connector.replaceById(model, id, inst.constructor._forDB(context.data), options, replaceCallback); - }); + }); } } }); @@ -2841,7 +2841,7 @@ function(data, options, cb) { data: data, currentInstance: inst, hookState: hookState, - options: options + options: options, }; Model.notifyObserversOf('before save', context, function(err, ctx) { @@ -2869,8 +2869,8 @@ function(data, options, cb) { // update instance's properties inst.setAttributes(data); - if (doValidate){ - inst.isValid(function (valid) { + if (doValidate) { + inst.isValid(function(valid) { if (!valid) { cb(new ValidationError(inst), inst); return; @@ -2879,12 +2879,12 @@ function(data, options, cb) { triggerSave(); }, data); } else { - triggerSave(); + triggerSave(); } - function triggerSave(){ - inst.trigger('save', function (saveDone) { - inst.trigger('update', function (done) { + function triggerSave() { + inst.trigger('save', function(saveDone) { + inst.trigger('update', function(done) { copyData(data, inst); var typedData = convertSubsetOfPropertiesByType(inst, data); context.data = typedData; @@ -2895,7 +2895,7 @@ function(data, options, cb) { Model: Model, data: context.data, hookState: hookState, - options: options + options: options, }; Model.notifyObserversOf('loaded', ctx, function(err) { if (err) return cb(err); @@ -2906,11 +2906,11 @@ function(data, options, cb) { // with the changes made through persist/loaded hooks. To preserve // backwards compatibility, we introduced a new setting updateOnLoad, // which if set, will apply these changes to the model instance too. - if(Model.settings.updateOnLoad) { + if (Model.settings.updateOnLoad) { inst.setAttributes(ctx.data); } - done.call(inst, function () { - saveDone.call(inst, function () { + done.call(inst, function() { + saveDone.call(inst, function() { if (err) return cb(err, inst); var context = { @@ -2918,10 +2918,10 @@ function(data, options, cb) { instance: inst, isNewInstance: false, hookState: hookState, - options: options + options: options, }; Model.notifyObserversOf('after save', context, function(err) { - if(!err) Model.emit('changed', inst); + if (!err) Model.emit('changed', inst); cb(err, inst); }); }); @@ -2936,7 +2936,7 @@ function(data, options, cb) { currentInstance: inst, isNewInstance: false, hookState: hookState, - options: options + options: options, }; Model.notifyObserversOf('persist', ctx, function(err) { if (connector.updateAttributes.length === 5) { @@ -2952,7 +2952,7 @@ function(data, options, cb) { } } }); -return cb.promise; + return cb.promise; }; /** @@ -2984,7 +2984,7 @@ function defineReadonlyProp(obj, key, value) { writable: false, enumerable: true, configurable: true, - value: value + value: value, }); } @@ -2999,7 +2999,7 @@ var defineScope = require('./scope.js').defineScope; * @param {ModelClass} [targetClass] The model class for the query, default to * the declaring model */ -DataAccessObject.scope = function (name, query, targetClass, methods, options) { +DataAccessObject.scope = function(name, query, targetClass, methods, options) { var cls = this; if (options && options.isStatic === false) { cls = cls.prototype; diff --git a/lib/datasource.js b/lib/datasource.js index dfdac0b2..f62b07b4 100644 --- a/lib/datasource.js +++ b/lib/datasource.js @@ -120,11 +120,11 @@ function DataSource(name, settings, modelBuilder) { // DataAccessObject - connector defined or supply the default var dao = (connector && connector.DataAccessObject) || this.constructor.DataAccessObject; - this.DataAccessObject = function () { + this.DataAccessObject = function() { }; // define DataAccessObject methods - Object.keys(dao).forEach(function (name) { + Object.keys(dao).forEach(function(name) { var fn = dao[name]; this.DataAccessObject[name] = fn; @@ -135,13 +135,13 @@ function DataSource(name, settings, modelBuilder) { http: fn.http, remoteEnabled: fn.shared ? true : false, scope: this.DataAccessObject, - fnName: name + fnName: name, }); } }.bind(this)); // define DataAccessObject.prototype methods - Object.keys(dao.prototype).forEach(function (name) { + Object.keys(dao.prototype).forEach(function(name) { var fn = dao.prototype[name]; this.DataAccessObject.prototype[name] = fn; if (typeof fn === 'function') { @@ -152,7 +152,7 @@ function DataSource(name, settings, modelBuilder) { http: fn.http, remoteEnabled: fn.shared ? true : false, scope: this.DataAccessObject.prototype, - fnName: name + fnName: name, }); } }.bind(this)); @@ -168,7 +168,7 @@ DataSource.DataAccessObject = DataAccessObject; * Set up the connector instance for backward compatibility with JugglingDB schema/adapter * @private */ -DataSource.prototype._setupConnector = function () { +DataSource.prototype._setupConnector = function() { this.connector = this.connector || this.adapter; // The legacy JugglingDB adapter will set up `adapter` property this.adapter = this.connector; // Keep the adapter as an alias to connector if (this.connector) { @@ -177,14 +177,14 @@ DataSource.prototype._setupConnector = function () { this.connector.dataSource = this; } var dataSource = this; - this.connector.log = function (query, start) { + this.connector.log = function(query, start) { dataSource.log(query, start); }; - this.connector.logger = function (query) { + this.connector.logger = function(query) { var t1 = Date.now(); var log = this.log; - return function (q) { + return function(q) { log(q || query, t1); }; }; @@ -233,7 +233,7 @@ function tryModules(names, loader) { * @returns {*} * @private */ -DataSource._resolveConnector = function (name, loader) { +DataSource._resolveConnector = function(name, loader) { var names = connectorModuleNames(name); var connector = tryModules(names, loader); var error = null; @@ -244,7 +244,7 @@ DataSource._resolveConnector = function (name, loader) { } return { connector: connector, - error: error + error: error, }; }; @@ -255,7 +255,7 @@ DataSource._resolveConnector = function (name, loader) { * @returns {*} * @private */ -DataSource.prototype.setup = function (name, settings) { +DataSource.prototype.setup = function(name, settings) { var dataSource = this; var connector; @@ -341,7 +341,7 @@ DataSource.prototype.setup = function (name, settings) { this.connector = new connector(this.settings); postInit(); } - } catch(err) { + } catch (err) { if (err.message) { err.message = 'Cannot initialize connector ' + JSON.stringify(connector.name || name) + ': ' + @@ -351,17 +351,17 @@ DataSource.prototype.setup = function (name, settings) { } } - dataSource.connect = function (cb) { + dataSource.connect = function(cb) { var dataSource = this; if (dataSource.connected || dataSource.connecting) { - process.nextTick(function () { + process.nextTick(function() { cb && cb(); }); return; } dataSource.connecting = true; if (dataSource.connector.connect) { - dataSource.connector.connect(function (err, result) { + dataSource.connector.connect(function(err, result) { if (!err) { dataSource.connected = true; dataSource.connecting = false; @@ -374,7 +374,7 @@ DataSource.prototype.setup = function (name, settings) { cb && cb(err, result); }); } else { - process.nextTick(function () { + process.nextTick(function() { dataSource.connected = true; dataSource.connecting = false; dataSource.emit('connected'); @@ -402,7 +402,7 @@ function isModelDataSourceAttached(model) { * @param modelClass * @param scopes */ -DataSource.prototype.defineScopes = function (modelClass, scopes) { +DataSource.prototype.defineScopes = function(modelClass, scopes) { if (scopes) { for (var s in scopes) { defineScope(modelClass, modelClass, s, scopes[s], {}, scopes[s].options); @@ -415,13 +415,13 @@ DataSource.prototype.defineScopes = function (modelClass, scopes) { * @param modelClass * @param relations */ -DataSource.prototype.defineRelations = function (modelClass, relations) { +DataSource.prototype.defineRelations = function(modelClass, relations) { var self = this; // Create a function for the closure in the loop - var createListener = function (name, relation, targetModel, throughModel) { + var createListener = function(name, relation, targetModel, throughModel) { if (!isModelDataSourceAttached(targetModel)) { - targetModel.once('dataAccessConfigured', function (model) { + targetModel.once('dataAccessConfigured', function(model) { // Check if the through model doesn't exist or resolved if (!throughModel || isModelDataSourceAttached(throughModel)) { // The target model is resolved @@ -438,7 +438,7 @@ DataSource.prototype.defineRelations = function (modelClass, relations) { } if (throughModel && !isModelDataSourceAttached(throughModel)) { // Set up a listener to the through model - throughModel.once('dataAccessConfigured', function (model) { + throughModel.once('dataAccessConfigured', function(model) { if (isModelDataSourceAttached(targetModel)) { // The target model is resolved var params = traverse(relation).clone(); @@ -453,9 +453,9 @@ DataSource.prototype.defineRelations = function (modelClass, relations) { // Set up the relations if (relations) { - Object.keys(relations).forEach(function (rn) { + Object.keys(relations).forEach(function(rn) { var r = relations[rn]; - assert(DataSource.relationTypes.indexOf(r.type) !== -1, "Invalid relation type: " + r.type); + assert(DataSource.relationTypes.indexOf(r.type) !== -1, 'Invalid relation type: ' + r.type); var targetModel, polymorphicName; if (r.polymorphic && r.type !== 'belongsTo' && !r.model) { @@ -503,7 +503,7 @@ DataSource.prototype.defineRelations = function (modelClass, relations) { * @param {Model} modelClass The model class * @param {Object} settings The settings object */ -DataSource.prototype.setupDataAccess = function (modelClass, settings) { +DataSource.prototype.setupDataAccess = function(modelClass, settings) { if (this.connector) { // Check if the id property should be generated var idName = modelClass.definition.idName(); @@ -515,7 +515,7 @@ DataSource.prototype.setupDataAccess = function (modelClass, settings) { modelClass.definition.rawProperties[idName].type = idType; modelClass.definition.properties[idName].type = idType; if (settings.forceId) { - modelClass.validatesAbsenceOf(idName, {if: 'isNewRecord'}); + modelClass.validatesAbsenceOf(idName, { if: 'isNewRecord' }); } } if (this.connector.define) { @@ -523,7 +523,7 @@ DataSource.prototype.setupDataAccess = function (modelClass, settings) { this.connector.define({ model: modelClass, properties: modelClass.definition.properties, - settings: settings + settings: settings, }); } } @@ -642,15 +642,15 @@ DataSource.prototype.createModel = DataSource.prototype.define = function define * @private */ -DataSource.prototype.mixin = function (ModelCtor) { +DataSource.prototype.mixin = function(ModelCtor) { var ops = this.operations(); var DAO = this.DataAccessObject; // mixin DAO - jutil.mixin(ModelCtor, DAO, {proxyFunctions: true, override: true}); + jutil.mixin(ModelCtor, DAO, { proxyFunctions: true, override: true }); // decorate operations as alias functions - Object.keys(ops).forEach(function (name) { + Object.keys(ops).forEach(function(name) { var op = ops[name]; var scope; @@ -660,15 +660,15 @@ DataSource.prototype.mixin = function (ModelCtor) { // op.scope[op.fnName].apply(self, arguments); // } Object.keys(op) - .filter(function (key) { + .filter(function(key) { // filter out the following keys return ~[ 'scope', 'fnName', - 'prototype' + 'prototype', ].indexOf(key); }) - .forEach(function (key) { + .forEach(function(key) { if (typeof op[key] !== 'undefined') { op.scope[op.fnName][key] = op[key]; } @@ -680,14 +680,14 @@ DataSource.prototype.mixin = function (ModelCtor) { /** * See ModelBuilder.getModel */ -DataSource.prototype.getModel = function (name, forceCreate) { +DataSource.prototype.getModel = function(name, forceCreate) { return this.modelBuilder.getModel(name, forceCreate); }; /** * See ModelBuilder.getModelDefinition */ -DataSource.prototype.getModelDefinition = function (name) { +DataSource.prototype.getModelDefinition = function(name) { return this.modelBuilder.getModelDefinition(name); }; @@ -696,7 +696,7 @@ DataSource.prototype.getModelDefinition = function (name) { * @returns {String[]} The data source type, such as ['db', 'nosql', 'mongodb'], * ['rest'], or ['db', 'rdbms', 'mysql'] */ -DataSource.prototype.getTypes = function () { +DataSource.prototype.getTypes = function() { var getTypes = this.connector && this.connector.getTypes; var types = getTypes && getTypes() || []; if (typeof types === 'string') { @@ -710,7 +710,7 @@ DataSource.prototype.getTypes = function () { * @param {String} types Type name or an array of type names. Can also be array of Strings. * @returns {Boolean} true if all types are supported by the data source */ -DataSource.prototype.supportTypes = function (types) { +DataSource.prototype.supportTypes = function(types) { var supportedTypes = this.getTypes(); if (Array.isArray(types)) { // Check each of the types @@ -733,7 +733,7 @@ DataSource.prototype.supportTypes = function (types) { * @param {Function} modelClass The model constructor */ -DataSource.prototype.attach = function (modelClass) { +DataSource.prototype.attach = function(modelClass) { if (modelClass.dataSource === this) { // Already attached to the data source return modelClass; @@ -762,7 +762,7 @@ DataSource.prototype.attach = function (modelClass) { * @param {String} prop Name of property * @param {Object} params Property settings */ -DataSource.prototype.defineProperty = function (model, prop, params) { +DataSource.prototype.defineProperty = function(model, prop, params) { this.modelBuilder.defineProperty(model, prop, params); var resolvedProp = this.getModelDefinition(model).properties[prop]; @@ -782,7 +782,7 @@ DataSource.prototype.defineProperty = function (model, prop, params) { * */ -DataSource.prototype.automigrate = function (models, cb) { +DataSource.prototype.automigrate = function(models, cb) { this.freeze(); if ((!cb) && ('function' === typeof models)) { @@ -813,13 +813,13 @@ DataSource.prototype.automigrate = function (models, cb) { return cb.promise; } - var invalidModels = models.filter(function (m) { + var invalidModels = models.filter(function(m) { return !(m in attachedModels); }); if (invalidModels.length) { - process.nextTick(function () { - cb(new Error('Cannot migrate models not attached to this datasource: ' + + process.nextTick(function() { + cb(new Error('Cannot migrate models not attached to this datasource: ' + invalidModels.join(' '))); }); return cb.promise; @@ -837,7 +837,7 @@ DataSource.prototype.automigrate = function (models, cb) { * @param {String} model Model to migrate. If not present, apply to all models. Can also be an array of Strings. * @param {Function} [cb] The callback function */ -DataSource.prototype.autoupdate = function (models, cb) { +DataSource.prototype.autoupdate = function(models, cb) { this.freeze(); if ((!cb) && ('function' === typeof models)) { @@ -868,12 +868,12 @@ DataSource.prototype.autoupdate = function (models, cb) { return cb.promise; } - var invalidModels = models.filter(function (m) { + var invalidModels = models.filter(function(m) { return !(m in attachedModels); }); if (invalidModels.length) { - process.nextTick(function () { + process.nextTick(function() { cb(new Error('Cannot migrate models not attached to this datasource: ' + invalidModels.join(' '))); }); @@ -898,7 +898,7 @@ DataSource.prototype.autoupdate = function (models, cb) { * @property {Number} offset Starting index * */ -DataSource.prototype.discoverModelDefinitions = function (options, cb) { +DataSource.prototype.discoverModelDefinitions = function(options, cb) { this.freeze(); if (cb === undefined && typeof options === 'function') { @@ -925,7 +925,7 @@ DataSource.prototype.discoverModelDefinitions = function (options, cb) { * @property {Number} offset Starting index * @returns {*} */ -DataSource.prototype.discoverModelDefinitionsSync = function (options) { +DataSource.prototype.discoverModelDefinitionsSync = function(options) { this.freeze(); if (this.connector.discoverModelDefinitionsSync) { return this.connector.discoverModelDefinitionsSync(options); @@ -955,7 +955,7 @@ DataSource.prototype.discoverModelDefinitionsSync = function (options) { * @param {Function} cb Callback function. Optional * */ -DataSource.prototype.discoverModelProperties = function (modelName, options, cb) { +DataSource.prototype.discoverModelProperties = function(modelName, options, cb) { this.freeze(); if (cb === undefined && typeof options === 'function') { @@ -970,7 +970,7 @@ DataSource.prototype.discoverModelProperties = function (modelName, options, cb) } else if (cb) { process.nextTick(cb); } - return cb.promise; + return cb.promise; }; /** @@ -979,7 +979,7 @@ DataSource.prototype.discoverModelProperties = function (modelName, options, cb) * @param {Object} options The options * @returns {*} */ -DataSource.prototype.discoverModelPropertiesSync = function (modelName, options) { +DataSource.prototype.discoverModelPropertiesSync = function(modelName, options) { this.freeze(); if (this.connector.discoverModelPropertiesSync) { return this.connector.discoverModelPropertiesSync(modelName, options); @@ -1004,7 +1004,7 @@ DataSource.prototype.discoverModelPropertiesSync = function (modelName, options) * @property {String} owner|schema The database owner or schema * @param {Function} [cb] The callback function */ -DataSource.prototype.discoverPrimaryKeys = function (modelName, options, cb) { +DataSource.prototype.discoverPrimaryKeys = function(modelName, options, cb) { this.freeze(); if (cb === undefined && typeof options === 'function') { @@ -1029,7 +1029,7 @@ DataSource.prototype.discoverPrimaryKeys = function (modelName, options, cb) { * @property {String} owner|schema The database owner orschema * @returns {*} */ -DataSource.prototype.discoverPrimaryKeysSync = function (modelName, options) { +DataSource.prototype.discoverPrimaryKeysSync = function(modelName, options) { this.freeze(); if (this.connector.discoverPrimaryKeysSync) { return this.connector.discoverPrimaryKeysSync(modelName, options); @@ -1060,7 +1060,7 @@ DataSource.prototype.discoverPrimaryKeysSync = function (modelName, options) { * @param {Function} [cb] The callback function * */ -DataSource.prototype.discoverForeignKeys = function (modelName, options, cb) { +DataSource.prototype.discoverForeignKeys = function(modelName, options, cb) { this.freeze(); if (cb === undefined && typeof options === 'function') { @@ -1085,7 +1085,7 @@ DataSource.prototype.discoverForeignKeys = function (modelName, options, cb) { * @param {Object} options The options * @returns {*} */ -DataSource.prototype.discoverForeignKeysSync = function (modelName, options) { +DataSource.prototype.discoverForeignKeysSync = function(modelName, options) { this.freeze(); if (this.connector.discoverForeignKeysSync) { return this.connector.discoverForeignKeysSync(modelName, options); @@ -1116,7 +1116,7 @@ DataSource.prototype.discoverForeignKeysSync = function (modelName, options) { * @property {String} owner|schema The database owner or schema * @param {Function} [cb] The callback function */ -DataSource.prototype.discoverExportedForeignKeys = function (modelName, options, cb) { +DataSource.prototype.discoverExportedForeignKeys = function(modelName, options, cb) { this.freeze(); if (cb === undefined && typeof options === 'function') { @@ -1140,7 +1140,7 @@ DataSource.prototype.discoverExportedForeignKeys = function (modelName, options, * @param {Object} options The options * @returns {*} */ -DataSource.prototype.discoverExportedForeignKeysSync = function (modelName, options) { +DataSource.prototype.discoverExportedForeignKeysSync = function(modelName, options) { this.freeze(); if (this.connector.discoverExportedForeignKeysSync) { return this.connector.discoverExportedForeignKeysSync(modelName, options); @@ -1226,7 +1226,7 @@ function fromDBName(dbName, camelCase) { * @param {Object} [options] The options * @param {Function} [cb] The callback function */ -DataSource.prototype.discoverSchema = function (modelName, options, cb) { +DataSource.prototype.discoverSchema = function(modelName, options, cb) { options = options || {}; if (!cb && 'function' === typeof options) { @@ -1238,7 +1238,7 @@ DataSource.prototype.discoverSchema = function (modelName, options, cb) { cb = cb || utils.createPromiseCallback(); - this.discoverSchemas(modelName, options, function (err, schemas) { + this.discoverSchemas(modelName, options, function(err, schemas) { if (err) { cb && cb(err, schemas); return; @@ -1262,7 +1262,7 @@ DataSource.prototype.discoverSchema = function (modelName, options, cb) { * @property {Boolean} views True if views are included; false otherwise. * @param {Function} [cb] The callback function */ -DataSource.prototype.discoverSchemas = function (modelName, options, cb) { +DataSource.prototype.discoverSchemas = function(modelName, options, cb) { options = options || {}; if (!cb && 'function' === typeof options) { @@ -1310,7 +1310,7 @@ DataSource.prototype.discoverSchemas = function (modelName, options, cb) { tasks.push(this.discoverForeignKeys.bind(this, modelName, options)); } - async.parallel(tasks, function (err, results) { + async.parallel(tasks, function(err, results) { if (err) { cb(err); @@ -1326,7 +1326,7 @@ DataSource.prototype.discoverSchemas = function (modelName, options, cb) { // Handle primary keys var primaryKeys = results[1] || []; var pks = {}; - primaryKeys.forEach(function (pk) { + primaryKeys.forEach(function(pk) { pks[pk.columnName] = pk.keySeq; }); @@ -1337,17 +1337,17 @@ DataSource.prototype.discoverSchemas = function (modelName, options, cb) { var schema = { name: nameMapper('table', modelName), options: { - idInjection: false // DO NOT add id property + idInjection: false, // DO NOT add id property }, - properties: {} + properties: {}, }; schema.options[dbType] = { schema: columns[0].owner, - table: modelName + table: modelName, }; - columns.forEach(function (item) { + columns.forEach(function(item) { var i = item; var propName = nameMapper('column', item.columnName); @@ -1357,7 +1357,7 @@ DataSource.prototype.discoverSchemas = function (modelName, options, cb) { || item.nullable === 0 || item.nullable === false), length: item.dataLength, precision: item.dataPrecision, - scale: item.dataScale + scale: item.dataScale, }; if (pks[item.columnName]) { @@ -1369,7 +1369,7 @@ DataSource.prototype.discoverSchemas = function (modelName, options, cb) { dataLength: i.dataLength, dataPrecision: item.dataPrecision, dataScale: item.dataScale, - nullable: i.nullable + nullable: i.nullable, }; }); @@ -1388,12 +1388,12 @@ DataSource.prototype.discoverSchemas = function (modelName, options, cb) { // Handle foreign keys var fks = {}; var foreignKeys = results[2] || []; - foreignKeys.forEach(function (fk) { + foreignKeys.forEach(function(fk) { var fkInfo = { keySeq: fk.keySeq, owner: fk.pkOwner, tableName: fk.pkTableName, - columnName: fk.pkColumnName + columnName: fk.pkColumnName, }; if (fks[fk.fkName]) { fks[fk.fkName].push(fkInfo); @@ -1407,17 +1407,17 @@ DataSource.prototype.discoverSchemas = function (modelName, options, cb) { } schema.options.relations = {}; - foreignKeys.forEach(function (fk) { + foreignKeys.forEach(function(fk) { var propName = nameMapper('column', fk.pkTableName); schema.options.relations[propName] = { model: nameMapper('table', fk.pkTableName), type: 'belongsTo', - foreignKey: nameMapper('column', fk.fkColumnName) + foreignKey: nameMapper('column', fk.fkColumnName), }; var key = fk.pkOwner + '.' + fk.pkTableName; if (!options.visited.hasOwnProperty(key) && !otherTables.hasOwnProperty(key)) { - otherTables[key] = {owner: fk.pkOwner, tableName: fk.pkTableName}; + otherTables[key] = { owner: fk.pkOwner, tableName: fk.pkTableName }; } }); } @@ -1438,7 +1438,7 @@ DataSource.prototype.discoverSchemas = function (modelName, options, cb) { moreTasks.push(DataSource.prototype.discoverSchemas.bind(self, otherTables[t].tableName, newOptions)); } - async.parallel(moreTasks, function (err, results) { + async.parallel(moreTasks, function(err, results) { var result = results && results[0]; cb(err, result); }); @@ -1457,7 +1457,7 @@ DataSource.prototype.discoverSchemas = function (modelName, options, cb) { * @property {Boolean} all True if all owners are included; false otherwise. * @property {Boolean} views True if views are included; false otherwise. */ -DataSource.prototype.discoverSchemasSync = function (modelName, options) { +DataSource.prototype.discoverSchemasSync = function(modelName, options) { var self = this; var dbType = this.name || this.connector.name; @@ -1477,7 +1477,7 @@ DataSource.prototype.discoverSchemasSync = function (modelName, options) { // Handle primary keys var primaryKeys = this.discoverPrimaryKeysSync(modelName, options); var pks = {}; - primaryKeys.forEach(function (pk) { + primaryKeys.forEach(function(pk) { pks[pk.columnName] = pk.keySeq; }); @@ -1488,17 +1488,17 @@ DataSource.prototype.discoverSchemasSync = function (modelName, options) { var schema = { name: nameMapper('table', modelName), options: { - idInjection: false // DO NOT add id property + idInjection: false, // DO NOT add id property }, - properties: {} + properties: {}, }; schema.options[dbType] = { schema: columns.length > 0 && columns[0].owner, - table: modelName + table: modelName, }; - columns.forEach(function (item) { + columns.forEach(function(item) { var i = item; var propName = nameMapper('column', item.columnName); @@ -1507,7 +1507,7 @@ DataSource.prototype.discoverSchemasSync = function (modelName, options) { required: (item.nullable === 'N'), length: item.dataLength, precision: item.dataPrecision, - scale: item.dataScale + scale: item.dataScale, }; if (pks[item.columnName]) { @@ -1519,7 +1519,7 @@ DataSource.prototype.discoverSchemasSync = function (modelName, options) { dataLength: i.dataLength, dataPrecision: item.dataPrecision, dataScale: item.dataScale, - nullable: i.nullable + nullable: i.nullable, }; }); @@ -1539,12 +1539,12 @@ DataSource.prototype.discoverSchemasSync = function (modelName, options) { // Handle foreign keys var fks = {}; var foreignKeys = this.discoverForeignKeysSync(modelName, options); - foreignKeys.forEach(function (fk) { + foreignKeys.forEach(function(fk) { var fkInfo = { keySeq: fk.keySeq, owner: fk.pkOwner, tableName: fk.pkTableName, - columnName: fk.pkColumnName + columnName: fk.pkColumnName, }; if (fks[fk.fkName]) { fks[fk.fkName].push(fkInfo); @@ -1558,17 +1558,17 @@ DataSource.prototype.discoverSchemasSync = function (modelName, options) { } schema.options.relations = {}; - foreignKeys.forEach(function (fk) { + foreignKeys.forEach(function(fk) { var propName = nameMapper('column', fk.pkTableName); schema.options.relations[propName] = { model: nameMapper('table', fk.pkTableName), type: 'belongsTo', - foreignKey: nameMapper('column', fk.fkColumnName) + foreignKey: nameMapper('column', fk.fkColumnName), }; var key = fk.pkOwner + '.' + fk.pkTableName; if (!options.visited.hasOwnProperty(key) && !otherTables.hasOwnProperty(key)) { - otherTables[key] = {owner: fk.pkOwner, tableName: fk.pkTableName}; + otherTables[key] = { owner: fk.pkOwner, tableName: fk.pkTableName }; } }); } @@ -1604,10 +1604,10 @@ DataSource.prototype.discoverSchemasSync = function (modelName, options) { * @property {Boolean} views True if views are included; false otherwise. * @param {Function} [cb] The callback function */ -DataSource.prototype.discoverAndBuildModels = function (modelName, options, cb) { +DataSource.prototype.discoverAndBuildModels = function(modelName, options, cb) { var self = this; options = options || {}; - this.discoverSchemas(modelName, options, function (err, schemas) { + this.discoverSchemas(modelName, options, function(err, schemas) { if (err) { cb && cb(err, schemas); return; @@ -1643,7 +1643,7 @@ DataSource.prototype.discoverAndBuildModels = function (modelName, options, cb) * @param {String} modelName The model name * @param {Object} [options] The options */ -DataSource.prototype.discoverAndBuildModelsSync = function (modelName, options) { +DataSource.prototype.discoverAndBuildModelsSync = function(modelName, options) { options = options || {}; var schemas = this.discoverSchemasSync(modelName, options); @@ -1670,7 +1670,7 @@ DataSource.prototype.discoverAndBuildModelsSync = function (modelName, options) * @param {Object} options Options * @returns {*} */ -DataSource.prototype.buildModelFromInstance = function (name, json, options) { +DataSource.prototype.buildModelFromInstance = function(name, json, options) { // Introspect the JSON document to generate a schema var schema = ModelBuilder.introspect(json); @@ -1684,7 +1684,7 @@ DataSource.prototype.buildModelFromInstance = function (name, json, options) { * This method applies only to SQL connectors. * @param {String|String[]} [models] A model name or an array of model names. If not present, apply to all models. */ -DataSource.prototype.isActual = function (models, cb) { +DataSource.prototype.isActual = function(models, cb) { this.freeze(); if (this.connector.isActual) { this.connector.isActual(models, cb); @@ -1694,7 +1694,7 @@ DataSource.prototype.isActual = function (models, cb) { models = undefined; } if (cb) { - process.nextTick(function () { + process.nextTick(function() { cb(null, true); }); } @@ -1707,7 +1707,7 @@ DataSource.prototype.isActual = function (models, cb) { * * @private used by connectors */ -DataSource.prototype.log = function (sql, t) { +DataSource.prototype.log = function(sql, t) { debug(sql, t); this.emit('log', sql, t); }; @@ -1731,7 +1731,7 @@ DataSource.prototype.freeze = function freeze() { * Return table name for specified `modelName` * @param {String} modelName The model name */ -DataSource.prototype.tableName = function (modelName) { +DataSource.prototype.tableName = function(modelName) { return this.getModelDefinition(modelName).tableName(this.connector.name); }; @@ -1741,7 +1741,7 @@ DataSource.prototype.tableName = function (modelName) { * @param {String} propertyName The property name * @returns {String} columnName The column name. */ -DataSource.prototype.columnName = function (modelName, propertyName) { +DataSource.prototype.columnName = function(modelName, propertyName) { return this.getModelDefinition(modelName).columnName(this.connector.name, propertyName); }; @@ -1751,7 +1751,7 @@ DataSource.prototype.columnName = function (modelName, propertyName) { * @param {String} propertyName The property name * @returns {Object} column metadata */ -DataSource.prototype.columnMetadata = function (modelName, propertyName) { +DataSource.prototype.columnMetadata = function(modelName, propertyName) { return this.getModelDefinition(modelName).columnMetadata(this.connector.name, propertyName); }; @@ -1760,7 +1760,7 @@ DataSource.prototype.columnMetadata = function (modelName, propertyName) { * @param {String} modelName The model name * @returns {String[]} column names */ -DataSource.prototype.columnNames = function (modelName) { +DataSource.prototype.columnNames = function(modelName) { return this.getModelDefinition(modelName).columnNames(this.connector.name); }; @@ -1769,7 +1769,7 @@ DataSource.prototype.columnNames = function (modelName) { * @param {String} modelName The model name * @returns {String} columnName for ID */ -DataSource.prototype.idColumnName = function (modelName) { +DataSource.prototype.idColumnName = function(modelName) { return this.getModelDefinition(modelName).idColumnName(this.connector.name); }; @@ -1778,7 +1778,7 @@ DataSource.prototype.idColumnName = function (modelName) { * @param {String} modelName The model name * @returns {String} property name for ID */ -DataSource.prototype.idName = function (modelName) { +DataSource.prototype.idName = function(modelName) { if (!this.getModelDefinition(modelName).idName) { console.error('No id name', this.getModelDefinition(modelName)); } @@ -1790,7 +1790,7 @@ DataSource.prototype.idName = function (modelName) { * @param {String} modelName The model name * @returns {String[]} property names for IDs */ -DataSource.prototype.idNames = function (modelName) { +DataSource.prototype.idNames = function(modelName) { return this.getModelDefinition(modelName).idNames(); }; @@ -1799,7 +1799,7 @@ DataSource.prototype.idNames = function (modelName) { * @param {String} modelName The model name * @returns {Object} The id property definition */ -DataSource.prototype.idProperty = function (modelName) { +DataSource.prototype.idProperty = function(modelName) { var def = this.getModelDefinition(modelName); var idProps = def && def.ids(); return idProps && idProps[0] && idProps[0].property; @@ -1828,7 +1828,7 @@ DataSource.prototype.defineForeignKey = function defineForeignKey(className, key return; } - var fkDef = {type: pkType}; + var fkDef = { type: pkType }; var foreignMeta = this.columnMetadata(foreignClassName, pkName); if (foreignMeta && (foreignMeta.dataType || foreignMeta.dataLength)) { fkDef[this.connector.name] = {}; @@ -1840,7 +1840,7 @@ DataSource.prototype.defineForeignKey = function defineForeignKey(className, key } } if (this.connector.defineForeignKey) { - var cb = function (err, keyType) { + var cb = function(err, keyType) { if (err) throw err; fkDef.type = keyType || pkType; // Add the foreign key property to the data source _models @@ -1869,12 +1869,12 @@ DataSource.prototype.defineForeignKey = function defineForeignKey(className, key DataSource.prototype.disconnect = function disconnect(cb) { var self = this; if (this.connected && (typeof this.connector.disconnect === 'function')) { - this.connector.disconnect(function (err, result) { + this.connector.disconnect(function(err, result) { self.connected = false; cb && cb(err, result); }); } else { - process.nextTick(function () { + process.nextTick(function() { cb && cb(); }); } @@ -1914,7 +1914,7 @@ DataSource.prototype.copyModel = function copyModel(Master) { dataSource.connector.define({ model: Slave, properties: md.properties, - settings: md.settings + settings: md.settings, }); } @@ -1928,7 +1928,7 @@ DataSource.prototype.copyModel = function copyModel(Master) { * @returns {EventEmitter} * @private */ -DataSource.prototype.transaction = function () { +DataSource.prototype.transaction = function() { var dataSource = this; var transaction = new EventEmitter(); @@ -1953,7 +1953,7 @@ DataSource.prototype.transaction = function () { dataSource.copyModel.call(transaction, dataSource.modelBuilder.models[i]); } - transaction.exec = function (cb) { + transaction.exec = function(cb) { transaction.connector.exec(cb); }; @@ -1966,14 +1966,14 @@ DataSource.prototype.transaction = function () { * @param {String} operation The operation name */ -DataSource.prototype.enableRemote = function (operation) { +DataSource.prototype.enableRemote = function(operation) { var op = this.getOperation(operation); if (op) { op.remoteEnabled = true; } else { throw new Error(operation + ' is not provided by the attached connector'); } -} +}; /** * Disable remote access to a data source operation. Each [connector](#connector) has its own set of set enabled @@ -1995,21 +1995,21 @@ DataSource.prototype.enableRemote = function (operation) { * @param {String} operation The operation name */ -DataSource.prototype.disableRemote = function (operation) { +DataSource.prototype.disableRemote = function(operation) { var op = this.getOperation(operation); if (op) { op.remoteEnabled = false; } else { throw new Error(operation + ' is not provided by the attached connector'); } -} +}; /** * Get an operation's metadata. * @param {String} operation The operation name */ -DataSource.prototype.getOperation = function (operation) { +DataSource.prototype.getOperation = function(operation) { var ops = this.operations(); var opKeys = Object.keys(ops); @@ -2020,7 +2020,7 @@ DataSource.prototype.getOperation = function (operation) { return op; } } -} +}; /** * Return JSON object describing all operations. @@ -2045,9 +2045,9 @@ DataSource.prototype.getOperation = function (operation) { * } * ``` */ -DataSource.prototype.operations = function () { +DataSource.prototype.operations = function() { return this._operations; -} +}; /** * Define an operation to the data source @@ -2055,7 +2055,7 @@ DataSource.prototype.operations = function () { * @param {Object} options The options * @param {Function} fn The function */ -DataSource.prototype.defineOperation = function (name, options, fn) { +DataSource.prototype.defineOperation = function(name, options, fn) { options.fn = fn; options.name = name; this._operations[name] = options; @@ -2065,7 +2065,7 @@ DataSource.prototype.defineOperation = function (name, options, fn) { * Check if the backend is a relational DB * @returns {Boolean} */ -DataSource.prototype.isRelational = function () { +DataSource.prototype.isRelational = function() { return this.connector && this.connector.relational; }; @@ -2075,7 +2075,7 @@ DataSource.prototype.isRelational = function () { * @param {Object} obj ? * @param {Object} args ? */ -DataSource.prototype.ready = function (obj, args) { +DataSource.prototype.ready = function(obj, args) { var self = this; if (this.connected) { // Connected @@ -2107,7 +2107,7 @@ DataSource.prototype.ready = function (obj, args) { } } }; - onError = function (err) { + onError = function(err) { // Remove the connected listener self.removeListener('connected', onConnected); if (timeoutHandle) { @@ -2126,7 +2126,7 @@ DataSource.prototype.ready = function (obj, args) { // Set up a timeout to cancel the invocation var timeout = this.settings.connectionTimeout || 5000; - timeoutHandle = setTimeout(function () { + timeoutHandle = setTimeout(function() { self.removeListener('error', onError); self.removeListener('connected', onConnected); var params = [].slice.call(args); @@ -2146,14 +2146,14 @@ DataSource.prototype.ready = function (obj, args) { * Ping the underlying connector to test the connections * @param {Function} [cb] Callback function */ -DataSource.prototype.ping = function (cb) { +DataSource.prototype.ping = function(cb) { var self = this; if (self.connector.ping) { this.connector.ping(cb); } else if (self.connector.discoverModelProperties) { self.discoverModelProperties('dummy', {}, cb); } else { - process.nextTick(function () { + process.nextTick(function() { var err = self.connected ? null : 'Not connected'; cb(err); }); @@ -2171,7 +2171,7 @@ function hiddenProperty(obj, key, value) { writable: false, enumerable: false, configurable: false, - value: value + value: value, }); } @@ -2187,7 +2187,7 @@ function defineReadonlyProp(obj, key, value) { writable: false, enumerable: true, configurable: true, - value: value + value: value, }); } @@ -2200,6 +2200,6 @@ DataSource.Any = ModelBuilder.Any; * @deprecated Use ModelBuilder.registerType instead * @param type */ -DataSource.registerType = function (type) { +DataSource.registerType = function(type) { ModelBuilder.registerType(type); }; diff --git a/lib/geo.js b/lib/geo.js index 8b43198e..07c5afd5 100644 --- a/lib/geo.js +++ b/lib/geo.js @@ -13,7 +13,7 @@ exports.nearFilter = function nearFilter(where) { var result = false; if (where && typeof where === 'object') { - Object.keys(where).forEach(function (key) { + Object.keys(where).forEach(function(key) { var ex = where[key]; if (ex && ex.near) { @@ -21,20 +21,20 @@ exports.nearFilter = function nearFilter(where) { near: ex.near, maxDistance: ex.maxDistance, unit: ex.unit, - key: key + key: key, }; } }); } return result; -} +}; /*! * Filter a set of objects using the given `nearFilter`. */ -exports.filter = function (arr, filter) { +exports.filter = function(arr, filter) { var origin = filter.near; var max = filter.maxDistance > 0 ? filter.maxDistance : false; var unit = filter.unit; @@ -44,7 +44,7 @@ exports.filter = function (arr, filter) { var distances = {}; var result = []; - arr.forEach(function (obj) { + arr.forEach(function(obj) { var loc = obj[key]; // filter out objects without locations @@ -57,7 +57,7 @@ exports.filter = function (arr, filter) { if (typeof loc.lat !== 'number') return; if (typeof loc.lng !== 'number') return; - var d = GeoPoint.distanceBetween(origin, loc, {type: unit}); + var d = GeoPoint.distanceBetween(origin, loc, { type: unit }); if (max && d > max) { // dont add @@ -67,7 +67,7 @@ exports.filter = function (arr, filter) { } }); - return result.sort(function (objA, objB) { + return result.sort(function(objA, objB) { var a = objA[key]; var b = objB[key]; @@ -81,31 +81,31 @@ exports.filter = function (arr, filter) { return 0; } }); -} +}; exports.GeoPoint = GeoPoint; -/** +/** * The GeoPoint object represents a physical location. - * + * * For example: - * + * * ```js * var loopback = require(‘loopback’); * var here = new loopback.GeoPoint({lat: 10.32424, lng: 5.84978}); * ``` - * + * * Embed a latitude / longitude point in a model. - * + * * ```js * var CoffeeShop = loopback.createModel('coffee-shop', { * location: 'GeoPoint' * }); * ``` - * + * * You can query LoopBack models with a GeoPoint property and an attached data source using geo-spatial filters and * sorting. For example, the following code finds the three nearest coffee shops. - * + * * ```js * CoffeeShop.attachTo(oracle); * var here = new GeoPoint({lat: 10.32424, lng: 5.84978}); @@ -114,9 +114,9 @@ exports.GeoPoint = GeoPoint; * }); * ``` * @class GeoPoint - * @property {Number} lat The latitude in degrees. - * @property {Number} lng The longitude in degrees. - * + * @property {Number} lat The latitude in degrees. + * @property {Number} lng The longitude in degrees. + * * @options {Object} Options Object with two Number properties: lat and long. * @property {Number} lat The latitude point in degrees. Range: -90 to 90. * @property {Number} lng The longitude point in degrees. Range: -180 to 180. @@ -131,10 +131,10 @@ function GeoPoint(data) { return new GeoPoint(data); } - if(arguments.length === 2) { + if (arguments.length === 2) { data = { lat: arguments[0], - lng: arguments[1] + lng: arguments[1], }; } @@ -147,7 +147,7 @@ function GeoPoint(data) { if (Array.isArray(data)) { data = { lat: Number(data[0]), - lng: Number(data[1]) + lng: Number(data[1]), }; } else { data.lng = Number(data.lng); @@ -162,18 +162,18 @@ function GeoPoint(data) { assert(data.lat <= 90, 'lat must be <= 90'); assert(data.lat >= -90, 'lat must be >= -90'); - this.lat = data.lat; + this.lat = data.lat; this.lng = data.lng; } /** * Determine the spherical distance between two GeoPoints. - * + * * @param {GeoPoint} pointA Point A * @param {GeoPoint} pointB Point B * @options {Object} options Options object with one key, 'type'. See below. * @property {String} type Unit of measurement, one of: - * + * * - `miles` (default) * - `radians` * - `kilometers` @@ -205,16 +205,16 @@ GeoPoint.distanceBetween = function distanceBetween(a, b, options) { * Example: * ```js * var loopback = require(‘loopback’); - * + * * var here = new loopback.GeoPoint({lat: 10, lng: 10}); * var there = new loopback.GeoPoint({lat: 5, lng: 5}); - * + * * loopback.GeoPoint.distanceBetween(here, there, {type: 'miles'}) // 438 * ``` * @param {Object} point GeoPoint object to which to measure distance. * @options {Object} options Options object with one key, 'type'. See below. * @property {String} type Unit of measurement, one of: - * + * * - `miles` (default) * - `radians` * - `kilometers` @@ -224,7 +224,7 @@ GeoPoint.distanceBetween = function distanceBetween(a, b, options) { * - `degrees` */ -GeoPoint.prototype.distanceTo = function (point, options) { +GeoPoint.prototype.distanceTo = function(point, options) { return GeoPoint.distanceBetween(this, point, options); }; @@ -232,7 +232,7 @@ GeoPoint.prototype.distanceTo = function (point, options) { * Simple serialization. */ -GeoPoint.prototype.toString = function () { +GeoPoint.prototype.toString = function() { return this.lat + ',' + this.lng; }; @@ -255,7 +255,7 @@ var EARTH_RADIUS = { miles: 3958.75, feet: 20902200, radians: 1, - degrees: RAD2DEG + degrees: RAD2DEG, }; function geoDistance(x1, y1, x2, y2, options) { @@ -268,7 +268,7 @@ function geoDistance(x1, y1, x2, y2, options) { x2 = x2 * DEG2RAD; y2 = y2 * DEG2RAD; - // use the haversine formula to calculate distance for any 2 points on a sphere. + // use the haversine formula to calculate distance for any 2 points on a sphere. // ref http://en.wikipedia.org/wiki/Haversine_formula var haversine = function(a) { return Math.pow(Math.sin(a / 2.0), 2); diff --git a/lib/hooks.js b/lib/hooks.js index 7c72fa81..ffdbd0fc 100644 --- a/lib/hooks.js +++ b/lib/hooks.js @@ -36,10 +36,10 @@ Hookable.afterDestroy = null; // TODO: Evaluate https://github.com/bnoguchi/hooks-js/ Hookable.prototype.trigger = function trigger(actionName, work, data, callback) { var capitalizedName = capitalize(actionName); - var beforeHook = this.constructor["before" + capitalizedName] - || this.constructor["pre" + capitalizedName]; - var afterHook = this.constructor["after" + capitalizedName] - || this.constructor["post" + capitalizedName]; + var beforeHook = this.constructor['before' + capitalizedName] + || this.constructor['pre' + capitalizedName]; + var afterHook = this.constructor['after' + capitalizedName] + || this.constructor['post' + capitalizedName]; if (actionName === 'validate') { beforeHook = beforeHook || this.constructor.beforeValidation; afterHook = afterHook || this.constructor.afterValidation; @@ -57,7 +57,7 @@ Hookable.prototype.trigger = function trigger(actionName, work, data, callback) if (work) { if (beforeHook) { // before hook should be called on instance with two parameters: next and data - beforeHook.call(inst, function () { + beforeHook.call(inst, function() { // Check arguments to next(err, result) if (arguments.length) { return callback && callback.apply(null, arguments); diff --git a/lib/include.js b/lib/include.js index 9a78d892..d02a2474 100644 --- a/lib/include.js +++ b/lib/include.js @@ -100,11 +100,11 @@ function lookupModel(models, modelName) { function execTasksWithInterLeave(tasks, callback) { //let's give others some time to process. //Context Switch BEFORE Heavy Computation - process.nextTick(function () { + process.nextTick(function() { //Heavy Computation - async.parallel(tasks, function (err, info) { + async.parallel(tasks, function(err, info) { //Context Switch AFTER Heavy Computation - process.nextTick(function () { + process.nextTick(function() { callback(err, info); }); }); @@ -156,7 +156,7 @@ Inclusion.normalizeInclude = normalizeInclude; * @param {Function} cb Callback called when relations are loaded * */ -Inclusion.include = function (objects, include, options, cb) { +Inclusion.include = function(objects, include, options, cb) { if (typeof options === 'function' && cb === undefined) { cb = options; options = {}; @@ -236,14 +236,14 @@ Inclusion.include = function (objects, include, options, cb) { if (filter.fields && Array.isArray(subInclude) && relation.modelTo.relations) { includeScope.fields = []; - subInclude.forEach(function (name) { + subInclude.forEach(function(name) { var rel = relation.modelTo.relations[name]; if (rel && rel.type === 'belongsTo') { includeScope.fields.push(rel.keyFrom); } }); } - utils.mergeQuery(filter, includeScope, {fields: false}); + utils.mergeQuery(filter, includeScope, { fields: false }); } //Let's add a placeholder where query filter.where = filter.where || {}; @@ -276,7 +276,7 @@ Inclusion.include = function (objects, include, options, cb) { } //This handles exactly hasMany. Fast and straightforward. Without parallel, each and other boilerplate. - if(relation.type === 'hasMany' && relation.multiple && !subInclude){ + if (relation.type === 'hasMany' && relation.multiple && !subInclude) { return includeHasManySimple(cb); } //assuming all other relations with multiple=true as hasMany @@ -321,10 +321,10 @@ Inclusion.include = function (objects, include, options, cb) { //default filters are not applicable on through model. should be applied //on modelTo later in 2nd DB call. var throughFilter = { - where: {} + where: {}, }; throughFilter.where[relation.keyTo] = { - inq: uniq(sourceIds) + inq: uniq(sourceIds), }; if (polymorphic) { //handle polymorphic hasMany (reverse) in which case we need to filter @@ -367,7 +367,7 @@ Inclusion.include = function (objects, include, options, cb) { //Polymorphic relation does not have idKey of modelTo. Find it manually var modelToIdName = idName(relation.modelTo); filter.where[modelToIdName] = { - inq: uniq(targetIds) + inq: uniq(targetIds), }; //make sure that the modelToIdName is included if fields are specified @@ -401,7 +401,7 @@ Inclusion.include = function (objects, include, options, cb) { function linkManyToMany(target, next) { var targetId = target[modelToIdName]; var objList = targetObjsMap[targetId.toString()]; - async.each(objList, function (obj, next) { + async.each(objList, function(obj, next) { if (!obj) return next(); obj.__cachedRelations[relationName].push(target); processTargetObj(obj, next); @@ -450,7 +450,7 @@ Inclusion.include = function (objects, include, options, cb) { obj.__cachedRelations[relationName] = []; } filter.where[relation.keyTo] = { - inq: uniq(allTargetIds) + inq: uniq(allTargetIds), }; relation.applyScope(null, filter); /** @@ -481,7 +481,7 @@ Inclusion.include = function (objects, include, options, cb) { async.each(targets, linkManyToMany, next); function linkManyToMany(target, next) { var objList = targetObjsMap[target[relation.keyTo].toString()]; - async.each(objList, function (obj, next) { + async.each(objList, function(obj, next) { if (!obj) return next(); obj.__cachedRelations[relationName].push(target); processTargetObj(obj, next); @@ -503,21 +503,21 @@ Inclusion.include = function (objects, include, options, cb) { var objIdMap2 = includeUtils.buildOneToOneIdentityMapWithOrigKeys(objs, relation.keyFrom); filter.where[relation.keyTo] = { - inq: uniq(objIdMap2.getKeys()) + inq: uniq(objIdMap2.getKeys()), }; relation.applyScope(null, filter); relation.modelTo.find(filter, options, targetFetchHandler); function targetFetchHandler(err, targets) { - if(err) { + if (err) { return callback(err); } var targetsIdMap = includeUtils.buildOneToManyIdentityMapWithOrigKeys(targets, relation.keyTo); - includeUtils.join(objIdMap2, targetsIdMap, function(obj1, valueToMergeIn){ + includeUtils.join(objIdMap2, targetsIdMap, function(obj1, valueToMergeIn) { defineCachedRelations(obj1); obj1.__cachedRelations[relationName] = valueToMergeIn; - processTargetObj(obj1, function(){}); + processTargetObj(obj1, function() {}); }); callback(err, objs); } @@ -545,7 +545,7 @@ Inclusion.include = function (objects, include, options, cb) { obj.__cachedRelations[relationName] = []; } filter.where[relation.keyTo] = { - inq: uniq(sourceIds) + inq: uniq(sourceIds), }; relation.applyScope(null, filter); options.partitionBy = relation.keyTo; @@ -580,7 +580,7 @@ Inclusion.include = function (objects, include, options, cb) { function linkManyToOne(target, next) { //fix for bug in hasMany with referencesMany var targetIds = [].concat(target[relation.keyTo]); - async.each(targetIds, function (targetId, next) { + async.each(targetIds, function(targetId, next) { var obj = objIdMap[targetId.toString()]; if (!obj) return next(); obj.__cachedRelations[relationName].push(target); @@ -644,11 +644,11 @@ Inclusion.include = function (objects, include, options, cb) { * @param callback */ function processPolymorphicType(modelType, callback) { - var typeFilter = {where: {}}; + var typeFilter = { where: {}}; utils.mergeQuery(typeFilter, filter); var targetIds = targetIdsByType[modelType]; typeFilter.where[relation.keyTo] = { - inq: uniq(targetIds) + inq: uniq(targetIds), }; var Model = lookupModel(relation.modelFrom.dataSource.modelBuilder. models, modelType); @@ -684,7 +684,7 @@ Inclusion.include = function (objects, include, options, cb) { async.each(targets, linkOneToMany, next); function linkOneToMany(target, next) { var objList = targetObjsMap[target[relation.keyTo].toString()]; - async.each(objList, function (obj, next) { + async.each(objList, function(obj, next) { if (!obj) return next(); obj.__cachedRelations[relationName] = target; processTargetObj(obj, next); @@ -720,7 +720,7 @@ Inclusion.include = function (objects, include, options, cb) { obj.__cachedRelations[relationName] = null; } filter.where[relation.keyTo] = { - inq: uniq(sourceIds) + inq: uniq(sourceIds), }; relation.applyScope(null, filter); relation.modelTo.find(filter, options, targetFetchHandler); @@ -787,7 +787,7 @@ Inclusion.include = function (objects, include, options, cb) { obj.__cachedRelations[relationName] = null; } filter.where[relation.keyTo] = { - inq: uniq(targetIds) + inq: uniq(targetIds), }; relation.applyScope(null, filter); relation.modelTo.find(filter, options, targetFetchHandler); @@ -815,7 +815,7 @@ Inclusion.include = function (objects, include, options, cb) { function linkOneToMany(target, next) { var targetId = target[relation.keyTo]; var objList = objTargetIdMap[targetId.toString()]; - async.each(objList, function (obj, next) { + async.each(objList, function(obj, next) { if (!obj) return next(); obj.__cachedRelations[relationName] = target; processTargetObj(obj, next); @@ -838,7 +838,7 @@ Inclusion.include = function (objects, include, options, cb) { * @param callback */ function includeEmbeds(callback) { - async.each(objs, function (obj, next) { + async.each(objs, function(obj, next) { processTargetObj(obj, next); }, callback); } @@ -914,14 +914,14 @@ Inclusion.include = function (objects, include, options, cb) { }); } - utils.mergeQuery(filter, includeScope, {fields: false}); + utils.mergeQuery(filter, includeScope, { fields: false }); related = inst[relationName].bind(inst, filter); } else { related = inst[relationName].bind(inst, undefined); } - related(options, function (err, result) { + related(options, function(err, result) { if (err) { return callback(err); } else { diff --git a/lib/include_utils.js b/lib/include_utils.js index e12042ad..29145fb9 100644 --- a/lib/include_utils.js +++ b/lib/include_utils.js @@ -18,7 +18,7 @@ module.exports.KVMap = KVMap; */ function buildOneToOneIdentityMapWithOrigKeys(objs, idName) { var kvMap = new KVMap(); - for(var i = 0; i < objs.length; i++) { + for (var i = 0; i < objs.length; i++) { var obj = objs[i]; var id = obj[idName]; kvMap.set(id, obj); @@ -28,7 +28,7 @@ function buildOneToOneIdentityMapWithOrigKeys(objs, idName) { function buildOneToManyIdentityMapWithOrigKeys(objs, idName) { var kvMap = new KVMap(); - for(var i = 0; i < objs.length; i++) { + for (var i = 0; i < objs.length; i++) { var obj = objs[i]; var id = obj[idName]; var value = kvMap.get(id) || []; @@ -48,7 +48,7 @@ function buildOneToManyIdentityMapWithOrigKeys(objs, idName) { */ function join(oneToOneIdMap, oneToManyIdMap, mergeF) { var ids = oneToOneIdMap.getKeys(); - for(var i = 0; i < ids.length; i++) { + for (var i = 0; i < ids.length; i++) { var id = ids[i]; var obj = oneToOneIdMap.get(id); var objectsToMergeIn = oneToManyIdMap.get(id) || []; @@ -62,28 +62,28 @@ function join(oneToOneIdMap, oneToManyIdMap, mergeF) { * @returns {{set: Function, get: Function, remove: Function, exist: Function, getKeys: Function}} * @constructor */ -function KVMap(){ +function KVMap() { var _originalKeyFieldName = 'originalKey'; var _valueKeyFieldName = 'value'; var _dict = {}; - var keyToString = function(key){ return key.toString() }; + var keyToString = function(key) { return key.toString(); }; var mapImpl = { - set: function(key, value){ + set: function(key, value) { var recordObj = {}; recordObj[_originalKeyFieldName] = key; recordObj[_valueKeyFieldName] = value; _dict[keyToString(key)] = recordObj; return true; }, - get: function(key){ + get: function(key) { var storeObj = _dict[keyToString(key)]; - if(storeObj) { + if (storeObj) { return storeObj[_valueKeyFieldName]; } else { return undefined; } }, - remove: function(key){ + remove: function(key) { delete _dict[keyToString(key)]; return true; }, @@ -91,13 +91,13 @@ function KVMap(){ var result = _dict.hasOwnProperty(keyToString(key)); return result; }, - getKeys: function(){ + getKeys: function() { var result = []; - for(var key in _dict) { + for (var key in _dict) { result.push(_dict[key][_originalKeyFieldName]); } return result; - } + }, }; return mapImpl; diff --git a/lib/introspection.js b/lib/introspection.js index 34ccf392..8fd27c4c 100644 --- a/lib/introspection.js +++ b/lib/introspection.js @@ -62,6 +62,6 @@ module.exports = function getIntrospector(ModelBuilder) { ModelBuilder.introspect = introspectType; return introspectType; -} +}; diff --git a/lib/jutil.js b/lib/jutil.js index 7b5f7cda..29049669 100644 --- a/lib/jutil.js +++ b/lib/jutil.js @@ -10,16 +10,16 @@ var util = require('util'); * @param newClass * @param baseClass */ -exports.inherits = function (newClass, baseClass, options) { +exports.inherits = function(newClass, baseClass, options) { util.inherits(newClass, baseClass); options = options || { staticProperties: true, - override: false + override: false, }; if (options.staticProperties) { - Object.keys(baseClass).forEach(function (classProp) { + Object.keys(baseClass).forEach(function(classProp) { if (classProp !== 'super_' && (!newClass.hasOwnProperty(classProp) || options.override)) { var pd = Object.getOwnPropertyDescriptor(baseClass, classProp); @@ -35,7 +35,7 @@ exports.inherits = function (newClass, baseClass, options) { * @param mixinClass The class to be mixed in * @param options */ -exports.mixin = function (newClass, mixinClass, options) { +exports.mixin = function(newClass, mixinClass, options) { if (Array.isArray(newClass._mixins)) { if (newClass._mixins.indexOf(mixinClass) !== -1) { return; @@ -49,7 +49,7 @@ exports.mixin = function (newClass, mixinClass, options) { staticProperties: true, instanceProperties: true, override: false, - proxyFunctions: false + proxyFunctions: false, }; if (options.staticProperties === undefined) { @@ -72,7 +72,7 @@ exports.mixin = function (newClass, mixinClass, options) { }; function mixInto(sourceScope, targetScope, options) { - Object.keys(sourceScope).forEach(function (propertyName) { + Object.keys(sourceScope).forEach(function(propertyName) { var targetPropertyExists = targetScope.hasOwnProperty(propertyName); var sourceProperty = Object.getOwnPropertyDescriptor(sourceScope, propertyName); var targetProperty = targetPropertyExists && Object.getOwnPropertyDescriptor(targetScope, propertyName); diff --git a/lib/list.js b/lib/list.js index 0f47c5a8..94d211a5 100644 --- a/lib/list.js +++ b/lib/list.js @@ -34,7 +34,7 @@ function List(items, itemType, parent) { throw err; } - if(!itemType) { + if (!itemType) { itemType = items[0] && items[0].constructor; } @@ -42,25 +42,25 @@ function List(items, itemType, parent) { itemType = itemType[0]; } - if(itemType === Array) { + if (itemType === Array) { itemType = Any; } Object.defineProperty(arr, 'itemType', { writable: true, enumerable: false, - value: itemType + value: itemType, }); if (parent) { Object.defineProperty(arr, 'parent', { writable: true, enumerable: false, - value: parent + value: parent, }); } - items.forEach(function (item, i) { + items.forEach(function(item, i) { if (itemType && !(item instanceof itemType)) { arr[i] = itemType(item); } else { @@ -75,15 +75,15 @@ util.inherits(List, Array); var _push = List.prototype.push; -List.prototype.push = function (obj) { +List.prototype.push = function(obj) { var item = this.itemType && (obj instanceof this.itemType) ? obj : this.itemType(obj); _push.call(this, item); return item; }; -List.prototype.toObject = function (onlySchema, removeHidden, removeProtected) { +List.prototype.toObject = function(onlySchema, removeHidden, removeProtected) { var items = []; - this.forEach(function (item) { + this.forEach(function(item) { if (item && typeof item === 'object' && item.toObject) { items.push(item.toObject(onlySchema, removeHidden, removeProtected)); } else { @@ -93,11 +93,11 @@ List.prototype.toObject = function (onlySchema, removeHidden, removeProtected) { return items; }; -List.prototype.toJSON = function () { +List.prototype.toJSON = function() { return this.toObject(true); }; -List.prototype.toString = function () { +List.prototype.toString = function() { return JSON.stringify(this.toJSON()); }; diff --git a/lib/mixins.js b/lib/mixins.js index 322f0b20..e9e04d60 100644 --- a/lib/mixins.js +++ b/lib/mixins.js @@ -40,7 +40,7 @@ MixinProvider.prototype.applyMixin = function applyMixin(modelClass, name, optio } else { // Try model name var model = this.modelBuilder.getModel(name); - if(model) { + if (model) { debug('Mixin is resolved to a model: %s', name); modelClass.mixin(model, options); } else { @@ -62,7 +62,7 @@ MixinProvider.prototype.define = function defineMixin(name, mixin) { debug('Defining mixin: %s', name); } if (isModelClass(mixin)) { - this.mixins[name] = function (Model, options) { + this.mixins[name] = function(Model, options) { Model.mixin(mixin, options); }; } else if (typeof mixin === 'function') { diff --git a/lib/model-builder.js b/lib/model-builder.js index 81d1c051..9cd156b5 100644 --- a/lib/model-builder.js +++ b/lib/model-builder.js @@ -68,10 +68,10 @@ function isModelClass(cls) { * @param {Boolean} forceCreate Whether the create a stub for the given name if a model doesn't exist. * @returns {*} The model class */ -ModelBuilder.prototype.getModel = function (name, forceCreate) { +ModelBuilder.prototype.getModel = function(name, forceCreate) { var model = this.models[name]; if (!model && forceCreate) { - model = this.define(name, {}, {unresolved: true}); + model = this.define(name, {}, { unresolved: true }); } return model; }; @@ -81,7 +81,7 @@ ModelBuilder.prototype.getModel = function (name, forceCreate) { * @param {String} name The model name * @returns {ModelDefinition} The model definition */ -ModelBuilder.prototype.getModelDefinition = function (name) { +ModelBuilder.prototype.getModelDefinition = function(name) { return this.definitions[name]; }; @@ -214,7 +214,7 @@ ModelBuilder.prototype.define = function defineClass(className, properties, sett // Return the unresolved model if (settings.unresolved) { - ModelClass.settings = {unresolved: true}; + ModelClass.settings = { unresolved: true }; return ModelClass; } @@ -241,7 +241,7 @@ ModelBuilder.prototype.define = function defineClass(className, properties, sett // Load and inject the model classes if (settings.models) { - Object.keys(settings.models).forEach(function (m) { + Object.keys(settings.models).forEach(function(m) { var model = settings.models[m]; ModelClass[m] = typeof model === 'string' ? modelBuilder.getModel(model, true) : model; }); @@ -297,18 +297,18 @@ ModelBuilder.prototype.define = function defineClass(className, properties, sett var idProp = idNames[0]; if (idProp !== 'id') { Object.defineProperty(ModelClass.prototype, 'id', { - get: function () { + get: function() { var idProp = ModelClass.definition.idNames()[0]; return this.__data[idProp]; }, configurable: true, - enumerable: false + enumerable: false, }); } } else { // Now the id property is an object that consists of multiple keys Object.defineProperty(ModelClass.prototype, 'id', { - get: function () { + get: function() { var compositeId = {}; var idNames = ModelClass.definition.idNames(); for (var i = 0, p; i < idNames.length; i++) { @@ -318,12 +318,12 @@ ModelBuilder.prototype.define = function defineClass(className, properties, sett return compositeId; }, configurable: true, - enumerable: false + enumerable: false, }); } // A function to loop through the properties - ModelClass.forEachProperty = function (cb) { + ModelClass.forEachProperty = function(cb) { var props = ModelClass.definition.properties; var keys = Object.keys(props); for (var i = 0, n = keys.length; i < n; i++) { @@ -332,7 +332,7 @@ ModelBuilder.prototype.define = function defineClass(className, properties, sett }; // A function to attach the model class to a data source - ModelClass.attachTo = function (dataSource) { + ModelClass.attachTo = function(dataSource) { dataSource.attach(this); }; @@ -356,7 +356,7 @@ ModelBuilder.prototype.define = function defineClass(className, properties, sett * @options {Object} settings Model settings, such as relations and acls. * */ - ModelClass.extend = function (className, subclassProperties, subclassSettings) { + ModelClass.extend = function(className, subclassProperties, subclassSettings) { var properties = ModelClass.definition.properties; var settings = ModelClass.definition.settings; @@ -418,7 +418,7 @@ ModelBuilder.prototype.define = function defineClass(className, properties, sett * Register a property for the model class * @param {String} propertyName Name of the property. */ - ModelClass.registerProperty = function (propertyName) { + ModelClass.registerProperty = function(propertyName) { var properties = modelDefinition.build(); var prop = properties[propertyName]; var DataType = prop.type; @@ -432,14 +432,14 @@ ModelBuilder.prototype.define = function defineClass(className, properties, sett } Object.defineProperty(ModelClass.prototype, propertyName, { - get: function () { + get: function() { if (ModelClass.getter[propertyName]) { return ModelClass.getter[propertyName].call(this); // Try getter first } else { return this.__data && this.__data[propertyName]; // Try __data } }, - set: function (value) { + set: function(value) { var DataType = ModelClass.definition.properties[propertyName].type; if (Array.isArray(DataType) || DataType === Array) { DataType = List; @@ -474,23 +474,23 @@ ModelBuilder.prototype.define = function defineClass(className, properties, sett } }, configurable: true, - enumerable: true + enumerable: true, }); // FIXME: [rfeng] Do we need to keep the raw data? // Use $ as the prefix to avoid conflicts with properties such as _id Object.defineProperty(ModelClass.prototype, '$' + propertyName, { - get: function () { + get: function() { return this.__data && this.__data[propertyName]; }, - set: function (value) { + set: function(value) { if (!this.__data) { this.__data = {}; } this.__data[propertyName] = value; }, configurable: true, - enumerable: false + enumerable: false, }); }; @@ -563,7 +563,7 @@ function BooleanType(arg) { * @param {String} propertyName Name of property * @param {Object} propertyDefinition Property settings */ -ModelBuilder.prototype.defineProperty = function (model, propertyName, propertyDefinition) { +ModelBuilder.prototype.defineProperty = function(model, propertyName, propertyDefinition) { this.definitions[model].defineProperty(propertyName, propertyDefinition); this.models[model].registerProperty(propertyName); }; @@ -607,7 +607,7 @@ ModelBuilder.prototype.defineValueType = function(type, aliases) { * @property {String} type Datatype of property: Must be an [LDL type](http://docs.strongloop.com/display/LB/LoopBack+types). * @property {Boolean} index True if the property is an index; false otherwise. */ -ModelBuilder.prototype.extendModel = function (model, props) { +ModelBuilder.prototype.extendModel = function(model, props) { var t = this; var keys = Object.keys(props); for (var i = 0; i < keys.length; i++) { @@ -638,7 +638,7 @@ ModelBuilder.prototype.copyModel = function copyModel(Master) { modelBuilder.models[className] = Slave; modelBuilder.definitions[className] = { properties: md.properties, - settings: md.settings + settings: md.settings, }; } @@ -653,14 +653,14 @@ function hiddenProperty(where, property, value) { writable: true, enumerable: false, configurable: true, - value: value + value: value, }); } /** * Get the schema name */ -ModelBuilder.prototype.getSchemaName = function (name) { +ModelBuilder.prototype.getSchemaName = function(name) { if (name) { return name; } @@ -677,7 +677,7 @@ ModelBuilder.prototype.getSchemaName = function (name) { * Returns {Function} if the type is resolved * @param {String} type The type string, such as 'number', 'Number', 'boolean', or 'String'. It's case insensitive */ -ModelBuilder.prototype.resolveType = function (type) { +ModelBuilder.prototype.resolveType = function(type) { if (!type) { return type; } @@ -697,7 +697,7 @@ ModelBuilder.prototype.resolveType = function (type) { return schemaType; } else { // The type cannot be resolved, let's create a place holder - type = this.define(type, {}, {unresolved: true}); + type = this.define(type, {}, { unresolved: true }); return type; } } else if (type.constructor.name === 'Object') { @@ -706,7 +706,7 @@ ModelBuilder.prototype.resolveType = function (type) { return this.resolveType(type.type); } else { return this.define(this.getSchemaName(null), - type, {anonymous: true, idInjection: false}); + type, { anonymous: true, idInjection: false }); } } else if ('function' === typeof type) { return type; @@ -726,7 +726,7 @@ ModelBuilder.prototype.resolveType = function (type) { * @param {*} schemas The schemas * @returns {Object} A map of model constructors keyed by model name */ -ModelBuilder.prototype.buildModels = function (schemas, createModel) { +ModelBuilder.prototype.buildModels = function(schemas, createModel) { var models = {}; // Normalize the schemas to be an array of the schema objects {name: , properties: {}, options: {}} @@ -740,8 +740,8 @@ ModelBuilder.prototype.buildModels = function (schemas, createModel) { { name: this.getSchemaName(), properties: schemas, - options: {anonymous: true} - } + options: { anonymous: true }, + }, ]; } } @@ -751,7 +751,7 @@ ModelBuilder.prototype.buildModels = function (schemas, createModel) { var name = this.getSchemaName(schemas[s].name); schemas[s].name = name; var model; - if(typeof createModel === 'function') { + if (typeof createModel === 'function') { model = createModel(schemas[s].name, schemas[s].properties, schemas[s].options); } else { model = this.define(schemas[s].name, schemas[s].properties, schemas[s].options); @@ -767,7 +767,7 @@ ModelBuilder.prototype.buildModels = function (schemas, createModel) { var targetModel = models[relation.target]; if (sourceModel && targetModel) { if (typeof sourceModel[relation.type] === 'function') { - sourceModel[relation.type](targetModel, {as: relation.as}); + sourceModel[relation.type](targetModel, { as: relation.as }); } } } @@ -781,7 +781,7 @@ ModelBuilder.prototype.buildModels = function (schemas, createModel) { * @param {Object} options The options * @returns {} */ -ModelBuilder.prototype.buildModelFromInstance = function (name, json, options) { +ModelBuilder.prototype.buildModelFromInstance = function(name, json, options) { // Introspect the JSON document to generate a schema var schema = introspect(json); diff --git a/lib/model-definition.js b/lib/model-definition.js index 8b65c50d..6481f540 100644 --- a/lib/model-definition.js +++ b/lib/model-definition.js @@ -58,7 +58,7 @@ require('./types')(ModelDefinition); * Return table name for specified `modelName` * @param {String} connectorType The connector type, such as 'oracle' or 'mongodb' */ -ModelDefinition.prototype.tableName = function (connectorType) { +ModelDefinition.prototype.tableName = function(connectorType) { var settings = this.settings; if (settings[connectorType]) { return settings[connectorType].table || settings[connectorType].tableName || this.name; @@ -73,7 +73,7 @@ ModelDefinition.prototype.tableName = function (connectorType) { * @param propertyName The property name * @returns {String} columnName */ -ModelDefinition.prototype.columnName = function (connectorType, propertyName) { +ModelDefinition.prototype.columnName = function(connectorType, propertyName) { if (!propertyName) { return propertyName; } @@ -92,7 +92,7 @@ ModelDefinition.prototype.columnName = function (connectorType, propertyName) { * @param propertyName The property name * @returns {Object} column metadata */ -ModelDefinition.prototype.columnMetadata = function (connectorType, propertyName) { +ModelDefinition.prototype.columnMetadata = function(connectorType, propertyName) { if (!propertyName) { return propertyName; } @@ -110,7 +110,7 @@ ModelDefinition.prototype.columnMetadata = function (connectorType, propertyName * @param {String} connectorType The connector type, such as 'oracle' or 'mongodb' * @returns {String[]} column names */ -ModelDefinition.prototype.columnNames = function (connectorType) { +ModelDefinition.prototype.columnNames = function(connectorType) { this.build(); var props = this.properties; var cols = []; @@ -128,7 +128,7 @@ ModelDefinition.prototype.columnNames = function (connectorType) { * Find the ID properties sorted by the index * @returns {Object[]} property name/index for IDs */ -ModelDefinition.prototype.ids = function () { +ModelDefinition.prototype.ids = function() { if (this._ids) { return this._ids; } @@ -143,9 +143,9 @@ ModelDefinition.prototype.ids = function () { if (typeof id !== 'number') { id = 1; } - ids.push({name: key, id: id, property: props[key]}); + ids.push({ name: key, id: id, property: props[key] }); } - ids.sort(function (a, b) { + ids.sort(function(a, b) { return a.id - b.id; }); this._ids = ids; @@ -157,7 +157,7 @@ ModelDefinition.prototype.ids = function () { * @param {String} modelName The model name * @returns {String} columnName for ID */ -ModelDefinition.prototype.idColumnName = function (connectorType) { +ModelDefinition.prototype.idColumnName = function(connectorType) { return this.columnName(connectorType, this.idName()); }; @@ -165,7 +165,7 @@ ModelDefinition.prototype.idColumnName = function (connectorType) { * Find the ID property name * @returns {String} property name for ID */ -ModelDefinition.prototype.idName = function () { +ModelDefinition.prototype.idName = function() { var id = this.ids()[0]; if (this.properties.id && this.properties.id.id) { return 'id'; @@ -178,9 +178,9 @@ ModelDefinition.prototype.idName = function () { * Find the ID property names sorted by the index * @returns {String[]} property names for IDs */ -ModelDefinition.prototype.idNames = function () { +ModelDefinition.prototype.idNames = function() { var ids = this.ids(); - var names = ids.map(function (id) { + var names = ids.map(function(id) { return id.name; }); return names; @@ -190,7 +190,7 @@ ModelDefinition.prototype.idNames = function () { * * @returns {{}} */ -ModelDefinition.prototype.indexes = function () { +ModelDefinition.prototype.indexes = function() { this.build(); var indexes = {}; if (this.settings.indexes) { @@ -210,7 +210,7 @@ ModelDefinition.prototype.indexes = function () { * Build a model definition * @param {Boolean} force Forcing rebuild */ -ModelDefinition.prototype.build = function (forceRebuild) { +ModelDefinition.prototype.build = function(forceRebuild) { if (forceRebuild) { this.properties = null; this.relations = []; @@ -229,11 +229,11 @@ ModelDefinition.prototype.build = function (forceRebuild) { source: this.name, target: type, type: Array.isArray(prop) ? 'hasMany' : 'belongsTo', - as: p + as: p, }); } else { var typeDef = { - type: type + type: type, }; if (typeof prop === 'object' && prop !== null) { for (var a in prop) { @@ -254,7 +254,7 @@ ModelDefinition.prototype.build = function (forceRebuild) { * @param {String} propertyName The property name * @param {Object} propertyDefinition The property definition */ -ModelDefinition.prototype.defineProperty = function (propertyName, propertyDefinition) { +ModelDefinition.prototype.defineProperty = function(propertyName, propertyDefinition) { this.rawProperties[propertyName] = propertyDefinition; this.build(true); }; @@ -266,7 +266,7 @@ function isModelClass(cls) { return cls.prototype instanceof ModelBaseClass; } -ModelDefinition.prototype.toJSON = function (forceRebuild) { +ModelDefinition.prototype.toJSON = function(forceRebuild) { if (forceRebuild) { this.json = null; } @@ -276,11 +276,11 @@ ModelDefinition.prototype.toJSON = function (forceRebuild) { var json = { name: this.name, properties: {}, - settings: this.settings + settings: this.settings, }; this.build(forceRebuild); - var mapper = function (val) { + var mapper = function(val) { if (val === undefined || val === null) { return val; } diff --git a/lib/model.js b/lib/model.js index 3d5266a6..8b9cec46 100644 --- a/lib/model.js +++ b/lib/model.js @@ -31,7 +31,7 @@ var BASE_TYPES = { 'Number': true, 'Date': true, 'Text': true, - 'ObjectID': true + 'ObjectID': true, }; /** @@ -44,7 +44,7 @@ var BASE_TYPES = { */ function ModelBaseClass(data, options) { options = options || {}; - if(!('applySetters' in options)) { + if (!('applySetters' in options)) { // Default to true options.applySetters = true; } @@ -64,11 +64,11 @@ function ModelBaseClass(data, options) { * @property {Boolean} persisted Whether the instance has been persisted * @private */ -ModelBaseClass.prototype._initProperties = function (data, options) { +ModelBaseClass.prototype._initProperties = function(data, options) { var self = this; var ctor = this.constructor; - if(data instanceof ctor) { + if (data instanceof ctor) { // Convert the data to be plain object to avoid pollutions data = data.toObject(false); } @@ -84,7 +84,7 @@ ModelBaseClass.prototype._initProperties = function (data, options) { var applyDefaultValues = options.applyDefaultValues; var strict = options.strict; - if(strict === undefined) { + if (strict === undefined) { strict = ctor.definition.settings.strict; } @@ -99,14 +99,14 @@ ModelBaseClass.prototype._initProperties = function (data, options) { writable: true, enumerable: false, configurable: true, - value: {} + value: {}, }, __data: { writable: true, enumerable: false, configurable: true, - value: {} + value: {}, }, // Instance level data source @@ -114,7 +114,7 @@ ModelBaseClass.prototype._initProperties = function (data, options) { writable: true, enumerable: false, configurable: true, - value: options.dataSource + value: options.dataSource, }, // Instance level strict mode @@ -122,14 +122,14 @@ ModelBaseClass.prototype._initProperties = function (data, options) { writable: true, enumerable: false, configurable: true, - value: strict + value: strict, }, __persisted: { writable: true, enumerable: false, configurable: true, - value: false + value: false, }, }); @@ -138,7 +138,7 @@ ModelBaseClass.prototype._initProperties = function (data, options) { writable: true, enumerable: false, configrable: true, - value: [] + value: [], }); } } else { @@ -320,13 +320,13 @@ ModelBaseClass.prototype._initProperties = function (data, options) { if (type.prototype instanceof ModelBaseClass) { if (!(self.__data[p] instanceof type) && typeof self.__data[p] === 'object' - && self.__data[p] !== null ) { + && self.__data[p] !== null) { self.__data[p] = new type(self.__data[p]); } } else if (type.name === 'Array' || Array.isArray(type)) { if (!(self.__data[p] instanceof List) && self.__data[p] !== undefined - && self.__data[p] !== null ) { + && self.__data[p] !== null) { self.__data[p] = List(self.__data[p], type, self); } } @@ -340,15 +340,15 @@ ModelBaseClass.prototype._initProperties = function (data, options) { * @param {String} prop Property name * @param {Object} params Various property configuration */ -ModelBaseClass.defineProperty = function (prop, params) { - if(this.dataSource) { +ModelBaseClass.defineProperty = function(prop, params) { + if (this.dataSource) { this.dataSource.defineProperty(this.modelName, prop, params); } else { this.modelBuilder.defineProperty(this.modelName, prop, params); } }; -ModelBaseClass.getPropertyType = function (propName) { +ModelBaseClass.getPropertyType = function(propName) { var prop = this.definition.properties[propName]; if (!prop) { // The property is not part of the definition @@ -361,7 +361,7 @@ ModelBaseClass.getPropertyType = function (propName) { return prop.type.name; }; -ModelBaseClass.prototype.getPropertyType = function (propName) { +ModelBaseClass.prototype.getPropertyType = function(propName) { return this.constructor.getPropertyType(propName); }; @@ -369,7 +369,7 @@ ModelBaseClass.prototype.getPropertyType = function (propName) { * Return string representation of class * This overrides the default `toString()` method */ -ModelBaseClass.toString = function () { +ModelBaseClass.toString = function() { return '[Model ' + this.modelName + ']'; }; @@ -379,7 +379,7 @@ ModelBaseClass.toString = function () { * * @param {Boolean} onlySchema Restrict properties to dataSource only. Default is false. If true, the function returns only properties defined in the schema; Otherwise it returns all enumerable properties. */ -ModelBaseClass.prototype.toObject = function (onlySchema, removeHidden, removeProtected) { +ModelBaseClass.prototype.toObject = function(onlySchema, removeHidden, removeProtected) { if (onlySchema === undefined) { onlySchema = true; } @@ -504,7 +504,7 @@ ModelBaseClass.prototype.toObject = function (onlySchema, removeHidden, removePr return data; }; -ModelBaseClass.isProtectedProperty = function (propertyName) { +ModelBaseClass.isProtectedProperty = function(propertyName) { var Model = this; var settings = Model.definition && Model.definition.settings; var protectedProperties = settings && (settings.protectedProperties || settings.protected); @@ -523,7 +523,7 @@ ModelBaseClass.isProtectedProperty = function (propertyName) { } }; -ModelBaseClass.isHiddenProperty = function (propertyName) { +ModelBaseClass.isHiddenProperty = function(propertyName) { var Model = this; var settings = Model.definition && Model.definition.settings; var hiddenProperties = settings && (settings.hiddenProperties || settings.hidden); @@ -542,11 +542,11 @@ ModelBaseClass.isHiddenProperty = function (propertyName) { } }; -ModelBaseClass.prototype.toJSON = function () { +ModelBaseClass.prototype.toJSON = function() { return this.toObject(false, true, false); }; -ModelBaseClass.prototype.fromObject = function (obj) { +ModelBaseClass.prototype.fromObject = function(obj) { for (var key in obj) { this[key] = obj[key]; } @@ -557,7 +557,7 @@ ModelBaseClass.prototype.fromObject = function (obj) { * This method does not perform any database operations; it just resets the object to its * initial state. */ -ModelBaseClass.prototype.reset = function () { +ModelBaseClass.prototype.reset = function() { var obj = this; for (var k in obj) { if (k !== 'id' && !obj.constructor.dataSource.definitions[obj.constructor.modelName].properties[k]) { @@ -578,20 +578,20 @@ var INSPECT_SUPPORTS_OBJECT_RETVAL = versionParts[1] > 11 || (versionParts[0] === 11 && versionParts[1] >= 14); -ModelBaseClass.prototype.inspect = function (depth) { +ModelBaseClass.prototype.inspect = function(depth) { if (INSPECT_SUPPORTS_OBJECT_RETVAL) - return this.__data; + return this.__data; // Workaround for older versions // See also https://github.com/joyent/node/commit/66280de133 return util.inspect(this.__data, { showHidden: false, depth: depth, - colors: false + colors: false, }); }; -ModelBaseClass.mixin = function (anotherClass, options) { +ModelBaseClass.mixin = function(anotherClass, options) { if (typeof anotherClass === 'string') { this.modelBuilder.mixins.applyMixin(this, anotherClass, options); } else { @@ -608,15 +608,15 @@ ModelBaseClass.mixin = function (anotherClass, options) { } }; -ModelBaseClass.prototype.getDataSource = function () { +ModelBaseClass.prototype.getDataSource = function() { return this.__dataSource || this.constructor.dataSource; }; -ModelBaseClass.getDataSource = function () { +ModelBaseClass.getDataSource = function() { return this.dataSource; }; -ModelBaseClass.prototype.setStrict = function (strict) { +ModelBaseClass.prototype.setStrict = function(strict) { this.__strict = strict; }; diff --git a/lib/observer.js b/lib/observer.js index 5de79fa1..f2046eb4 100644 --- a/lib/observer.js +++ b/lib/observer.js @@ -108,7 +108,7 @@ ObserverMixin.notifyObserversOf = function(operation, context, callback) { ); } }, - function(err) { callback(err, context) } + function(err) { callback(err, context); } ); }); return callback.promise; diff --git a/lib/relation-definition.js b/lib/relation-definition.js index 4c2780ce..12cb1eb0 100644 --- a/lib/relation-definition.js +++ b/lib/relation-definition.js @@ -26,7 +26,7 @@ var RelationTypes = { hasAndBelongsToMany: 'hasAndBelongsToMany', referencesMany: 'referencesMany', embedsOne: 'embedsOne', - embedsMany: 'embedsMany' + embedsMany: 'embedsMany', }; var RelationClasses = { @@ -37,7 +37,7 @@ var RelationClasses = { hasAndBelongsToMany: HasAndBelongsToMany, referencesMany: ReferencesMany, embedsOne: EmbedsOne, - embedsMany: EmbedsMany + embedsMany: EmbedsMany, }; exports.Relation = Relation; @@ -136,7 +136,7 @@ function RelationDefinition(definition) { this.methods = definition.methods || {}; } -RelationDefinition.prototype.toJSON = function () { +RelationDefinition.prototype.toJSON = function() { var polymorphic = typeof this.polymorphic === 'object'; var modelToName = this.modelTo && this.modelTo.modelName; @@ -151,7 +151,7 @@ RelationDefinition.prototype.toJSON = function () { keyFrom: this.keyFrom, modelTo: modelToName, keyTo: this.keyTo, - multiple: this.multiple + multiple: this.multiple, }; if (this.modelThrough) { json.modelThrough = this.modelThrough.modelName; @@ -186,7 +186,7 @@ RelationDefinition.prototype.defineMethod = function(name, fn) { method = function() { var rel = this[relationName]; return rel[name].apply(rel, arguments); - } + }; } if (method && fn.shared) { sharedMethod(definition, name, method, fn); @@ -241,16 +241,16 @@ RelationDefinition.prototype.applyProperties = function(modelInstance, obj) { var k, key; if (typeof this.properties === 'function') { var data = this.properties.call(this, source, target); - for(k in data) { + for (k in data) { target[k] = data[k]; } } else if (Array.isArray(this.properties)) { - for(k = 0; k < this.properties.length; k++) { + for (k = 0; k < this.properties.length; k++) { key = this.properties[k]; target[key] = source[key]; } } else if (typeof this.properties === 'object') { - for(k in this.properties) { + for (k in this.properties) { key = this.properties[k]; target[key] = source[k]; } @@ -285,12 +285,12 @@ function Relation(definition, modelInstance) { this.modelInstance = modelInstance; } -Relation.prototype.resetCache = function (cache) { +Relation.prototype.resetCache = function(cache) { cache = cache || undefined; this.modelInstance.__cachedRelations[this.definition.name] = cache; }; -Relation.prototype.getCache = function () { +Relation.prototype.getCache = function() { return this.modelInstance.__cachedRelations[this.definition.name]; }; @@ -333,12 +333,12 @@ function HasMany(definition, modelInstance) { util.inherits(HasMany, Relation); -HasMany.prototype.removeFromCache = function (id) { +HasMany.prototype.removeFromCache = function(id) { var cache = this.modelInstance.__cachedRelations[this.definition.name]; var idName = this.definition.modelTo.definition.idName(); if (Array.isArray(cache)) { for (var i = 0, n = cache.length; i < n; i++) { - if (idEquals(cache[i][idName],id)) { + if (idEquals(cache[i][idName], id)) { return cache.splice(i, 1); } } @@ -346,7 +346,7 @@ HasMany.prototype.removeFromCache = function (id) { return null; }; -HasMany.prototype.addToCache = function (inst) { +HasMany.prototype.addToCache = function(inst) { if (!inst) { return; } @@ -357,7 +357,7 @@ HasMany.prototype.addToCache = function (inst) { var idName = this.definition.modelTo.definition.idName(); if (Array.isArray(cache)) { for (var i = 0, n = cache.length; i < n; i++) { - if (idEquals(cache[i][idName],inst[idName])) { + if (idEquals(cache[i][idName], inst[idName])) { cache[i] = inst; return; } @@ -518,7 +518,7 @@ function findBelongsTo(modelFrom, modelTo, keyTo) { * @returns {*} The matching model class */ function lookupModel(models, modelName) { - if(models[modelName]) { + if (models[modelName]) { return models[modelName]; } var lookupClassName = modelName.toLowerCase(); @@ -623,7 +623,7 @@ RelationDefinition.hasMany = function hasMany(modelFrom, modelTo, params) { scope: params.scope, options: params.options, keyThrough: keyThrough, - polymorphic: polymorphic + polymorphic: polymorphic, }); definition.modelThrough = params.through; @@ -641,7 +641,7 @@ RelationDefinition.hasMany = function hasMany(modelFrom, modelTo, params) { findById: scopeMethod(definition, 'findById'), destroy: scopeMethod(definition, 'destroyById'), updateById: scopeMethod(definition, 'updateById'), - exists: scopeMethod(definition, 'exists') + exists: scopeMethod(definition, 'exists'), }; var findByIdFunc = scopeMethods.findById; @@ -656,7 +656,7 @@ RelationDefinition.hasMany = function hasMany(modelFrom, modelTo, params) { var existsByIdFunc = scopeMethods.exists; modelFrom.prototype['__exists__' + relationName] = existsByIdFunc; - if(definition.modelThrough) { + if (definition.modelThrough) { scopeMethods.create = scopeMethod(definition, 'create'); scopeMethods.add = scopeMethod(definition, 'add'); scopeMethods.remove = scopeMethod(definition, 'remove'); @@ -682,7 +682,7 @@ RelationDefinition.hasMany = function hasMany(modelFrom, modelTo, params) { }; // Mix the property and scoped methods into the prototype class - defineScope(modelFrom.prototype, params.through || modelTo, relationName, function () { + defineScope(modelFrom.prototype, params.through || modelTo, relationName, function() { var filter = {}; filter.where = {}; filter.where[fk] = this[pkName]; @@ -693,7 +693,7 @@ RelationDefinition.hasMany = function hasMany(modelFrom, modelTo, params) { var throughRelationName; // find corresponding belongsTo relations from through model as collect - for(var r in definition.modelThrough.relations) { + for (var r in definition.modelThrough.relations) { var relation = definition.modelThrough.relations[r]; // should be a belongsTo and match modelTo and keyThrough @@ -727,7 +727,7 @@ function scopeMethod(definition, methodName) { if (definition.type === RelationTypes.hasMany && definition.modelThrough) { relationClass = RelationClasses.hasManyThrough; } - var method = function () { + var method = function() { var relation = new relationClass(definition, this); return relation[methodName].apply(relation, arguments); }; @@ -753,7 +753,7 @@ function sharedMethod(definition, methodName, method, relationMethod) { * @param {Object} [options] Options * @param {Function} cb The callback function */ -HasMany.prototype.findById = function (fkId, options, cb) { +HasMany.prototype.findById = function(fkId, options, cb) { if (typeof options === 'function' && cb === undefined) { cb = options; options = {}; @@ -779,7 +779,7 @@ HasMany.prototype.findById = function (fkId, options, cb) { } this.definition.applyScope(modelInstance, filter); - modelTo.findOne(filter, options, function (err, inst) { + modelTo.findOne(filter, options, function(err, inst) { if (err) { return cb(err); } @@ -808,7 +808,7 @@ HasMany.prototype.findById = function (fkId, options, cb) { * @param {Object} [options] Options * @param {Function} cb The callback function */ -HasMany.prototype.exists = function (fkId, options, cb) { +HasMany.prototype.exists = function(fkId, options, cb) { if (typeof options === 'function' && cb === undefined) { cb = options; options = {}; @@ -819,7 +819,7 @@ HasMany.prototype.exists = function (fkId, options, cb) { cb = cb || utils.createPromiseCallback(); - this.findById(fkId, function (err, inst) { + this.findById(fkId, function(err, inst) { if (err) { return cb(err); } @@ -843,13 +843,13 @@ HasMany.prototype.exists = function (fkId, options, cb) { * @param {Object} [options] Options * @param {Function} cb The callback function */ -HasMany.prototype.updateById = function (fkId, data, options, cb) { +HasMany.prototype.updateById = function(fkId, data, options, cb) { if (typeof options === 'function' && cb === undefined) { cb = options; options = {}; } cb = cb || utils.createPromiseCallback(); - this.findById(fkId, options, function (err, inst) { + this.findById(fkId, options, function(err, inst) { if (err) { return cb && cb(err); } @@ -864,7 +864,7 @@ HasMany.prototype.updateById = function (fkId, data, options, cb) { * @param {Object} [options] Options * @param {Function} cb The callback function */ -HasMany.prototype.destroyById = function (fkId, options, cb) { +HasMany.prototype.destroyById = function(fkId, options, cb) { if (typeof options === 'function' && cb === undefined) { cb = options; options = {}; @@ -894,7 +894,7 @@ var throughKeys = function(definition) { } } else if (definition.modelFrom === definition.modelTo) { return findBelongsTo(modelThrough, definition.modelTo, pk2). - sort(function (fk1, fk2) { + sort(function(fk1, fk2) { //Fix for bug - https://github.com/strongloop/loopback-datasource-juggler/issues/571 //Make sure that first key is mapped to modelFrom //& second key to modelTo. Order matters @@ -906,7 +906,7 @@ var throughKeys = function(definition) { var fk2 = findBelongsTo(modelThrough, definition.modelTo, pk2)[0]; } return [fk1, fk2]; -} +}; /** * Find a related item by foreign key @@ -914,7 +914,7 @@ var throughKeys = function(definition) { * @param {Object} [options] Options * @param {Function} cb The callback function */ -HasManyThrough.prototype.findById = function (fkId, options, cb) { +HasManyThrough.prototype.findById = function(fkId, options, cb) { if (typeof options === 'function' && cb === undefined) { cb = options; options = {}; @@ -927,7 +927,7 @@ HasManyThrough.prototype.findById = function (fkId, options, cb) { cb = cb || utils.createPromiseCallback(); - self.exists(fkId, options, function (err, exists) { + self.exists(fkId, options, function(err, exists) { if (err || !exists) { if (!err) { err = new Error('No relation found in ' + modelThrough.modelName @@ -937,7 +937,7 @@ HasManyThrough.prototype.findById = function (fkId, options, cb) { } return cb(err); } - modelTo.findById(fkId, options, function (err, inst) { + modelTo.findById(fkId, options, function(err, inst) { if (err) { return cb(err); } @@ -958,7 +958,7 @@ HasManyThrough.prototype.findById = function (fkId, options, cb) { * @param {Object} [options] Options * @param {Function} cb The callback function */ -HasManyThrough.prototype.destroyById = function (fkId, options, cb) { +HasManyThrough.prototype.destroyById = function(fkId, options, cb) { if (typeof options === 'function' && cb === undefined) { cb = options; options = {}; @@ -971,7 +971,7 @@ HasManyThrough.prototype.destroyById = function (fkId, options, cb) { cb = cb || utils.createPromiseCallback(); - self.exists(fkId, options, function (err, exists) { + self.exists(fkId, options, function(err, exists) { if (err || !exists) { if (!err) { err = new Error('No record found in ' + modelThrough.modelName @@ -982,7 +982,7 @@ HasManyThrough.prototype.destroyById = function (fkId, options, cb) { return cb(err); } self.remove(fkId, options, function(err) { - if(err) { + if (err) { return cb(err); } modelTo.deleteById(fkId, options, cb); @@ -1012,7 +1012,7 @@ HasManyThrough.prototype.create = function create(data, options, cb) { var modelInstance = this.modelInstance; // First create the target model - modelTo.create(data, options, function (err, to) { + modelTo.create(data, options, function(err, to) { if (err) { return cb(err, to); } @@ -1023,17 +1023,17 @@ 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); definition.applyScope(modelInstance, filter); // Then create the through model - modelThrough.findOrCreate(filter, d, options, function (e, through) { + modelThrough.findOrCreate(filter, d, options, function(e, through) { if (e) { // Undo creation of the target model - to.destroy(options, function () { + to.destroy(options, function() { next(e); }); } else { @@ -1061,7 +1061,7 @@ HasManyThrough.prototype.create = function create(data, options, cb) { * @param {Object} [options] Options * @param {Function} [cb] Callback function */ -HasManyThrough.prototype.add = function (acInst, data, options, cb) { +HasManyThrough.prototype.add = function(acInst, data, options, cb) { if (typeof options === 'function' && cb === undefined) { cb = options; options = {}; @@ -1101,7 +1101,7 @@ HasManyThrough.prototype.add = function (acInst, data, options, cb) { // Create an instance of the through model modelThrough.findOrCreate(filter, data, options, function(err, ac) { - if(!err) { + if (!err) { if (acInst instanceof definition.modelTo) { self.addToCache(acInst); } @@ -1115,7 +1115,7 @@ HasManyThrough.prototype.add = function (acInst, data, options, cb) { * Check if the target model instance is related to the 'hasMany' relation * @param {Object|ID} acInst The actual instance or id value */ -HasManyThrough.prototype.exists = function (acInst, options, cb) { +HasManyThrough.prototype.exists = function(acInst, options, cb) { if (typeof options === 'function' && cb === undefined) { cb = options; options = {}; @@ -1152,7 +1152,7 @@ HasManyThrough.prototype.exists = function (acInst, options, cb) { * Remove the target model instance from the 'hasMany' relation * @param {Object|ID) acInst The actual instance or id value */ -HasManyThrough.prototype.remove = function (acInst, options, cb) { +HasManyThrough.prototype.remove = function(acInst, options, cb) { if (typeof options === 'function' && cb === undefined) { cb = options; options = {}; @@ -1180,7 +1180,7 @@ HasManyThrough.prototype.remove = function (acInst, options, cb) { cb = cb || utils.createPromiseCallback(); - modelThrough.deleteAll(filter.where, options, function (err) { + modelThrough.deleteAll(filter.where, options, function(err) { if (!err) { self.removeFromCache(query[fk2]); } @@ -1214,7 +1214,7 @@ HasManyThrough.prototype.remove = function (acInst, options, cb) { * @property {String} foreignKey Name of foreign key property. * */ -RelationDefinition.belongsTo = function (modelFrom, modelTo, params) { +RelationDefinition.belongsTo = function(modelFrom, modelTo, params) { var discriminator, polymorphic; params = params || {}; if ('string' === typeof modelTo && !params.polymorphic) { @@ -1266,7 +1266,7 @@ RelationDefinition.belongsTo = function (modelFrom, modelTo, params) { scope: params.scope, options: params.options, polymorphic: polymorphic, - methods: params.methods + methods: params.methods, }); // Define a property for the scope so that we have 'this' for the scoped methods @@ -1286,7 +1286,7 @@ RelationDefinition.belongsTo = function (modelFrom, modelTo, params) { } bindRelationMethods(relation, relationMethod, definition); return relationMethod; - } + }, }); // FIXME: [rfeng] Wrap the property into a function for remoting @@ -1321,7 +1321,7 @@ BelongsTo.prototype.create = function(targetModelData, options, cb) { this.definition.applyProperties(modelInstance, targetModelData || {}); modelTo.create(targetModelData, options, function(err, targetModel) { - if(!err) { + if (!err) { modelInstance[fk] = targetModel[pk]; if (modelInstance.isNewRecord()) { self.resetCache(targetModel); @@ -1346,7 +1346,7 @@ BelongsTo.prototype.build = function(targetModelData) { return new modelTo(targetModelData); }; -BelongsTo.prototype.update = function (targetModelData, options, cb) { +BelongsTo.prototype.update = function(targetModelData, options, cb) { if (typeof options === 'function' && cb === undefined) { cb = options; options = {}; @@ -1364,7 +1364,7 @@ BelongsTo.prototype.update = function (targetModelData, options, cb) { return cb.promise; }; -BelongsTo.prototype.destroy = function (options, cb) { +BelongsTo.prototype.destroy = function(options, cb) { if (typeof options === 'function' && cb === undefined) { cb = options; options = {}; @@ -1401,7 +1401,7 @@ BelongsTo.prototype.destroy = function (options, cb) { * @param params * @returns {*} */ -BelongsTo.prototype.related = function (condOrRefresh, options, cb) { +BelongsTo.prototype.related = function(condOrRefresh, options, cb) { var self = this; var modelFrom = this.definition.modelFrom; var modelTo = this.definition.modelTo; @@ -1464,7 +1464,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 @@ -1478,10 +1478,10 @@ BelongsTo.prototype.related = function (condOrRefresh, options, cb) { if (scopeQuery) mergeQuery(query, scopeQuery); if (Array.isArray(query.fields) && query.fields.indexOf(pk) === -1) { - query.fields.push(pk); // always include the pk + query.fields.push(pk); // always include the pk } - modelTo.findOne(query, options, function (err, inst) { + modelTo.findOne(query, options, function(err, inst) { if (err) { return cb(err); } @@ -1522,7 +1522,7 @@ BelongsTo.prototype.related = function (condOrRefresh, options, cb) { * @param {Function} cb Callback of the form function (err, inst) * @returns {Promise | Undefined} returns promise if callback is omitted */ -BelongsTo.prototype.getAsync = function (options, cb) { +BelongsTo.prototype.getAsync = function(options, cb) { if (typeof options === 'function' && cb === undefined) { // order.customer.getAsync(cb) cb = options; @@ -1531,7 +1531,7 @@ BelongsTo.prototype.getAsync = function (options, cb) { cb = cb || utils.createPromiseCallback(); this.related(true, options, cb); return cb.promise; -} +}; /** @@ -1565,7 +1565,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; @@ -1601,7 +1601,7 @@ RelationDefinition.hasAndBelongsToMany = function hasAndBelongsToMany(modelFrom, * @property {String} foreignKey Property name of foreign key field. * @property {Object} model Model object */ -RelationDefinition.hasOne = function (modelFrom, modelTo, params) { +RelationDefinition.hasOne = function(modelFrom, modelTo, params) { params = params || {}; modelTo = lookupModelTo(modelFrom, modelTo, params); @@ -1632,7 +1632,7 @@ RelationDefinition.hasOne = function (modelFrom, modelTo, params) { scope: params.scope, options: params.options, polymorphic: polymorphic, - methods: params.methods + methods: params.methods, }); modelTo.dataSource.defineForeignKey(modelTo.modelName, fk, modelFrom.modelName, pk); @@ -1643,7 +1643,7 @@ RelationDefinition.hasOne = function (modelFrom, modelTo, params) { configurable: true, get: function() { var relation = new HasOne(definition, this); - var relationMethod = relation.related.bind(relation) + var relationMethod = relation.related.bind(relation); relationMethod.getAsync = relation.getAsync.bind(relation); relationMethod.create = relation.create.bind(relation); relationMethod.build = relation.build.bind(relation); @@ -1652,7 +1652,7 @@ RelationDefinition.hasOne = function (modelFrom, modelTo, params) { relationMethod._targetClass = definition.modelTo.modelName; bindRelationMethods(relation, relationMethod, definition); return relationMethod; - } + }, }); // FIXME: [rfeng] Wrap the property into a function for remoting @@ -1688,7 +1688,7 @@ RelationDefinition.hasOne = function (modelFrom, modelTo, params) { * @param {String|Object} err Error string or object * @param {Object} The newly created target model instance */ -HasOne.prototype.create = function (targetModelData, options, cb) { +HasOne.prototype.create = function(targetModelData, options, cb) { if (typeof options === 'function' && cb === undefined) { // customer.profile.create(options, cb) cb = options; @@ -1708,7 +1708,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); @@ -1752,7 +1752,7 @@ HasOne.prototype.update = function(targetModelData, options, cb) { return cb.promise; }; -HasOne.prototype.destroy = function (options, cb) { +HasOne.prototype.destroy = function(options, cb) { if (typeof options === 'function' && cb === undefined) { // customer.profile.destroy(cb) cb = options; @@ -1778,7 +1778,7 @@ HasOne.prototype.destroy = function (options, cb) { * @param {String|Object} err Error string or object * @param {Object} The newly created target model instance */ -HasMany.prototype.create = function (targetModelData, options, cb) { +HasMany.prototype.create = function(targetModelData, options, cb) { if (typeof options === 'function' && cb === undefined) { // customer.orders.create(data, cb) cb = options; @@ -1813,7 +1813,7 @@ HasMany.prototype.create = function (targetModelData, options, cb) { apply(targetModelData, fkAndProps); modelTo.create(targetModelData, options, function(err, targetModel) { - if(!err) { + if (!err) { //Refresh the cache apply(targetModel, self.addToCache.bind(self)); cb && cb(err, targetModel); @@ -1852,7 +1852,7 @@ HasMany.prototype.build = HasOne.prototype.build = function(targetModelData) { * @param {Object|Function} params Query parameters * @returns {Object} */ -HasOne.prototype.related = function (condOrRefresh, options, cb) { +HasOne.prototype.related = function(condOrRefresh, options, cb) { var self = this; var modelTo = this.definition.modelTo; var fk = this.definition.keyTo; @@ -1886,10 +1886,10 @@ 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) { + modelTo.findOne(query, options, function(err, inst) { if (err) { return cb(err); } @@ -1930,7 +1930,7 @@ HasOne.prototype.related = function (condOrRefresh, options, cb) { * @returns {Promise | Undefined} Returns promise if cb is omitted */ -HasOne.prototype.getAsync = function (options, cb) { +HasOne.prototype.getAsync = function(options, cb) { if (typeof options === 'function' && cb === undefined) { // order.profile.getAsync(cb) cb = options; @@ -1941,7 +1941,7 @@ HasOne.prototype.getAsync = function (options, cb) { return cb.promise; }; -RelationDefinition.embedsOne = function (modelFrom, modelTo, params) { +RelationDefinition.embedsOne = function(modelFrom, modelTo, params) { params = params || {}; modelTo = lookupModelTo(modelFrom, modelTo, params); @@ -1968,7 +1968,7 @@ RelationDefinition.embedsOne = function (modelFrom, modelTo, params) { scope: params.scope, options: params.options, embed: true, - methods: params.methods + methods: params.methods, }); var opts = { type: modelTo }; @@ -2015,7 +2015,7 @@ RelationDefinition.embedsOne = function (modelFrom, modelTo, params) { relationMethod._targetClass = definition.modelTo.modelName; bindRelationMethods(relation, relationMethod, definition); return relationMethod; - } + }, }); // FIXME: [rfeng] Wrap the property into a function for remoting @@ -2044,7 +2044,7 @@ RelationDefinition.embedsOne = function (modelFrom, modelTo, params) { return definition; }; -EmbedsOne.prototype.related = function (condOrRefresh, options, cb) { +EmbedsOne.prototype.related = function(condOrRefresh, options, cb) { var modelTo = this.definition.modelTo; var modelInstance = this.modelInstance; var propertyName = this.definition.keyFrom; @@ -2094,7 +2094,7 @@ EmbedsOne.prototype.embeddedValue = function(modelInstance) { return modelInstance[this.definition.keyFrom]; }; -EmbedsOne.prototype.create = function (targetModelData, options, cb) { +EmbedsOne.prototype.create = function(targetModelData, options, cb) { if (typeof options === 'function' && cb === undefined) { // order.customer.create(data, cb) cb = options; @@ -2118,13 +2118,13 @@ EmbedsOne.prototype.create = function (targetModelData, options, cb) { if (modelInstance.isNewRecord()) { modelInstance.setAttribute(propertyName, inst); modelInstance.save(options, function(err) { - cb(err, err ? null : inst); + cb(err, err ? null : inst); }); } else { modelInstance.updateAttribute(propertyName, inst, options, function(err) { - cb(err, err ? null : inst); - }); + cb(err, err ? null : inst); + }); } }; @@ -2146,7 +2146,7 @@ EmbedsOne.prototype.create = function (targetModelData, options, cb) { return cb.promise; }; -EmbedsOne.prototype.build = function (targetModelData) { +EmbedsOne.prototype.build = function(targetModelData) { var modelTo = this.definition.modelTo; var modelInstance = this.modelInstance; var propertyName = this.definition.keyFrom; @@ -2165,8 +2165,8 @@ EmbedsOne.prototype.build = function (targetModelData) { assignId = assignId && !persistent && (pkProp && pkProp.generated); if (assignId && typeof connector.generateId === 'function') { - var id = connector.generateId(modelTo.modelName, targetModelData, pk); - targetModelData[pk] = id; + var id = connector.generateId(modelTo.modelName, targetModelData, pk); + targetModelData[pk] = id; } var embeddedInstance = new modelTo(targetModelData); @@ -2175,7 +2175,7 @@ EmbedsOne.prototype.build = function (targetModelData) { return embeddedInstance; }; -EmbedsOne.prototype.update = function (targetModelData, options, cb) { +EmbedsOne.prototype.update = function(targetModelData, options, cb) { if (typeof options === 'function' && cb === undefined) { // order.customer.update(data, cb) cb = options; @@ -2205,7 +2205,7 @@ EmbedsOne.prototype.update = function (targetModelData, options, cb) { return cb.promise; }; -EmbedsOne.prototype.destroy = function (options, cb) { +EmbedsOne.prototype.destroy = function(options, cb) { if (typeof options === 'function' && cb === undefined) { // order.customer.destroy(cb) cb = options; @@ -2215,7 +2215,7 @@ EmbedsOne.prototype.destroy = function (options, cb) { var propertyName = this.definition.keyFrom; modelInstance.unsetAttribute(propertyName, true); cb = cb || utils.createPromiseCallback(); - modelInstance.save(function (err, result) { + modelInstance.save(function(err, result) { cb && cb(err, result); }); return cb.promise; @@ -2247,11 +2247,11 @@ RelationDefinition.embedsMany = function embedsMany(modelFrom, modelTo, params) properties: params.properties, scope: params.scope, options: params.options, - embed: true + embed: true, }); modelFrom.dataSource.defineProperty(modelFrom.modelName, propertyName, { - type: [modelTo], default: function() { return []; } + type: [modelTo], default: function() { return []; }, }); if (typeof modelTo.dataSource.connector.generateId !== 'function') { @@ -2276,13 +2276,13 @@ RelationDefinition.embedsMany = function embedsMany(modelFrom, modelTo, params) var embeddedList = this[propertyName] || []; var ids = embeddedList.map(function(m) { return m[idName] && m[idName].toString(); }); // mongodb var uniqueIds = ids.filter(function(id, pos) { - return utils.findIndexOf(ids, id, idEquals) === pos; + return utils.findIndexOf(ids, id, idEquals) === pos; }); if (ids.length !== uniqueIds.length) { this.errors.add(propertyName, 'contains duplicate `' + idName + '`', 'uniqueness'); err(false); } - }, { code: 'uniqueness' }) + }, { code: 'uniqueness' }); } // validate all embedded items @@ -2325,7 +2325,7 @@ RelationDefinition.embedsMany = function embedsMany(modelFrom, modelTo, params) set: scopeMethod(definition, 'set'), unset: scopeMethod(definition, 'unset'), at: scopeMethod(definition, 'at'), - value: scopeMethod(definition, 'embeddedValue') + value: scopeMethod(definition, 'embeddedValue'), }; var findByIdFunc = scopeMethods.findById; @@ -2363,7 +2363,7 @@ RelationDefinition.embedsMany = function embedsMany(modelFrom, modelTo, params) }; // Mix the property and scoped methods into the prototype class - var scopeDefinition = defineScope(modelFrom.prototype, modelTo, relationName, function () { + var scopeDefinition = defineScope(modelFrom.prototype, modelTo, relationName, function() { return {}; }, scopeMethods, definition.options); @@ -2378,10 +2378,10 @@ EmbedsMany.prototype.prepareEmbeddedInstance = function(inst) { var propertyName = this.definition.keyFrom; var modelInstance = this.modelInstance; if (this.definition.options.persistent) { - var pk = this.definition.keyTo; - inst.__persisted = !!inst[pk]; + var pk = this.definition.keyTo; + inst.__persisted = !!inst[pk]; } else { - inst.__persisted = true; + inst.__persisted = true; } inst.triggerParent = function(actionName, callback) { if (actionName === 'save' || actionName === 'destroy') { @@ -2392,8 +2392,8 @@ EmbedsMany.prototype.prepareEmbeddedInstance = function(inst) { } modelInstance.updateAttribute(propertyName, embeddedList, function(err, modelInst) { - callback(err, err ? null : modelInst); - }); + callback(err, err ? null : modelInst); + }); } else { process.nextTick(callback); } @@ -2417,11 +2417,11 @@ EmbedsMany.prototype.prepareEmbeddedInstance = function(inst) { EmbedsMany.prototype.embeddedList = EmbedsMany.prototype.embeddedValue = function(modelInstance) { - modelInstance = modelInstance || this.modelInstance; - var embeddedList = modelInstance[this.definition.keyFrom] || []; - embeddedList.forEach(this.prepareEmbeddedInstance.bind(this)); - return embeddedList; -}; + modelInstance = modelInstance || this.modelInstance; + var embeddedList = modelInstance[this.definition.keyFrom] || []; + embeddedList.forEach(this.prepareEmbeddedInstance.bind(this)); + return embeddedList; + }; EmbedsMany.prototype.related = function(receiver, scopeParams, condOrRefresh, options, cb) { var modelTo = this.definition.modelTo; @@ -2466,7 +2466,7 @@ EmbedsMany.prototype.related = function(receiver, scopeParams, condOrRefresh, op returnRelated(embeddedList); }; -EmbedsMany.prototype.findById = function (fkId, options, cb) { +EmbedsMany.prototype.findById = function(fkId, options, cb) { if (typeof options === 'function' && cb === undefined) { // order.emails(fkId, cb) cb = options; @@ -2481,7 +2481,7 @@ EmbedsMany.prototype.findById = function (fkId, options, cb) { var find = function(id) { for (var i = 0; i < embeddedList.length; i++) { var item = embeddedList[i]; - if (idEquals(item[pk],id)) return item; + if (idEquals(item[pk], id)) return item; } return null; }; @@ -2498,20 +2498,20 @@ EmbedsMany.prototype.findById = function (fkId, options, cb) { return item; // sync }; -EmbedsMany.prototype.exists = function (fkId, options, cb) { +EmbedsMany.prototype.exists = function(fkId, options, cb) { if (typeof options === 'function' && cb === undefined) { // customer.emails.exists(fkId, cb) cb = options; options = {}; } var modelTo = this.definition.modelTo; - var inst = this.findById(fkId, options, function (err, inst) { + var inst = this.findById(fkId, options, function(err, inst) { if (cb) cb(err, inst instanceof modelTo); }); return inst instanceof modelTo; // sync }; -EmbedsMany.prototype.updateById = function (fkId, data, options, cb) { +EmbedsMany.prototype.updateById = function(fkId, data, options, cb) { if (typeof options === 'function' && cb === undefined) { // customer.emails.updateById(fkId, data, cb) cb = options; @@ -2533,7 +2533,7 @@ EmbedsMany.prototype.updateById = function (fkId, data, options, cb) { if (inst instanceof modelTo) { if (typeof data === 'object') { - inst.setAttributes(data); + inst.setAttributes(data); } var err = inst.isValid() ? null : new ValidationError(inst); if (err && typeof cb === 'function') { @@ -2545,8 +2545,8 @@ EmbedsMany.prototype.updateById = function (fkId, data, options, cb) { if (typeof cb === 'function') { modelInstance.updateAttribute(propertyName, embeddedList, options, function(err) { - cb(err, inst); - }); + cb(err, inst); + }); } } else if (typeof cb === 'function') { process.nextTick(function() { @@ -2556,7 +2556,7 @@ EmbedsMany.prototype.updateById = function (fkId, data, options, cb) { return inst; // sync }; -EmbedsMany.prototype.destroyById = function (fkId, options, cb) { +EmbedsMany.prototype.destroyById = function(fkId, options, cb) { if (typeof options === 'function' && cb === undefined) { // customer.emails.destroyById(fkId, cb) cb = options; @@ -2576,9 +2576,9 @@ EmbedsMany.prototype.destroyById = function (fkId, options, cb) { if (typeof cb === 'function') { modelInstance.updateAttribute(propertyName, embeddedList, function(err) { - cb(err); - modelTo.emit('deleted', inst.id, inst.toJSON()); - }); + cb(err); + modelTo.emit('deleted', inst.id, inst.toJSON()); + }); } } else if (typeof cb === 'function') { process.nextTick(cb); // not found @@ -2604,7 +2604,7 @@ EmbedsMany.prototype.destroyAll = function(where, options, cb) { if (where && Object.keys(where).length > 0) { var filter = applyFilter({ where: where }); - var reject = function(v) { return !filter(v) }; + var reject = function(v) { return !filter(v); }; embeddedList = embeddedList ? embeddedList.filter(reject) : embeddedList; } else { embeddedList = []; @@ -2613,8 +2613,8 @@ EmbedsMany.prototype.destroyAll = function(where, options, cb) { if (typeof cb === 'function') { modelInstance.updateAttribute(propertyName, embeddedList, function(err) { - cb(err); - }); + cb(err); + }); } else { modelInstance.setAttribute(propertyName, embeddedList); } @@ -2624,7 +2624,7 @@ EmbedsMany.prototype.get = EmbedsMany.prototype.findById; EmbedsMany.prototype.set = EmbedsMany.prototype.updateById; EmbedsMany.prototype.unset = EmbedsMany.prototype.destroyById; -EmbedsMany.prototype.at = function (index, cb) { +EmbedsMany.prototype.at = function(index, cb) { var modelTo = this.definition.modelTo; var modelInstance = this.modelInstance; @@ -2642,7 +2642,7 @@ EmbedsMany.prototype.at = function (index, cb) { return item; // sync }; -EmbedsMany.prototype.create = function (targetModelData, options, cb) { +EmbedsMany.prototype.create = function(targetModelData, options, cb) { var pk = this.definition.keyTo; var modelTo = this.definition.modelTo; var propertyName = this.definition.keyFrom; @@ -2669,13 +2669,13 @@ EmbedsMany.prototype.create = function (targetModelData, options, cb) { if (modelInstance.isNewRecord()) { modelInstance.setAttribute(propertyName, embeddedList); modelInstance.save(options, function(err) { - cb(err, err ? null : inst); + cb(err, err ? null : inst); }); } else { modelInstance.updateAttribute(propertyName, embeddedList, options, function(err) { - cb(err, err ? null : inst); - }); + cb(err, err ? null : inst); + }); } }; @@ -2725,8 +2725,8 @@ EmbedsMany.prototype.build = function(targetModelData) { targetModelData[pk] = 1; } } else if (assignId && typeof connector.generateId === 'function') { - var id = connector.generateId(modelTo.modelName, targetModelData, pk); - targetModelData[pk] = id; + var id = connector.generateId(modelTo.modelName, targetModelData, pk); + targetModelData[pk] = id; } this.definition.applyProperties(modelInstance, targetModelData); @@ -2748,7 +2748,7 @@ EmbedsMany.prototype.build = function(targetModelData) { * Add the target model instance to the 'embedsMany' relation * @param {Object|ID} acInst The actual instance or id value */ -EmbedsMany.prototype.add = function (acInst, data, options, cb) { +EmbedsMany.prototype.add = function(acInst, data, options, cb) { if (typeof options === 'function' && cb === undefined) { // customer.emails.add(acInst, data, cb) cb = options; @@ -2802,7 +2802,7 @@ EmbedsMany.prototype.add = function (acInst, data, options, cb) { * Remove the target model instance from the 'embedsMany' relation * @param {Object|ID) acInst The actual instance or id value */ -EmbedsMany.prototype.remove = function (acInst, options, cb) { +EmbedsMany.prototype.remove = function(acInst, options, cb) { if (typeof options === 'function' && cb === undefined) { // customer.emails.remove(acInst, cb) cb = options; @@ -2867,24 +2867,24 @@ RelationDefinition.referencesMany = function referencesMany(modelFrom, modelTo, multiple: true, properties: params.properties, scope: params.scope, - options: params.options + options: params.options, }); modelFrom.dataSource.defineProperty(modelFrom.modelName, fk, { - type: [idType], default: function() { return []; } + type: [idType], default: function() { return []; }, }); modelFrom.validate(relationName, function(err) { var ids = this[fk] || []; var uniqueIds = ids.filter(function(id, pos) { - return utils.findIndexOf(ids, id, idEquals) === pos; + return utils.findIndexOf(ids, id, idEquals) === pos; }); if (ids.length !== uniqueIds.length) { var msg = 'contains duplicate `' + modelTo.modelName + '` instance'; this.errors.add(relationName, msg, 'uniqueness'); err(false); } - }, { code: 'uniqueness' }) + }, { code: 'uniqueness' }); var scopeMethods = { findById: scopeMethod(definition, 'findById'), @@ -2893,7 +2893,7 @@ RelationDefinition.referencesMany = function referencesMany(modelFrom, modelTo, exists: scopeMethod(definition, 'exists'), add: scopeMethod(definition, 'add'), remove: scopeMethod(definition, 'remove'), - at: scopeMethod(definition, 'at') + at: scopeMethod(definition, 'at'), }; var findByIdFunc = scopeMethods.findById; @@ -2927,7 +2927,7 @@ RelationDefinition.referencesMany = function referencesMany(modelFrom, modelTo, }; // Mix the property and scoped methods into the prototype class - var scopeDefinition = defineScope(modelFrom.prototype, modelTo, relationName, function () { + var scopeDefinition = defineScope(modelFrom.prototype, modelTo, relationName, function() { return {}; }, scopeMethods, definition.options); @@ -2972,7 +2972,7 @@ ReferencesMany.prototype.related = function(receiver, scopeParams, condOrRefresh return modelTo.findByIds(ids, params, options, cb); }; -ReferencesMany.prototype.findById = function (fkId, options, cb) { +ReferencesMany.prototype.findById = function(fkId, options, cb) { if (typeof options === 'function' && cb === undefined) { // customer.orders.findById(fkId, cb) cb = options; @@ -2998,7 +2998,7 @@ ReferencesMany.prototype.findById = function (fkId, options, cb) { cb = cb || utils.createPromiseCallback(); - modelTo.findByIds([fkId], filter, options, function (err, instances) { + modelTo.findByIds([fkId], filter, options, function(err, instances) { if (err) { return cb(err); } @@ -3024,7 +3024,7 @@ ReferencesMany.prototype.findById = function (fkId, options, cb) { return cb.promise; }; -ReferencesMany.prototype.exists = function (fkId, options, cb) { +ReferencesMany.prototype.exists = function(fkId, options, cb) { if (typeof options === 'function' && cb === undefined) { // customer.orders.exists(fkId, cb) cb = options; @@ -3034,11 +3034,11 @@ ReferencesMany.prototype.exists = function (fkId, options, cb) { var ids = this.modelInstance[fk] || []; cb = cb || utils.createPromiseCallback(); - process.nextTick(function() { cb(null, utils.findIndexOf(ids, fkId, idEquals) > -1) }); + process.nextTick(function() { cb(null, utils.findIndexOf(ids, fkId, idEquals) > -1); }); return cb.promise; }; -ReferencesMany.prototype.updateById = function (fkId, data, options, cb) { +ReferencesMany.prototype.updateById = function(fkId, data, options, cb) { if (typeof options === 'function' && cb === undefined) { // customer.orders.updateById(fkId, data, cb) cb = options; @@ -3058,7 +3058,7 @@ ReferencesMany.prototype.updateById = function (fkId, data, options, cb) { return cb.promise; }; -ReferencesMany.prototype.destroyById = function (fkId, options, cb) { +ReferencesMany.prototype.destroyById = function(fkId, options, cb) { if (typeof options === 'function' && cb === undefined) { // customer.orders.destroyById(fkId, cb) cb = options; @@ -3075,7 +3075,7 @@ ReferencesMany.prototype.destroyById = function (fkId, options, cb) { return cb.promise; }; -ReferencesMany.prototype.at = function (index, options, cb) { +ReferencesMany.prototype.at = function(index, options, cb) { if (typeof options === 'function' && cb === undefined) { // customer.orders.at(index, cb) cb = options; @@ -3088,7 +3088,7 @@ ReferencesMany.prototype.at = function (index, options, cb) { return cb.promise; }; -ReferencesMany.prototype.create = function (targetModelData, options, cb) { +ReferencesMany.prototype.create = function(targetModelData, options, cb) { if (typeof options === 'function' && cb === undefined) { // customer.orders.create(data, cb) cb = options; @@ -3130,8 +3130,8 @@ ReferencesMany.prototype.create = function (targetModelData, options, cb) { modelInstance.updateAttribute(fk, ids, options, function(err, modelInst) { - cb(err, inst); - }); + cb(err, inst); + }); }); return cb.promise; }; @@ -3149,7 +3149,7 @@ ReferencesMany.prototype.build = function(targetModelData) { * Add the target model instance to the 'embedsMany' relation * @param {Object|ID} acInst The actual instance or id value */ -ReferencesMany.prototype.add = function (acInst, options, cb) { +ReferencesMany.prototype.add = function(acInst, options, cb) { if (typeof options === 'function' && cb === undefined) { // customer.orders.add(acInst, cb) cb = options; @@ -3188,12 +3188,12 @@ 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); - modelTo.findOne(filter, options, function (err, inst) { + modelTo.findOne(filter, options, function(err, inst) { if (err || !inst) return cb(err, null); insert(inst, cb); }); @@ -3205,7 +3205,7 @@ ReferencesMany.prototype.add = function (acInst, options, cb) { * Remove the target model instance from the 'embedsMany' relation * @param {Object|ID) acInst The actual instance or id value */ -ReferencesMany.prototype.remove = function (acInst, options, cb) { +ReferencesMany.prototype.remove = function(acInst, options, cb) { if (typeof options === 'function' && cb === undefined) { // customer.orders.remove(acInst, cb) cb = options; diff --git a/lib/relations.js b/lib/relations.js index 5dd9994d..b4a2c8b5 100644 --- a/lib/relations.js +++ b/lib/relations.js @@ -21,12 +21,12 @@ function RelationMixin() { /** * Define a "one to many" relationship by specifying the model name - * + * * Examples: * ``` * User.hasMany(Post, {as: 'posts', foreignKey: 'authorId'}); * ``` - * + * * ``` * Book.hasMany(Chapter); * ``` @@ -39,24 +39,24 @@ function RelationMixin() { * * ```js * Book.create(function(err, book) { - * + * * // Create a chapter instance ready to be saved in the data source. * var chapter = book.chapters.build({name: 'Chapter 1'}); - * + * * // Save the new chapter * chapter.save(); - * + * * // you can also call the Chapter.create method with the `chapters` property which will build a chapter * // instance and save the it in the data source. * book.chapters.create({name: 'Chapter 2'}, function(err, savedChapter) { * // this callback is optional * }); - * - * // Query chapters for the book - * book.chapters(function(err, chapters) { // all chapters with bookId = book.id + * + * // Query chapters for the book + * book.chapters(function(err, chapters) { // all chapters with bookId = book.id * console.log(chapters); * }); - * + * * book.chapters({where: {name: 'test'}, function(err, chapters) { * // All chapters with bookId = book.id and name = 'test' * console.log(chapters); @@ -94,10 +94,10 @@ RelationMixin.hasMany = function hasMany(modelTo, params) { * ``` * Set the author to be the given user: * ``` - * post.author(user) + * post.author(user) * ``` * Examples: - * + * * Suppose the model Post has a *belongsTo* relationship with User (the author of the post). You could declare it this way: * ```js * Post.belongsTo(User, {as: 'author', foreignKey: 'userId'}); @@ -123,9 +123,9 @@ RelationMixin.hasMany = function hasMany(modelTo, params) { * @options {Object} params Configuration parameters; see below. * @property {String} as Name of the property in the referring model that corresponds to the foreign key field in the related model. * @property {String} foreignKey Name of foreign key property. - * + * */ -RelationMixin.belongsTo = function (modelTo, params) { +RelationMixin.belongsTo = function(modelTo, params) { return RelationDefinition.belongsTo(this, modelTo, params); }; @@ -150,9 +150,9 @@ RelationMixin.belongsTo = function (modelTo, params) { * ``` * Remove the user from the group: * ``` - * user.groups.remove(group, callback); + * user.groups.remove(group, callback); * ``` - * + * * @param {String|Object} modelTo Model object (or String name of model) to which you are creating the relationship. * the relation * @options {Object} params Configuration parameters; see below. diff --git a/lib/scope.js b/lib/scope.js index fb361735..59941da0 100644 --- a/lib/scope.js +++ b/lib/scope.js @@ -83,9 +83,9 @@ ScopeDefinition.prototype.related = function(receiver, scopeParams, condOrRefres if (!self.__cachedRelations || self.__cachedRelations[name] === undefined || actualRefresh) { // It either doesn't hit the cache or refresh is required - var params = mergeQuery(actualCond, scopeParams, {nestedInclude: true}); + var params = mergeQuery(actualCond, scopeParams, { nestedInclude: true }); var targetModel = this.targetModel(receiver); - targetModel.find(params, options, function (err, data) { + targetModel.find(params, options, function(err, data) { if (!err && saveOnCache) { defineCachedRelations(self); self.__cachedRelations[name] = data; @@ -97,7 +97,7 @@ ScopeDefinition.prototype.related = function(receiver, scopeParams, condOrRefres cb(null, self.__cachedRelations[name]); } return cb.promise; -} +}; /** * Define a scope method @@ -106,7 +106,7 @@ ScopeDefinition.prototype.related = function(receiver, scopeParams, condOrRefres */ ScopeDefinition.prototype.defineMethod = function(name, fn) { return this.methods[name] = fn; -} +}; /** * Define a scope to the class @@ -143,10 +143,10 @@ function defineScope(cls, targetClass, name, params, methods, options) { name: name, params: params, methods: methods, - options: options + options: options, }); - if(isStatic) { + if (isStatic) { cls.scopes = cls.scopes || {}; cls.scopes[name] = definition; } else { @@ -169,7 +169,7 @@ function defineScope(cls, targetClass, name, params, methods, options) { * user.accounts.create(act, cb). * */ - get: function () { + get: function() { var targetModel = definition.targetModel(this); var self = this; @@ -192,23 +192,23 @@ function defineScope(cls, targetClass, name, params, methods, options) { cb = options; options = {}; } - options = options || {} + options = options || {}; // Check if there is a through model // see https://github.com/strongloop/loopback/issues/1076 if (f._scope.collect && condOrRefresh !== null && typeof condOrRefresh === 'object') { //extract the paging filters to the through model - ['limit','offset','skip','order'].forEach(function(pagerFilter){ - if(typeof(condOrRefresh[pagerFilter]) !== 'undefined'){ - f._scope[pagerFilter] = condOrRefresh[pagerFilter]; - delete condOrRefresh[pagerFilter]; - } + ['limit', 'offset', 'skip', 'order'].forEach(function(pagerFilter) { + if (typeof(condOrRefresh[pagerFilter]) !== 'undefined') { + f._scope[pagerFilter] = condOrRefresh[pagerFilter]; + delete condOrRefresh[pagerFilter]; + } }); // Adjust the include so that the condition will be applied to // the target model f._scope.include = { relation: f._scope.collect, - scope: condOrRefresh + scope: condOrRefresh, }; condOrRefresh = {}; } @@ -237,9 +237,9 @@ function defineScope(cls, targetClass, name, params, methods, options) { cb = options; options = {}; } - options = options || {} + options = options || {}; return definition.related(self, f._scope, condOrRefresh, options, cb); - } + }; f.build = build; f.create = create; @@ -259,21 +259,21 @@ function defineScope(cls, targetClass, name, params, methods, options) { // Station.scope('active', {where: {isActive: true}}); // Station.scope('subway', {where: {isUndeground: true}}); // Station.active.subway(cb); - Object.keys(targetClass._scopeMeta).forEach(function (name) { + Object.keys(targetClass._scopeMeta).forEach(function(name) { Object.defineProperty(f, name, { enumerable: false, - get: function () { + get: function() { mergeQuery(f._scope, targetModel._scopeMeta[name]); return f; - } + }, }); }.bind(self)); return f; - } + }, }); // Wrap the property into a function for remoting - var fn = function () { + var fn = function() { // primaryObject.scopeName, such as user.accounts var f = this[name]; // set receiver to be the scope property whose value is a function @@ -282,42 +282,42 @@ function defineScope(cls, targetClass, name, params, methods, options) { cls['__get__' + name] = fn; - var fn_create = function () { + var fn_create = function() { var f = this[name].create; f.apply(this[name], arguments); }; cls['__create__' + name] = fn_create; - var fn_delete = function () { + var fn_delete = function() { var f = this[name].destroyAll; f.apply(this[name], arguments); }; cls['__delete__' + name] = fn_delete; - var fn_update = function () { + var fn_update = function() { var f = this[name].updateAll; f.apply(this[name], arguments); }; cls['__update__' + name] = fn_update; - var fn_findById = function (cb) { + var fn_findById = function(cb) { var f = this[name].findById; f.apply(this[name], arguments); }; cls['__findById__' + name] = fn_findById; - var fn_findOne = function (cb) { + var fn_findOne = function(cb) { var f = this[name].findOne; f.apply(this[name], arguments); }; cls['__findOne__' + name] = fn_findOne; - var fn_count = function (cb) { + var fn_count = function(cb) { var f = this[name].count; f.apply(this[name], arguments); }; @@ -369,7 +369,7 @@ function defineScope(cls, targetClass, name, params, methods, options) { var targetModel = definition.targetModel(this._receiver); var scoped = (this._scope && this._scope.where) || {}; - var filter = mergeQuery({ where: scoped }, { where: where || {} }); + var filter = mergeQuery({ where: scoped }, { where: where || {}}); return targetModel.destroyAll(filter.where, options, cb); } @@ -389,7 +389,7 @@ function defineScope(cls, targetClass, name, params, methods, options) { options = options || {}; var targetModel = definition.targetModel(this._receiver); var scoped = (this._scope && this._scope.where) || {}; - var filter = mergeQuery({ where: scoped }, { where: where || {} }); + var filter = mergeQuery({ where: scoped }, { where: where || {}}); return targetModel.updateAll(filter.where, data, options, cb); } @@ -412,12 +412,12 @@ function defineScope(cls, targetClass, name, params, methods, options) { } } } - + options = options || {}; filter = filter || {}; var targetModel = definition.targetModel(this._receiver); var idName = targetModel.definition.idName(); - var query = {where: {}}; + var query = { where: {}}; query.where[idName] = id; query = mergeQuery(query, filter); return this.findOne(query, options, cb); @@ -455,7 +455,7 @@ function defineScope(cls, targetClass, name, params, methods, options) { var targetModel = definition.targetModel(this._receiver); var scoped = (this._scope && this._scope.where) || {}; - var filter = mergeQuery({ where: scoped }, { where: where || {} }); + var filter = mergeQuery({ where: scoped }, { where: where || {}}); return targetModel.count(filter.where, options, cb); } diff --git a/lib/transaction.js b/lib/transaction.js index 5c1d3623..8edb4845 100644 --- a/lib/transaction.js +++ b/lib/transaction.js @@ -78,7 +78,7 @@ TransactionMixin.beginTransaction = function(options, cb) { setTimeout(function() { var context = { transaction: transaction, - operation: 'timeout' + operation: 'timeout', }; transaction.notifyObserversOf('timeout', context, function(err) { if (!err) { @@ -121,7 +121,7 @@ if (Transaction) { } var context = { transaction: self, - operation: 'commit' + operation: 'commit', }; function work(done) { @@ -155,7 +155,7 @@ if (Transaction) { } var context = { transaction: self, - operation: 'rollback' + operation: 'rollback', }; function work(done) { diff --git a/lib/types.js b/lib/types.js index 286d04c0..f892ae24 100644 --- a/lib/types.js +++ b/lib/types.js @@ -14,7 +14,7 @@ Types.Text = function Text(value) { this.value = value; }; // Text type -Types.Text.prototype.toObject = Types.Text.prototype.toJSON = function () { +Types.Text.prototype.toObject = Types.Text.prototype.toJSON = function() { return this.value; }; @@ -24,7 +24,7 @@ Types.JSON = function JSON(value) { } this.value = value; }; // JSON Object -Types.JSON.prototype.toObject = Types.JSON.prototype.toJSON = function () { +Types.JSON.prototype.toObject = Types.JSON.prototype.toJSON = function() { return this.value; }; @@ -34,20 +34,20 @@ Types.Any = function Any(value) { } this.value = value; }; // Any Type -Types.Any.prototype.toObject = Types.Any.prototype.toJSON = function () { +Types.Any.prototype.toObject = Types.Any.prototype.toJSON = function() { return this.value; }; -module.exports = function (modelTypes) { +module.exports = function(modelTypes) { var GeoPoint = require('./geo').GeoPoint; - for(var t in Types) { + for (var t in Types) { modelTypes[t] = Types[t]; } modelTypes.schemaTypes = {}; - modelTypes.registerType = function (type, names) { + modelTypes.registerType = function(type, names) { names = names || []; names = names.concat([type.name]); for (var n = 0; n < names.length; n++) { @@ -69,4 +69,4 @@ module.exports = function (modelTypes) { modelTypes.registerType(Object); }; -module.exports.Types = Types; \ No newline at end of file +module.exports.Types = Types; diff --git a/lib/utils.js b/lib/utils.js index 4107bde8..f2edd3e5 100644 --- a/lib/utils.js +++ b/lib/utils.js @@ -135,9 +135,9 @@ function convertToArray(include) { if (typeof includeEntry === 'string') { var obj = {}; obj[includeEntry] = true; - normalized.push(obj) + normalized.push(obj); } - else{ + else { normalized.push(includeEntry); } } @@ -163,7 +163,7 @@ function mergeQuery(base, update, spec) { if (update.where && Object.keys(update.where).length > 0) { if (base.where && Object.keys(base.where).length > 0) { - base.where = {and: [base.where, update.where]}; + base.where = { and: [base.where, update.where] }; } else { base.where = update.where; } @@ -174,7 +174,7 @@ function mergeQuery(base, update, spec) { if (!base.include) { base.include = update.include; } else { - if (spec.nestedInclude === true){ + if (spec.nestedInclude === true) { //specify nestedInclude=true to force nesting of inclusions on scoped //queries. e.g. In physician.patients.getAsync({include: 'address'}), //inclusion should be on patient model, not on physician model. @@ -182,7 +182,7 @@ function mergeQuery(base, update, spec) { base.include = {}; base.include[update.include] = saved; } - else{ + else { //default behaviour of inclusion merge - merge inclusions at the same //level. - https://github.com/strongloop/loopback-datasource-juggler/pull/569#issuecomment-95310874 base.include = mergeIncludes(base.include, update.include); @@ -283,7 +283,7 @@ function fieldsToArray(fields, properties, excludeUnknown) { function selectFields(fields) { // map function - return function (obj) { + return function(obj) { var result = {}; var key; @@ -308,7 +308,7 @@ function removeUndefined(query, handleUndefined) { } // WARNING: [rfeng] Use map() will cause mongodb to produce invalid BSON // as traverse doesn't transform the ObjectId correctly - return traverse(query).forEach(function (x) { + return traverse(query).forEach(function(x) { if (x === undefined) { switch (handleUndefined) { case 'nullify': @@ -430,7 +430,7 @@ function defineCachedRelations(obj) { writable: true, enumerable: false, configurable: true, - value: {} + value: {}, }); } } @@ -449,7 +449,7 @@ function isPlainObject(obj) { function sortObjectsByIds(idName, ids, objects, strict) { ids = ids.map(function(id) { - return (typeof id === 'object') ? String(id) : id; + return (typeof id === 'object') ? String(id) : id; }); var indexOf = function(x) { @@ -485,15 +485,15 @@ function createPromiseCallback() { var cb; if (!global.Promise) { - cb = function(){}; + cb = function() {}; cb.promise = {}; Object.defineProperty(cb.promise, 'then', { get: throwPromiseNotDefined }); Object.defineProperty(cb.promise, 'catch', { get: throwPromiseNotDefined }); return cb; } - var promise = new Promise(function (resolve, reject) { - cb = function (err, data) { + var promise = new Promise(function(resolve, reject) { + cb = function(err, data) { if (err) return reject(err); return resolve(data); }; diff --git a/lib/validations.js b/lib/validations.js index ec33e743..9e774099 100644 --- a/lib/validations.js +++ b/lib/validations.js @@ -207,7 +207,7 @@ Validatable.validate = getConfigurator('custom'); * @options {Object} Options See below * @property {String} message Optional error message if property is not valid. Default error message: " is invalid". */ -Validatable.validateAsync = getConfigurator('custom', {async: true}); +Validatable.validateAsync = getConfigurator('custom', { async: true }); /** * Validate uniqueness. Ensure the value for property is unique in the collection of models. @@ -231,7 +231,7 @@ Validatable.validateAsync = getConfigurator('custom', {async: true}); * @property {Array.} scopedTo List of properties defining the scope. * @property {String} message Optional error message if property is not valid. Default error message: "is not unique". */ -Validatable.validatesUniquenessOf = getConfigurator('uniqueness', {async: true}); +Validatable.validatesUniquenessOf = getConfigurator('uniqueness', { async: true }); // implementation of validators @@ -292,7 +292,7 @@ function validateInclusion(attr, conf, err) { if (nullCheck.call(this, attr, conf, err)) return; if (!~conf.in.indexOf(this[attr])) { - err() + err(); } } @@ -303,7 +303,7 @@ function validateExclusion(attr, conf, err) { if (nullCheck.call(this, attr, conf, err)) return; if (~conf.in.indexOf(this[attr])) { - err() + err(); } } @@ -336,7 +336,7 @@ function validateUniqueness(attr, conf, err, done) { if (blank(this[attr])) { return process.nextTick(done); } - var cond = {where: {}}; + var cond = { where: {}}; cond.where[attr] = this[attr]; if (conf && conf.scopedTo) { @@ -349,7 +349,7 @@ function validateUniqueness(attr, conf, err, done) { var idName = this.constructor.definition.idName(); var isNewRecord = this.isNewRecord(); - this.constructor.find(cond, function (error, found) { + this.constructor.find(cond, function(error, found) { if (error) { err(error); } else if (found.length > 1) { @@ -372,11 +372,11 @@ var validators = { exclusion: validateExclusion, format: validateFormat, custom: validateCustom, - uniqueness: validateUniqueness + uniqueness: validateUniqueness, }; function getConfigurator(name, opts) { - return function () { + return function() { var args = Array.prototype.slice.call(arguments); args[1] = args[1] || {}; configure(this, name, args, opts); @@ -415,7 +415,7 @@ function getConfigurator(name, opts) { * @param {Function} callback called with (valid) * @returns {Boolean} True if no asynchronous validation is configured and all properties pass validation. */ -Validatable.prototype.isValid = function (callback, data) { +Validatable.prototype.isValid = function(callback, data) { var valid = true, inst = this, wait = 0, async = false; var validations = this.constructor.validations; @@ -426,8 +426,8 @@ Validatable.prototype.isValid = function (callback, data) { if (typeof validations !== 'object' && !reportDiscardedProperties) { cleanErrors(this); if (callback) { - this.trigger('validate', function (validationsDone) { - validationsDone.call(inst, function () { + this.trigger('validate', function(validationsDone) { + validationsDone.call(inst, function() { callback(valid); }); }, data, callback); @@ -438,10 +438,10 @@ Validatable.prototype.isValid = function (callback, data) { Object.defineProperty(this, 'errors', { enumerable: false, configurable: true, - value: new Errors + value: new Errors, }); - this.trigger('validate', function (validationsDone) { + this.trigger('validate', function(validationsDone) { var inst = this, asyncFail = false; @@ -453,7 +453,7 @@ Validatable.prototype.isValid = function (callback, data) { if (v.options && v.options.async) { async = true; wait += 1; - process.nextTick(function () { + process.nextTick(function() { validationFailed(inst, attr, v, done); }); } else { @@ -475,7 +475,7 @@ Validatable.prototype.isValid = function (callback, data) { } if (!async) { - validationsDone.call(inst, function () { + validationsDone.call(inst, function() { if (valid) cleanErrors(inst); if (callback) { callback(valid); @@ -486,7 +486,7 @@ Validatable.prototype.isValid = function (callback, data) { function done(fail) { asyncFail = asyncFail || fail; if (--wait === 0) { - validationsDone.call(inst, function () { + validationsDone.call(inst, function() { if (valid && !asyncFail) cleanErrors(inst); if (callback) { callback(valid && !asyncFail); @@ -511,7 +511,7 @@ function cleanErrors(inst) { Object.defineProperty(inst, 'errors', { enumerable: false, configurable: true, - value: false + value: false, }); } @@ -559,7 +559,7 @@ function validationFailed(inst, attr, conf, cb) { fail = true; }); if (cb) { - validatorArguments.push(function () { + validatorArguments.push(function() { cb(fail); }); } @@ -593,19 +593,19 @@ var defaultMessages = { length: { min: 'too short', max: 'too long', - is: 'length is wrong' + is: 'length is wrong', }, common: { blank: 'is blank', - 'null': 'is null' + 'null': 'is null', }, numericality: { 'int': 'is not an integer', - 'number': 'is not a number' + 'number': 'is not a number', }, inclusion: 'is not included in the list', exclusion: 'is reserved', - uniqueness: 'is not unique' + uniqueness: 'is not unique', }; function nullCheck(attr, conf, err) { @@ -647,7 +647,7 @@ function configure(cls, validation, args, opts) { writable: true, configurable: true, enumerable: false, - value: {} + value: {}, }); } args = [].slice.call(args); @@ -661,7 +661,7 @@ function configure(cls, validation, args, opts) { conf.customValidator = args.pop(); } conf.validation = validation; - args.forEach(function (attr) { + args.forEach(function(attr) { if (typeof attr === 'string') { var validation = extend({}, conf); validation.options = opts || {}; @@ -675,11 +675,11 @@ function Errors() { Object.defineProperty(this, 'codes', { enumerable: false, configurable: true, - value: {} + value: {}, }); } -Errors.prototype.add = function (field, message, code) { +Errors.prototype.add = function(field, message, code) { code = code || 'invalid'; if (!this[field]) { this[field] = []; @@ -691,7 +691,7 @@ Errors.prototype.add = function (field, message, code) { function ErrorCodes(messages) { var c = this; - Object.keys(messages).forEach(function (field) { + Object.keys(messages).forEach(function(field) { c[field] = messages[field].codes; }); } @@ -763,7 +763,7 @@ function ValidationError(obj) { this.details = { context: context, codes: obj.errors && obj.errors.codes, - messages: obj.errors + messages: obj.errors, }; if (Error.captureStackTrace) { @@ -813,7 +813,7 @@ function formatPropertyError(propertyName, propertyValue, errorMessage) { showHidden: false, color: false, // show top-level object properties only - depth: Array.isArray(propertyValue) ? 1 : 0 + depth: Array.isArray(propertyValue) ? 1 : 0, }); formattedValue = truncatePropertyString(formattedValue); } else { @@ -839,5 +839,5 @@ function truncatePropertyString(value) { len -= 3; } - return value.slice(0, len-4) + '...' + tail; + return value.slice(0, len - 4) + '...' + tail; } diff --git a/support/describe-operation-hooks.js b/support/describe-operation-hooks.js index da1e5bb6..f0e348f7 100644 --- a/support/describe-operation-hooks.js +++ b/support/describe-operation-hooks.js @@ -17,12 +17,12 @@ var Memory = require('../lib/connectors/memory').Memory; var HOOK_NAMES = [ 'access', 'before save', 'persist', 'after save', - 'before delete', 'after delete' + 'before delete', 'after delete', ]; var dataSources = [ createOptimizedDataSource(), - createUnoptimizedDataSource() + createUnoptimizedDataSource(), ]; var observedContexts = []; @@ -34,7 +34,7 @@ Promise.onPossiblyUnhandledRejection(function(err) { var operations = [ function find(ds) { - return ds.TestModel.find({ where: { id: '1' } }); + return ds.TestModel.find({ where: { id: '1' }}); }, function count(ds) { @@ -47,13 +47,13 @@ var operations = [ function findOrCreate_found(ds) { return ds.TestModel.findOrCreate( - { where: { name: ds.existingInstance.name } }, + { where: { name: ds.existingInstance.name }}, { name: ds.existingInstance.name }); }, function findOrCreate_create(ds) { return ds.TestModel.findOrCreate( - { where: { name: 'new-record' } }, + { where: { name: 'new-record' }}, { name: 'new-record' }); }, @@ -134,7 +134,7 @@ function setupTestModels() { var TestModel = ds.TestModel = ds.createModel('TestModel', { id: { type: String, id: true, default: uid }, name: { type: String, required: true }, - extra: { type: String, required: false } + extra: { type: String, required: false }, }); }); return Promise.resolve(); @@ -155,7 +155,7 @@ function runner(fn) { observedContexts.push({ operation: fn.name, connector: ds.name, - hooks: {} + hooks: {}, }); return fn(ds); }); @@ -171,11 +171,11 @@ function resetStorage(ds) { }); return TestModel.deleteAll() .then(function() { - return TestModel.create({ name: 'first' }) + return TestModel.create({ name: 'first' }); }) .then(function(instance) { // Look it up from DB so that default values are retrieved - return TestModel.findById(instance.id) + return TestModel.findById(instance.id); }) .then(function(instance) { ds.existingInstance = instance; @@ -184,7 +184,7 @@ function resetStorage(ds) { .then(function() { HOOK_NAMES.forEach(function(hook) { TestModel.observe(hook, function(ctx, next) { - var row = observedContexts[observedContexts.length-1]; + var row = observedContexts[observedContexts.length - 1]; row.hooks[hook] = Object.keys(ctx); next(); }); @@ -193,7 +193,7 @@ function resetStorage(ds) { } function report() { - console.log('