From 261ca1f0927b0463aef6e6f6d2fbc9b2cd4e9b3b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Miroslav=20Bajto=C5=A1?= Date: Fri, 7 Dec 2018 15:47:25 +0100 Subject: [PATCH 1/3] eslint: enable no-var and prefer-const rules --- .eslintrc | 3 +++ 1 file changed, 3 insertions(+) diff --git a/.eslintrc b/.eslintrc index 267f7f7b..47a68f9c 100644 --- a/.eslintrc +++ b/.eslintrc @@ -4,6 +4,9 @@ "ecmaVersion": 2017 }, "rules": { + // TODO(bajtos) move these two rules to eslint-config-loopback + "no-var": "error", + "prefer-const": "error", "max-len": ["error", 110, 4, { "ignoreComments": true, "ignoreUrls": true, From 422ec9ad4f94c80fb838d8d4172c5777f9ed33e2 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Miroslav=20Bajto=C5=A1?= Date: Fri, 7 Dec 2018 15:54:29 +0100 Subject: [PATCH 2/3] autofix eslint errors --- examples/app-noschema.js | 20 +- examples/app.js | 12 +- examples/datasource-app.js | 26 +- examples/inclusion.js | 18 +- examples/load-schemas.js | 6 +- examples/nesting-schema.js | 8 +- examples/relations.js | 26 +- index.js | 4 +- lib/browser.depd.js | 2 +- lib/connectors/kv-memory.js | 62 +- lib/connectors/memory.js | 228 ++--- lib/connectors/transient.js | 22 +- lib/dao.js | 526 +++++----- lib/datasource.js | 346 +++---- lib/date-string.js | 4 +- lib/geo.js | 52 +- lib/hooks.js | 16 +- lib/include.js | 240 ++--- lib/include_utils.js | 52 +- lib/introspection.js | 14 +- lib/jutil.js | 22 +- lib/kvao/delete-all.js | 18 +- lib/kvao/delete.js | 12 +- lib/kvao/expire.js | 4 +- lib/kvao/get.js | 4 +- lib/kvao/iterate-keys.js | 6 +- lib/kvao/keys.js | 8 +- lib/kvao/set.js | 4 +- lib/kvao/ttl.js | 4 +- lib/list.js | 18 +- lib/mixins.js | 12 +- lib/model-builder.js | 170 ++-- lib/model-definition.js | 62 +- lib/model-utils.js | 108 +- lib/model.js | 120 +-- lib/observer.js | 26 +- lib/relation-definition.js | 958 +++++++++--------- lib/relations.js | 4 +- lib/scope.js | 130 +-- lib/transaction.js | 24 +- lib/types.js | 10 +- lib/utils.js | 150 +-- lib/validations.js | 82 +- support/describe-operation-hooks.js | 36 +- test/CustomTypeForeignKey.test.js | 10 +- test/allow-extended-operators.test.js | 2 +- test/async-observer.test.js | 58 +- test/basic-querying.test.js | 72 +- test/common_test.js | 98 +- test/crud-with-options.test.js | 20 +- test/datasource.test.js | 28 +- test/datatype.test.js | 36 +- test/date-string.test.js | 32 +- test/default-scope.test.js | 42 +- test/defaults.test.js | 8 +- test/discovery.test.js | 74 +- test/exclude-base-props.test.js | 16 +- test/geo.test.js | 38 +- test/helpers/bdd-if.js | 2 +- test/helpers/context-test-helpers.js | 4 +- test/helpers/hook-monitor.js | 4 +- test/helpers/uid-generator.js | 2 +- test/hooks.test.js | 24 +- test/include.test.js | 208 ++-- test/include_util.test.js | 48 +- test/init.js | 4 +- test/introspection.test.js | 52 +- test/json.test.js | 16 +- test/kv-memory.js | 10 +- test/kvao.suite.js | 18 +- test/kvao/_helpers.js | 2 +- test/kvao/delete-all.suite.js | 2 +- test/kvao/expire.suite.js | 12 +- test/kvao/get-set.suite.js | 8 +- test/kvao/iterate-keys.suite.js | 16 +- test/kvao/keys.suite.js | 14 +- test/kvao/ttl.suite.js | 14 +- test/list.test.js | 36 +- test/loopback-data.test.js | 4 +- test/loopback-dl.test.js | 490 ++++----- test/manipulation.test.js | 196 ++-- test/memory.test.js | 102 +- test/mixins.test.js | 40 +- test/model-builder.test.js | 2 +- test/model-definition.test.js | 134 +-- test/model-inheritance.test.js | 20 +- test/normalize-undefined.test.js | 30 +- .../embeds-many-create.suite.js | 20 +- .../embeds-many-destroy.suite.js | 22 +- .../embeds-many-update-by-id.suite.js | 22 +- .../embeds-one-create.suite.js | 20 +- .../embeds-one-destroy.suite.js | 22 +- .../embeds-one-update.suite.js | 22 +- test/operation-hooks.suite/index.js | 14 +- test/optional-validation.test.js | 20 +- test/persistence-hooks.suite.js | 92 +- test/relations.test.js | 578 +++++------ test/schema.test.js | 12 +- test/scope.test.js | 16 +- test/spec_helper.js | 2 +- test/transaction.test.js | 2 +- test/transient.test.js | 14 +- test/util.test.js | 206 ++-- test/validations.test.js | 188 ++-- 104 files changed, 3498 insertions(+), 3498 deletions(-) diff --git a/examples/app-noschema.js b/examples/app-noschema.js index e1027d90..69b64493 100644 --- a/examples/app-noschema.js +++ b/examples/app-noschema.js @@ -5,16 +5,16 @@ 'use strict'; -var DataSource = require('../../loopback-datasource-juggler').DataSource; -var ModelBuilder = require('../../loopback-datasource-juggler').ModelBuilder; -var introspectType = require('../lib/introspection')(ModelBuilder); +const DataSource = require('../../loopback-datasource-juggler').DataSource; +const ModelBuilder = require('../../loopback-datasource-juggler').ModelBuilder; +const introspectType = require('../lib/introspection')(ModelBuilder); -var ds = new DataSource('memory'); +const ds = new DataSource('memory'); // Create a open model that doesn't require a schema -var Application = ds.createModel('Schemaless', {}, {strict: false}); +const Application = ds.createModel('Schemaless', {}, {strict: false}); -var application = { +const application = { owner: 'rfeng', name: 'MyApp1', description: 'My first app', @@ -47,7 +47,7 @@ Application.create(application, function(err, app1) { }); // Instance JSON document -var user = { +const user = { name: 'Joe', age: 30, birthday: new Date(), @@ -68,13 +68,13 @@ var user = { }; // Introspect the JSON document to generate a schema -var schema = introspectType(user); +const schema = introspectType(user); // Create a model for the generated schema -var User = ds.createModel('User', schema, {idInjection: true}); +const User = ds.createModel('User', schema, {idInjection: true}); // Use the model for CRUD -var obj = new User(user); +const obj = new User(user); console.log(obj.toObject()); diff --git a/examples/app.js b/examples/app.js index 488b8f5b..e29a2dbb 100644 --- a/examples/app.js +++ b/examples/app.js @@ -5,10 +5,10 @@ 'use strict'; -var ModelBuilder = require('../../loopback-datasource-juggler').ModelBuilder; -var modelBuilder = new ModelBuilder(); +const ModelBuilder = require('../../loopback-datasource-juggler').ModelBuilder; +const modelBuilder = new ModelBuilder(); // define models -var Post = modelBuilder.define('Post', { +const Post = modelBuilder.define('Post', { title: {type: String, length: 255}, content: {type: ModelBuilder.Text}, date: {type: Date, default: function() { @@ -19,7 +19,7 @@ var Post = modelBuilder.define('Post', { }); // simpler way to describe model -var User = modelBuilder.define('User', { +const User = modelBuilder.define('User', { name: String, bio: ModelBuilder.Text, approved: Boolean, @@ -27,14 +27,14 @@ var User = modelBuilder.define('User', { age: Number, }); -var Group = modelBuilder.define('Group', {group: String}); +const Group = modelBuilder.define('Group', {group: String}); // define any custom method User.prototype.getNameAndAge = function() { return this.name + ', ' + this.age; }; -var user = new User({name: 'Joe'}); +let user = new User({name: 'Joe'}); console.log(user); console.log(modelBuilder.models); diff --git a/examples/datasource-app.js b/examples/datasource-app.js index 34b70cf6..0ba825d1 100644 --- a/examples/datasource-app.js +++ b/examples/datasource-app.js @@ -5,12 +5,12 @@ 'use strict'; -var DataSource = require('../../loopback-datasource-juggler').DataSource; -var ModelBuilder = require('../../loopback-datasource-juggler').ModelBuilder; -var ds = new DataSource('memory'); +const DataSource = require('../../loopback-datasource-juggler').DataSource; +const ModelBuilder = require('../../loopback-datasource-juggler').ModelBuilder; +const ds = new DataSource('memory'); // define models -var Post = ds.define('Post', { +const Post = ds.define('Post', { title: {type: String, length: 255}, content: {type: DataSource.Text}, date: {type: Date, default: function() { @@ -21,7 +21,7 @@ var Post = ds.define('Post', { }); // simplier way to describe model -var User = ds.define('User', { +const User = ds.define('User', { name: String, bio: DataSource.Text, approved: Boolean, @@ -29,14 +29,14 @@ var User = ds.define('User', { age: Number, }); -var Group = ds.define('Group', {name: String}); +const Group = ds.define('Group', {name: String}); // define any custom method User.prototype.getNameAndAge = function() { return this.name + ', ' + this.age; }; -var user = new User({name: 'Joe'}); +const user = new User({name: 'Joe'}); console.log(user); // console.log(ds.models); @@ -58,10 +58,10 @@ Post.belongsTo(User, {as: 'author', foreignKey: 'userId'}); User.hasAndBelongsToMany('groups'); -var user2 = new User({name: 'Smith', age: 14}); +const user2 = new User({name: 'Smith', age: 14}); user2.save(function(err) { console.log(user2); - var post = user2.posts.build({title: 'Hello world'}); + const post = user2.posts.build({title: 'Hello world'}); post.save(function(err, data) { console.log(err ? err : data); }); @@ -77,7 +77,7 @@ User.create({name: 'Jeff', age: 12}, function(err, data) { return; } console.log(data); - var post = data.posts.build({title: 'My Post'}); + const post = data.posts.build({title: 'My Post'}); console.log(post); }); @@ -90,8 +90,8 @@ User.minors(function(err, kids) { console.log('Kids: ', kids); }); -var Article = ds.define('Article', {title: String}); -var Tag = ds.define('Tag', {name: String}); +const Article = ds.define('Article', {title: String}); +const Tag = ds.define('Tag', {name: String}); Article.hasAndBelongsToMany('tags'); Article.create(function(e, article) { @@ -105,7 +105,7 @@ Article.create(function(e, article) { }); // should be able to attach a data source to an existing model -var modelBuilder = new ModelBuilder(); +const modelBuilder = new ModelBuilder(); const Color = modelBuilder.define('Color', { name: String, diff --git a/examples/inclusion.js b/examples/inclusion.js index acd149bc..8bcf94df 100644 --- a/examples/inclusion.js +++ b/examples/inclusion.js @@ -5,10 +5,10 @@ 'use strict'; -var jdb = require('../index'); +const jdb = require('../index'); -var User, Post, Passport, City, Street, Building; -var nbSchemaRequests = 0; +let User, Post, Passport, City, Street, Building; +const nbSchemaRequests = 0; setup(function() { Passport.find({include: 'owner'}, function(err, passports) { @@ -35,7 +35,7 @@ setup(function() { }); function setup(done) { - var db = new jdb.DataSource({connector: 'memory'}); + const db = new jdb.DataSource({connector: 'memory'}); City = db.define('City'); Street = db.define('Street'); Building = db.define('Building'); @@ -56,9 +56,9 @@ function setup(done) { Post.belongsTo('author', {model: User, foreignKey: 'userId'}); db.automigrate(function() { - var createdUsers = []; - var createdPassports = []; - var createdPosts = []; + let createdUsers = []; + let createdPassports = []; + let createdPosts = []; createUsers(); function createUsers() { clearAndCreate( @@ -112,12 +112,12 @@ function setup(done) { } function clearAndCreate(model, data, callback) { - var createdItems = []; + const createdItems = []; model.destroyAll(function() { nextItem(null, null); }); - var itemIndex = 0; + let itemIndex = 0; function nextItem(err, lastItem) { if (lastItem !== null) { diff --git a/examples/load-schemas.js b/examples/load-schemas.js index 3af462a1..d9b8f336 100644 --- a/examples/load-schemas.js +++ b/examples/load-schemas.js @@ -5,7 +5,7 @@ 'use strict'; -var path = require('path'), +const path = require('path'), fs = require('fs'), DataSource = require('../lib/datasource').DataSource; @@ -21,12 +21,12 @@ function loadSchemasSync(schemaFile, dataSource) { } // Read the dataSource JSON file - var schemas = JSON.parse(fs.readFileSync(schemaFile)); + const schemas = JSON.parse(fs.readFileSync(schemaFile)); return dataSource.buildModels(schemas); } -var models = loadSchemasSync(path.join(__dirname, 'jdb-schemas.json')); +let models = loadSchemasSync(path.join(__dirname, 'jdb-schemas.json')); for (const s in models) { const m = models[s]; diff --git a/examples/nesting-schema.js b/examples/nesting-schema.js index db99a503..5adaeb9c 100644 --- a/examples/nesting-schema.js +++ b/examples/nesting-schema.js @@ -5,11 +5,11 @@ 'use strict'; -var ModelBuilder = require('../../loopback-datasource-juggler').ModelBuilder; -var modelBuilder = new ModelBuilder(); +const ModelBuilder = require('../../loopback-datasource-juggler').ModelBuilder; +const modelBuilder = new ModelBuilder(); // simplier way to describe model -var User = modelBuilder.define('User', { +const User = modelBuilder.define('User', { name: String, bio: ModelBuilder.Text, approved: Boolean, @@ -31,7 +31,7 @@ var User = modelBuilder.define('User', { friends: [String], }); -var user = new User({ +const user = new User({ name: 'Joe', age: 20, address: {street: '123 Main St', 'city': 'San Jose', state: 'CA'}, diff --git a/examples/relations.js b/examples/relations.js index 858766ea..a2dd20cc 100644 --- a/examples/relations.js +++ b/examples/relations.js @@ -5,22 +5,22 @@ 'use strict'; -var DataSource = require('../index').DataSource; -var ds = new DataSource('memory'); +const DataSource = require('../index').DataSource; +const ds = new DataSource('memory'); -var Order = ds.createModel('Order', { +const Order = ds.createModel('Order', { items: [String], orderDate: Date, qty: Number, }); -var Customer = ds.createModel('Customer', { +const Customer = ds.createModel('Customer', { name: String, }); Order.belongsTo(Customer); -var order1, order2, order3; +let order1, order2, order3; Customer.create({name: 'John'}, function(err, customer) { Order.create({customerId: customer.id, orderDate: new Date(), items: ['Book']}, function(err, order) { @@ -42,7 +42,7 @@ Customer.create({name: 'John'}, function(err, customer) { }); }); - var customer3 = order.customer.build({name: 'Tom'}); + const customer3 = order.customer.build({name: 'Tom'}); console.log('Customer 3', customer3); }); }); @@ -67,15 +67,15 @@ Customer.create({name: 'Ray'}, function(err, customer) { }); }); -var Physician = ds.createModel('Physician', { +const Physician = ds.createModel('Physician', { name: String, }); -var Patient = ds.createModel('Patient', { +const Patient = ds.createModel('Patient', { name: String, }); -var Appointment = ds.createModel('Appointment', { +const Appointment = ds.createModel('Appointment', { physicianId: Number, patientId: Number, appointmentDate: Date, @@ -102,7 +102,7 @@ Physician.create({name: 'Dr John'}, function(err, physician1) { patient1.physicians(console.log); // Build an appointment? - var patient3 = patient1.physicians.build({name: 'Dr X'}); + const patient3 = patient1.physicians.build({name: 'Dr X'}); console.log('Physician 3: ', patient3, patient3.constructor.modelName); // Create a physician? @@ -118,11 +118,11 @@ Physician.create({name: 'Dr John'}, function(err, physician1) { }); }); -var Assembly = ds.createModel('Assembly', { +const Assembly = ds.createModel('Assembly', { name: String, }); -var Part = ds.createModel('Part', { +const Part = ds.createModel('Part', { partNumber: String, }); @@ -137,7 +137,7 @@ Assembly.create({name: 'car'}, function(err, assembly) { }); // Build an part? - var part3 = assembly.parts.build({partNumber: 'door'}); + const part3 = assembly.parts.build({partNumber: 'door'}); console.log('Part3: ', part3, part3.constructor.modelName); // Create a part? diff --git a/index.js b/index.js index 18e9e292..9cabf639 100644 --- a/index.js +++ b/index.js @@ -4,7 +4,7 @@ // License text available at https://opensource.org/licenses/MIT 'use strict'; -var SG = require('strong-globalize'); +const SG = require('strong-globalize'); SG.SetRootDir(__dirname); exports.ModelBuilder = exports.LDL = require('./lib/model-builder.js').ModelBuilder; @@ -17,7 +17,7 @@ Object.defineProperty(exports, 'version', { get: function() { return require('./package.json').version; }, }); -var commonTest = './test/common_test'; +const commonTest = './test/common_test'; Object.defineProperty(exports, 'test', { get: function() { return require(commonTest); }, }); diff --git a/lib/browser.depd.js b/lib/browser.depd.js index b8c29967..ec9c846a 100644 --- a/lib/browser.depd.js +++ b/lib/browser.depd.js @@ -7,7 +7,7 @@ // A lightweight alternative to "depd" that works in the browser module.exports = function depd(namespace) { - var warned = {}; + const warned = {}; return function deprecate(message) { if (warned[message]) return; warned[message] = true; diff --git a/lib/connectors/kv-memory.js b/lib/connectors/kv-memory.js index 61415e86..9962ff49 100644 --- a/lib/connectors/kv-memory.js +++ b/lib/connectors/kv-memory.js @@ -1,15 +1,15 @@ 'use strict'; -var g = require('strong-globalize')(); +const g = require('strong-globalize')(); -var assert = require('assert'); -var Connector = require('loopback-connector').Connector; -var debug = require('debug')('loopback:connector:kv-memory'); -var minimatch = require('minimatch'); -var util = require('util'); +const assert = require('assert'); +const Connector = require('loopback-connector').Connector; +const debug = require('debug')('loopback:connector:kv-memory'); +const minimatch = require('minimatch'); +const util = require('util'); exports.initialize = function initializeDataSource(dataSource, cb) { - var settings = dataSource.settings; + const settings = dataSource.settings; dataSource.connector = new KeyValueMemoryConnector(settings, dataSource); if (cb) process.nextTick(cb); }; @@ -33,7 +33,7 @@ KeyValueMemoryConnector.prototype._setupRegularCleanup = function() { // in order to release memory. Note that GET operation checks // key expiration too, the scheduled cleanup is merely a performance // optimization. - var self = this; + const self = this; var timer = this._cleanupTimer = setInterval( function() { if (self && self._removeExpiredItems) { @@ -50,9 +50,9 @@ KeyValueMemoryConnector.prototype._setupRegularCleanup = function() { KeyValueMemoryConnector._removeExpiredItems = function() { debug('Running scheduled cleanup of expired items.'); - for (var modelName in this._store) { - var modelStore = this._store[modelName]; - for (var key in modelStore) { + for (const modelName in this._store) { + const modelStore = this._store[modelName]; + for (const key in modelStore) { if (modelStore[key].isExpired()) { debug('Removing expired key', key); delete modelStore[key]; @@ -69,8 +69,8 @@ KeyValueMemoryConnector.prototype._getStoreForModel = function(modelName) { }; KeyValueMemoryConnector.prototype._removeIfExpired = function(modelName, key) { - var store = this._getStoreForModel(modelName); - var item = store[key]; + const store = this._getStoreForModel(modelName); + let item = store[key]; if (item && item.isExpired()) { debug('Removing expired key', key); delete store[key]; @@ -84,9 +84,9 @@ KeyValueMemoryConnector.prototype.get = function(modelName, key, options, callback) { this._removeIfExpired(modelName, key); - var store = this._getStoreForModel(modelName); - var item = store[key]; - var value = item ? item.value : null; + const store = this._getStoreForModel(modelName); + const item = store[key]; + let value = item ? item.value : null; debug('GET %j %j -> %s', modelName, key, value); if (/^buffer:/.test(value)) { @@ -104,7 +104,7 @@ function(modelName, key, options, callback) { KeyValueMemoryConnector.prototype.set = function(modelName, key, value, options, callback) { - var store = this._getStoreForModel(modelName); + const store = this._getStoreForModel(modelName); if (Buffer.isBuffer(value)) { value = 'buffer:' + value.toString('base64'); } else if (value instanceof Date) { @@ -123,11 +123,11 @@ KeyValueMemoryConnector.prototype.expire = function(modelName, key, ttl, options, callback) { this._removeIfExpired(modelName, key); - var store = this._getStoreForModel(modelName); + const store = this._getStoreForModel(modelName); if (!(key in store)) { return process.nextTick(function() { - var err = new Error(g.f('Cannot expire unknown key %j', key)); + const err = new Error(g.f('Cannot expire unknown key %j', key)); err.statusCode = 404; callback(err); }); @@ -142,18 +142,18 @@ KeyValueMemoryConnector.prototype.ttl = function(modelName, key, options, callback) { this._removeIfExpired(modelName, key); - var store = this._getStoreForModel(modelName); + const store = this._getStoreForModel(modelName); // key is unknown if (!(key in store)) { return process.nextTick(function() { - var err = new Error(g.f('Cannot get TTL for unknown key %j', key)); + const err = new Error(g.f('Cannot get TTL for unknown key %j', key)); err.statusCode = 404; callback(err); }); } - var ttl = store[key].getTtl(); + const ttl = store[key].getTtl(); debug('TTL %j %j -> %s', modelName, key, ttl); process.nextTick(function() { @@ -163,20 +163,20 @@ function(modelName, key, options, callback) { KeyValueMemoryConnector.prototype.iterateKeys = function(modelName, filter, options, callback) { - var store = this._getStoreForModel(modelName); - var self = this; - var checkFilter = createMatcher(filter.match); + const store = this._getStoreForModel(modelName); + const self = this; + const checkFilter = createMatcher(filter.match); - var keys = Object.keys(store).filter(function(key) { + const keys = Object.keys(store).filter(function(key) { return !self._removeIfExpired(modelName, key) && checkFilter(key); }); debug('ITERATE KEYS %j -> %s keys', modelName, keys.length); - var ix = 0; + let ix = 0; return { next: function(cb) { - var value = ix < keys.length ? keys[ix++] : undefined; + const value = ix < keys.length ? keys[ix++] : undefined; setImmediate(function() { cb(null, value); }); }, }; @@ -203,15 +203,15 @@ KeyValueMemoryConnector.prototype.disconnect = function(callback) { KeyValueMemoryConnector.prototype.delete = function(modelName, key, options, callback) { - var store = this._getStoreForModel(modelName); + const store = this._getStoreForModel(modelName); delete store[key]; callback(); }; KeyValueMemoryConnector.prototype.deleteAll = function(modelName, options, callback) { - var modelStore = this._getStoreForModel(modelName); - for (var key in modelStore) + const modelStore = this._getStoreForModel(modelName); + for (const key in modelStore) delete modelStore[key]; callback(); }; diff --git a/lib/connectors/memory.js b/lib/connectors/memory.js index c8f5489f..9d44c8d1 100644 --- a/lib/connectors/memory.js +++ b/lib/connectors/memory.js @@ -6,14 +6,14 @@ 'use strict'; /* global window:false */ -var g = require('strong-globalize')(); -var util = require('util'); -var Connector = require('loopback-connector').Connector; -var geo = require('../geo'); -var utils = require('../utils'); -var fs = require('fs'); -var async = require('async'); -var debug = require('debug')('loopback:connector:memory'); +const g = require('strong-globalize')(); +const util = require('util'); +const Connector = require('loopback-connector').Connector; +const geo = require('../geo'); +const utils = require('../utils'); +const fs = require('fs'); +const async = require('async'); +const debug = require('debug')('loopback:connector:memory'); /** * Initialize the Memory connector against the given data source @@ -82,7 +82,7 @@ function deserialize(dbObj) { } Memory.prototype.getCollection = function(model) { - var modelClass = this._models[model]; + const modelClass = this._models[model]; if (modelClass && modelClass.settings.memory) { model = modelClass.settings.memory.collection || model; } @@ -111,12 +111,12 @@ Memory.prototype.collectionSeq = function(model, val) { * @returns {*} The file operation queue */ Memory.prototype.setupFileQueue = function() { - var self = this; + const self = this; if (!this.fileQueue) { // Create a queue for writes this.fileQueue = async.queue(function(task, done) { - var callback = task.callback || function() {}; - var file = self.settings.file; + const callback = task.callback || function() {}; + const file = self.settings.file; if (task.operation === 'write') { // Flush out the models/ids var data = JSON.stringify({ @@ -147,7 +147,7 @@ Memory.prototype.setupFileQueue = function() { } }); } else { - var err = new Error('Unknown type of task'); + const err = new Error('Unknown type of task'); done(err); callback(err); } @@ -176,8 +176,8 @@ Memory.prototype.parseAndLoad = function(data, callback) { }; Memory.prototype.loadFromFile = function(callback) { - var hasLocalStorage = typeof window !== 'undefined' && window.localStorage; - var localStorage = hasLocalStorage && this.settings.localStorage; + const hasLocalStorage = typeof window !== 'undefined' && window.localStorage; + const localStorage = hasLocalStorage && this.settings.localStorage; if (this.settings.file) { debug('Queueing read %s', this.settings.file); @@ -186,7 +186,7 @@ Memory.prototype.loadFromFile = function(callback) { callback: callback, }); } else if (localStorage) { - var data = window.localStorage.getItem(localStorage); + let data = window.localStorage.getItem(localStorage); data = data || '{}'; this.parseAndLoad(data, callback); } else { @@ -199,9 +199,9 @@ Memory.prototype.loadFromFile = function(callback) { * @param {Function} callback */ Memory.prototype.saveToFile = function(result, callback) { - var file = this.settings.file; - var hasLocalStorage = typeof window !== 'undefined' && window.localStorage; - var localStorage = hasLocalStorage && this.settings.localStorage; + const file = this.settings.file; + const hasLocalStorage = typeof window !== 'undefined' && window.localStorage; + const localStorage = hasLocalStorage && this.settings.localStorage; if (file) { debug('Queueing write %s', this.settings.file); // Enqueue the write @@ -212,7 +212,7 @@ Memory.prototype.saveToFile = function(result, callback) { }); } else if (localStorage) { // Flush out the models/ids - var data = JSON.stringify({ + const data = JSON.stringify({ ids: this.ids, models: this.cache, }, null, ' '); @@ -229,26 +229,26 @@ 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; + const m = definition.model.modelName; if (!this.collection(m)) this.initCollection(m); }; Memory.prototype._createSync = function(model, data, fn) { // FIXME: [rfeng] We need to generate unique ids based on the id type // FIXME: [rfeng] We don't support composite ids yet - var currentId = this.collectionSeq(model); + let currentId = this.collectionSeq(model); if (currentId === undefined) { // First time currentId = this.collectionSeq(model, 1); } - var id = this.getIdValue(model, data) || currentId; + let id = this.getIdValue(model, data) || currentId; if (id > currentId) { // If the id is passed in and the value is greater than the current id currentId = id; } this.collectionSeq(model, Number(currentId) + 1); - var props = this._models[model].properties; - var idName = this.idName(model); + const props = this._models[model].properties; + const idName = this.idName(model); id = (props[idName] && props[idName].type && props[idName].type(id)) || id; this.setIdValue(model, data, id); if (!this.collection(model)) { @@ -256,7 +256,7 @@ Memory.prototype._createSync = function(model, data, fn) { } if (this.collection(model)[id]) { - var error = new Error(g.f('Duplicate entry for %s.%s', model, idName)); + const error = new Error(g.f('Duplicate entry for %s.%s', model, idName)); error.statusCode = error.status = 409; return fn(error); } @@ -266,7 +266,7 @@ Memory.prototype._createSync = function(model, data, fn) { }; Memory.prototype.create = function create(model, data, options, callback) { - var self = this; + const self = this; this._createSync(model, data, function(err, id) { if (err) { return process.nextTick(function() { @@ -278,7 +278,7 @@ Memory.prototype.create = function create(model, data, options, callback) { }; Memory.prototype.updateOrCreate = function(model, data, options, callback) { - var self = this; + const self = this; this.exists(model, self.getIdValue(model, data), options, function(err, exists) { if (exists) { self.save(model, data, options, function(err, data) { @@ -295,10 +295,10 @@ Memory.prototype.updateOrCreate = function(model, data, options, callback) { Memory.prototype.patchOrCreateWithWhere = Memory.prototype.upsertWithWhere = function(model, where, data, options, callback) { - var self = this; - var primaryKey = this.idName(model); - var filter = {where: where}; - var nodes = self._findAllSkippingIncludes(model, filter); + const self = this; + const primaryKey = this.idName(model); + const filter = {where: where}; + const nodes = self._findAllSkippingIncludes(model, filter); if (nodes.length === 0) { return self._createSync(model, data, function(err, id) { if (err) return process.nextTick(function() { callback(err); }); @@ -309,13 +309,13 @@ Memory.prototype.upsertWithWhere = function(model, where, data, options, callbac }); } if (nodes.length === 1) { - var primaryKeyValue = nodes[0][primaryKey]; + const primaryKeyValue = nodes[0][primaryKey]; self.updateAttributes(model, primaryKeyValue, data, options, function(err, data) { callback(err, data, {isNewInstance: false}); }); } else { process.nextTick(function() { - var error = new Error('There are multiple instances found.' + + const error = new Error('There are multiple instances found.' + 'Upsert Operation will not be performed!'); error.statusCode = 400; callback(error); @@ -324,9 +324,9 @@ Memory.prototype.upsertWithWhere = function(model, where, data, options, callbac }; Memory.prototype.findOrCreate = function(model, filter, data, options, callback) { - var self = this; - var nodes = self._findAllSkippingIncludes(model, filter); - var found = nodes[0]; + const self = this; + const nodes = self._findAllSkippingIncludes(model, filter); + const found = nodes[0]; 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 @@ -354,10 +354,10 @@ Memory.prototype.findOrCreate = function(model, filter, data, options, callback) }; Memory.prototype.save = function save(model, data, options, callback) { - var self = this; - var id = this.getIdValue(model, data); - var cachedModels = this.collection(model); - var modelData = cachedModels && this.collection(model)[id]; + const self = this; + const id = this.getIdValue(model, data); + const cachedModels = this.collection(model); + let modelData = cachedModels && this.collection(model)[id]; modelData = modelData && deserialize(modelData); if (modelData) { data = merge(modelData, data); @@ -381,7 +381,7 @@ Memory.prototype.find = function find(model, id, options, callback) { }; Memory.prototype.destroy = function destroy(model, id, options, callback) { - var exists = this.collection(model)[id]; + const exists = this.collection(model)[id]; delete this.collection(model)[id]; this.saveToFile({count: exists ? 1 : 0}, callback); }; @@ -389,9 +389,9 @@ Memory.prototype.destroy = function destroy(model, id, options, callback) { Memory.prototype.fromDb = function(model, data) { if (!data) return null; data = deserialize(data); - var props = this._models[model].properties; - for (var key in data) { - var val = data[key]; + const props = this._models[model].properties; + for (const key in data) { + let val = data[key]; if (val === undefined || val === null) { continue; } @@ -417,9 +417,9 @@ function getValue(obj, path) { if (obj == null) { return undefined; } - var keys = path.split('.'); - var val = obj; - for (var i = 0, n = keys.length; i < n; i++) { + const keys = path.split('.'); + let val = obj; + for (let i = 0, n = keys.length; i < n; i++) { val = val[keys[i]]; if (val == null) { return val; @@ -429,26 +429,26 @@ function getValue(obj, path) { } Memory.prototype._findAllSkippingIncludes = function(model, filter) { - var nodes = Object.keys(this.collection(model)).map(function(key) { + let nodes = Object.keys(this.collection(model)).map(function(key) { return this.fromDb(model, this.collection(model)[key]); }.bind(this)); if (filter) { if (!filter.order) { - var idNames = this.idNames(model); + const idNames = this.idNames(model); if (idNames && idNames.length) { filter.order = idNames; } } // do we need some sorting? if (filter.order) { - var orders = filter.order; + let orders = filter.order; if (typeof filter.order === 'string') { orders = [filter.order]; } orders.forEach(function(key, i) { - var reverse = 1; - var m = key.match(/\s+(A|DE)SC$/i); + let reverse = 1; + const 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; @@ -458,7 +458,7 @@ Memory.prototype._findAllSkippingIncludes = function(model, filter) { nodes = nodes.sort(sorting.bind(orders)); } - var nearFilter = geo.nearFilter(filter.where); + const nearFilter = geo.nearFilter(filter.where); // geo sorting if (nearFilter) { @@ -475,18 +475,18 @@ Memory.prototype._findAllSkippingIncludes = function(model, filter) { } // limit/skip - var skip = filter.skip || filter.offset || 0; - var limit = filter.limit || nodes.length; + const skip = filter.skip || filter.offset || 0; + const limit = filter.limit || nodes.length; nodes = nodes.slice(skip, skip + limit); } return nodes; function sorting(a, b) { - var undefinedA, undefinedB; + let undefinedA, undefinedB; - for (var i = 0, l = this.length; i < l; i++) { - var aVal = getValue(a, this[i].key); - var bVal = getValue(b, this[i].key); + for (let i = 0, l = this.length; i < l; i++) { + const aVal = getValue(a, this[i].key); + const bVal = getValue(b, this[i].key); undefinedB = bVal === undefined && aVal !== undefined; undefinedA = aVal === undefined && bVal !== undefined; @@ -502,8 +502,8 @@ Memory.prototype._findAllSkippingIncludes = function(model, filter) { }; Memory.prototype.all = function all(model, filter, options, callback) { - var self = this; - var nodes = self._findAllSkippingIncludes(model, filter); + const self = this; + const nodes = self._findAllSkippingIncludes(model, filter); process.nextTick(function() { if (filter && filter.include) { @@ -515,11 +515,11 @@ Memory.prototype.all = function all(model, filter, options, callback) { }; function applyFilter(filter) { - var where = filter.where; + const where = filter.where; if (typeof where === 'function') { return where; } - var keys = Object.keys(where); + const keys = Object.keys(where); return function(obj) { return keys.every(function(key) { if (key === 'and' || key === 'or') { @@ -537,18 +537,18 @@ function applyFilter(filter) { } } - var value = getValue(obj, key); + const value = getValue(obj, key); // Support referencesMany and other embedded relations // Also support array types. Mongo, possibly PostgreSQL if (Array.isArray(value)) { - var matcher = where[key]; + const matcher = where[key]; // The following condition is for the case where we are querying with // a neq filter, and when the value is an empty array ([]). if (matcher.neq !== undefined && value.length <= 0) { return true; } return value.some(function(v, i) { - var filter = {where: {}}; + const filter = {where: {}}; filter.where[i] = matcher; return applyFilter(filter)(value); }); @@ -560,11 +560,11 @@ function applyFilter(filter) { // If we have a composed key a.b and b would resolve to a property of an object inside an array // then, we attempt to emulate mongo db matching. Helps for embedded relations - var dotIndex = key.indexOf('.'); - var subValue = obj[key.substring(0, dotIndex)]; + const dotIndex = key.indexOf('.'); + const subValue = obj[key.substring(0, dotIndex)]; if (dotIndex !== -1) { - var subFilter = {where: {}}; - var subKey = key.substring(dotIndex + 1); + const subFilter = {where: {}}; + const subKey = key.substring(dotIndex + 1); subFilter.where[subKey] = where[key]; if (Array.isArray(subValue)) { return subValue.some(applyFilter(subFilter)); @@ -581,12 +581,12 @@ function applyFilter(filter) { if (pattern instanceof RegExp) { return pattern; } - var regex = ''; + let 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'); - for (var i = 0, n = pattern.length; i < n; i++) { - var char = pattern.charAt(i); + for (let i = 0, n = pattern.length; i < n; i++) { + const char = pattern.charAt(i); if (char === '\\') { i++; // Skip to next char if (i < n) { @@ -627,7 +627,7 @@ function applyFilter(filter) { return true; } - var i; + let i; if (example.inq) { // if (!value) return false; for (i = 0; i < example.inq.length; i++) { @@ -657,7 +657,7 @@ function applyFilter(filter) { } if (example.like || example.nlike || example.ilike || example.nilike) { - var like = example.like || example.nlike || example.ilike || example.nilike; + let like = example.like || example.nlike || example.ilike || example.nilike; if (typeof like === 'string') { like = toRegExp(like); } @@ -709,7 +709,7 @@ function applyFilter(filter) { return val1 - val2; } if (val1 instanceof Date) { - var result = val1 - val2; + const result = val1 - val2; return result; } // Return NaN if we don't know how to compare @@ -734,9 +734,9 @@ function applyFilter(filter) { } Memory.prototype.destroyAll = function destroyAll(model, where, options, callback) { - var cache = this.collection(model); - var filter = null; - var count = 0; + const cache = this.collection(model); + let filter = null; + let count = 0; if (where) { filter = applyFilter({where: where}); Object.keys(cache).forEach(function(id) { @@ -753,10 +753,10 @@ Memory.prototype.destroyAll = function destroyAll(model, where, options, callbac }; Memory.prototype.count = function count(model, where, options, callback) { - var cache = this.collection(model); - var data = Object.keys(cache); + const cache = this.collection(model); + let data = Object.keys(cache); if (where) { - var filter = {where: where}; + const filter = {where: where}; data = data.map(function(id) { return this.fromDb(model, cache[id]); }.bind(this)); @@ -769,16 +769,16 @@ Memory.prototype.count = function count(model, where, options, callback) { Memory.prototype.update = Memory.prototype.updateAll = function updateAll(model, where, data, options, cb) { - var self = this; - var cache = this.collection(model); - var filter = null; + const self = this; + const cache = this.collection(model); + let filter = null; where = where || {}; filter = applyFilter({where: where}); - var ids = Object.keys(cache); - var count = 0; + const ids = Object.keys(cache); + let count = 0; async.each(ids, function(id, done) { - var inst = self.fromDb(model, cache[id]); + const inst = self.fromDb(model, cache[id]); if (!filter || filter(inst)) { count++; // The id value from the cache is string @@ -796,7 +796,7 @@ Memory.prototype.update = Memory.prototype.updateAttributes = function updateAttributes(model, id, data, options, cb) { if (!id) { - var err = new Error(g.f('You must provide an {{id}} when updating attributes!')); + const err = new Error(g.f('You must provide an {{id}} when updating attributes!')); if (cb) { return cb(err); } else { @@ -809,40 +809,40 @@ Memory.prototype.updateAttributes = function updateAttributes(model, id, data, o this.setIdValue(model, data, id); - var cachedModels = this.collection(model); - var modelData = cachedModels && this.collection(model)[id]; + const cachedModels = this.collection(model); + const modelData = cachedModels && this.collection(model)[id]; if (modelData) { this.save(model, data, options, cb); } else { - var msg = g.f('Could not update attributes. {{Object}} with {{id}} %s does not exist!', id); - var error = new Error(msg); + const msg = g.f('Could not update attributes. {{Object}} with {{id}} %s does not exist!', id); + const error = new Error(msg); error.statusCode = error.status = 404; cb(error); } }; Memory.prototype.replaceById = function(model, id, data, options, cb) { - var self = this; + const self = this; if (!id) { - var err = new Error(g.f('You must provide an {{id}} when replacing!')); + const err = new Error(g.f('You must provide an {{id}} when replacing!')); return process.nextTick(function() { cb(err); }); } // Do not modify the data object passed in arguments data = Object.create(data); this.setIdValue(model, data, id); - var cachedModels = this.collection(model); - var modelData = cachedModels && this.collection(model)[id]; + const cachedModels = this.collection(model); + const modelData = cachedModels && this.collection(model)[id]; if (!modelData) { - var msg = 'Could not replace. Object with id ' + id + ' does not exist!'; - var error = new Error(msg); + const msg = 'Could not replace. Object with id ' + id + ' does not exist!'; + const error = new Error(msg); error.statusCode = error.status = 404; return process.nextTick(function() { cb(error); }); } - var newModelData = {}; - for (var key in data) { - var val = data[key]; + const newModelData = {}; + for (const key in data) { + const val = data[key]; if (typeof val === 'function') { continue; // Skip methods } @@ -856,13 +856,13 @@ Memory.prototype.replaceById = function(model, id, data, options, cb) { }; 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: {}}; + const self = this; + const idName = self.idNames(model)[0]; + const idValue = self.getIdValue(model, data); + const filter = {where: {}}; filter.where[idName] = idValue; - var nodes = self._findAllSkippingIncludes(model, filter); - var found = nodes[0]; + const nodes = self._findAllSkippingIncludes(model, filter); + const found = nodes[0]; if (!found) { // Calling _createSync to update the collection in a sync way and @@ -875,7 +875,7 @@ Memory.prototype.replaceOrCreate = function(model, data, options, callback) { }); }); } - var id = self.getIdValue(model, data); + const id = self.getIdValue(model, data); self.collection(model)[id] = serialize(data); self.saveToFile(data, function(err) { callback(err, self.fromDb(model, data), {isNewInstance: false}); @@ -896,7 +896,7 @@ Memory.prototype.buildNearFilter = function(filter) { }; Memory.prototype.automigrate = function(models, cb) { - var self = this; + const self = this; if ((!cb) && ('function' === typeof models)) { cb = models; @@ -912,7 +912,7 @@ Memory.prototype.automigrate = function(models, cb) { return process.nextTick(cb); } - var invalidModels = models.filter(function(m) { + const invalidModels = models.filter(function(m) { return !(m in self._models); }); @@ -935,8 +935,8 @@ 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) { - var val = update[key]; + for (const key in update) { + const val = update[key]; if (typeof val === 'function') { continue; // Skip methods } diff --git a/lib/connectors/transient.js b/lib/connectors/transient.js index 5578e2a9..8baa5b5d 100644 --- a/lib/connectors/transient.js +++ b/lib/connectors/transient.js @@ -5,11 +5,11 @@ 'use strict'; -var g = require('strong-globalize')(); -var util = require('util'); -var Connector = require('loopback-connector').Connector; -var utils = require('../utils'); -var crypto = require('crypto'); +const g = require('strong-globalize')(); +const util = require('util'); +const Connector = require('loopback-connector').Connector; +const utils = require('../utils'); +const crypto = require('crypto'); /** * Initialize the Transient connector against the given data source @@ -59,8 +59,8 @@ Transient.prototype.connect = function(callback) { }; Transient.prototype.generateId = function(model, data, idName) { - var idType; - var props = this._models[model].properties; + let idType; + const props = this._models[model].properties; if (idName) idType = props[idName] && props[idName].type; idType = idType || this.getDefaultIdType(); if (idType === Number) { @@ -89,8 +89,8 @@ Transient.prototype.count = function count(model, callback, where) { }; Transient.prototype.create = function create(model, data, callback) { - var props = this._models[model].properties; - var idName = this.idName(model); + const props = this._models[model].properties; + const idName = this.idName(model); if (idName && props[idName]) { var id = this.getIdValue(model, data) || this.generateId(model, data, idName); id = (props[idName] && props[idName].type && props[idName].type(id)) || id; @@ -105,13 +105,13 @@ Transient.prototype.save = function save(model, data, callback) { Transient.prototype.update = Transient.prototype.updateAll = function updateAll(model, where, data, cb) { - var count = 0; + const count = 0; this.flush('update', {count: count}, cb); }; Transient.prototype.updateAttributes = function updateAttributes(model, id, data, cb) { if (!id) { - var err = new Error(g.f('You must provide an {{id}} when updating attributes!')); + const err = new Error(g.f('You must provide an {{id}} when updating attributes!')); if (cb) { return cb(err); } else { diff --git a/lib/dao.js b/lib/dao.js index 1f484dc2..a6f95d57 100644 --- a/lib/dao.js +++ b/lib/dao.js @@ -15,26 +15,26 @@ module.exports = DataAccessObject; /*! * Module dependencies */ -var g = require('strong-globalize')(); -var async = require('async'); -var jutil = require('./jutil'); -var DataAccessObjectUtils = require('./model-utils'); -var ValidationError = require('./validations').ValidationError; -var Relation = require('./relations.js'); -var Inclusion = require('./include.js'); -var List = require('./list.js'); -var geo = require('./geo'); -var Memory = require('./connectors/memory').Memory; -var utils = require('./utils'); -var fieldsToArray = utils.fieldsToArray; -var sanitizeQueryOrData = utils.sanitizeQuery; -var setScopeValuesFromWhere = utils.setScopeValuesFromWhere; -var idEquals = utils.idEquals; -var mergeQuery = utils.mergeQuery; -var util = require('util'); -var assert = require('assert'); -var BaseModel = require('./model'); -var debug = require('debug')('loopback:dao'); +const g = require('strong-globalize')(); +const async = require('async'); +const jutil = require('./jutil'); +const DataAccessObjectUtils = require('./model-utils'); +const ValidationError = require('./validations').ValidationError; +const Relation = require('./relations.js'); +const Inclusion = require('./include.js'); +const List = require('./list.js'); +const geo = require('./geo'); +const Memory = require('./connectors/memory').Memory; +const utils = require('./utils'); +const fieldsToArray = utils.fieldsToArray; +const sanitizeQueryOrData = utils.sanitizeQuery; +const setScopeValuesFromWhere = utils.setScopeValuesFromWhere; +const idEquals = utils.idEquals; +const mergeQuery = utils.mergeQuery; +const util = require('util'); +const assert = require('assert'); +const BaseModel = require('./model'); +const debug = require('debug')('loopback:dao'); /** * Base class for all persistent objects. @@ -46,8 +46,8 @@ var debug = require('debug')('loopback:dao'); */ function DataAccessObject() { if (DataAccessObject._mixins) { - var self = this; - var args = arguments; + const self = this; + const args = arguments; DataAccessObject._mixins.forEach(function(m) { m.call(self, args); }); @@ -63,14 +63,14 @@ function getIdValue(m, data) { } function copyData(from, to) { - for (var key in from) { + for (const key in from) { to[key] = from[key]; } } function convertSubsetOfPropertiesByType(inst, data) { - var typedData = {}; - for (var key in data) { + const typedData = {}; + for (const key in data) { // Convert the properties by type typedData[key] = inst[key]; if (typeof typedData[key] === 'object' && @@ -87,10 +87,10 @@ function convertSubsetOfPropertiesByType(inst, data) { * Notice: Please note this method modifies `inst` when `strict` is `validate`. */ function applyStrictCheck(model, strict, data, inst, cb) { - var props = model.definition.properties; - var keys = Object.keys(data); - var result = {}, key; - for (var i = 0; i < keys.length; i++) { + const props = model.definition.properties; + const keys = Object.keys(data); + let result = {}, key; + for (let i = 0; i < keys.length; i++) { key = keys[i]; if (props[key]) { result[key] = data[key]; @@ -108,38 +108,38 @@ function setIdValue(m, data, value) { } function byIdQuery(m, id) { - var pk = idName(m); - var query = {where: {}}; + const pk = idName(m); + const query = {where: {}}; query.where[pk] = id; return query; } function isWhereByGivenId(Model, where, idValue) { - var keys = Object.keys(where); + const keys = Object.keys(where); if (keys.length != 1) return false; - var pk = idName(Model); + const pk = idName(Model); if (keys[0] !== pk) return false; return where[pk] === idValue; } function errorModelNotFound(idValue) { - var msg = g.f('Could not update attributes. {{Object}} with {{id}} %s does not exist!', idValue); - var error = new Error(msg); + const msg = g.f('Could not update attributes. {{Object}} with {{id}} %s does not exist!', idValue); + const error = new Error(msg); error.statusCode = error.status = 404; return error; } function invokeConnectorMethod(connector, method, Model, args, options, cb) { - var dataSource = Model.getDataSource(); + const dataSource = Model.getDataSource(); // If the DataSource is a transaction and no transaction object is provide in // the options yet, add it to the options, see: DataSource#transaction() - var opts = dataSource.isTransaction && !options.transaction ? Object.assign( + const opts = dataSource.isTransaction && !options.transaction ? Object.assign( options, {transaction: dataSource.currentTransaction} ) : options; - var optionsSupported = connector[method].length >= args.length + 3; - var transaction = opts.transaction; + const optionsSupported = connector[method].length >= args.length + 3; + const transaction = opts.transaction; if (transaction) { if (!optionsSupported) { return process.nextTick(function() { @@ -154,12 +154,12 @@ function invokeConnectorMethod(connector, method, Model, args, options, cb) { return; } } - var modelName = Model.modelName; - var fullArgs; + const modelName = Model.modelName; + let fullArgs; if (!optionsSupported && method === 'count') { // NOTE: The old count() signature is irregular, with `where` coming last: // [modelName, cb, where] - var where = args[0]; + const where = args[0]; fullArgs = [modelName, cb, where]; } else { // Standard signature: [modelName, ...args, (opts, ) cb] @@ -176,9 +176,9 @@ DataAccessObject._forDB = function(data) { if (!(this.getDataSource().isRelational && this.getDataSource().isRelational())) { return data; } - var res = {}; - for (var propName in data) { - var type = this.getPropertyType(propName); + const res = {}; + for (const propName in data) { + const type = this.getPropertyType(propName); if (type === 'JSON' || type === 'Any' || type === 'Object' || data[propName] instanceof Array) { res[propName] = JSON.stringify(data[propName]); } else { @@ -189,7 +189,7 @@ DataAccessObject._forDB = function(data) { }; DataAccessObject.defaultScope = function(target, inst) { - var scope = this.definition.settings.scope; + let scope = this.definition.settings.scope; if (typeof scope === 'function') { scope = this.definition.settings.scope.call(this, target, inst); } @@ -197,21 +197,21 @@ DataAccessObject.defaultScope = function(target, inst) { }; DataAccessObject.applyScope = function(query, inst) { - var scope = this.defaultScope(query, inst) || {}; + const scope = this.defaultScope(query, inst) || {}; if (typeof scope === 'object') { mergeQuery(query, scope || {}, this.definition.settings.scope); } }; DataAccessObject.applyProperties = function(data, inst) { - var properties = this.definition.settings.properties; + let properties = this.definition.settings.properties; properties = properties || this.definition.settings.attributes; if (typeof properties === 'object') { util._extend(data, properties); } else if (typeof properties === 'function') { util._extend(data, properties.call(this, data, inst) || {}); } else if (properties !== false) { - var scope = this.defaultScope(data, inst) || {}; + const scope = this.defaultScope(data, inst) || {}; if (typeof scope.where === 'object') { setScopeValuesFromWhere(data, scope.where, this); } @@ -248,17 +248,17 @@ DataAccessObject.getConnector = function() { * - instance (null or Model) */ DataAccessObject.create = function(data, options, cb) { - var connectionPromise = stillConnecting(this.getDataSource(), this, arguments); + const connectionPromise = stillConnecting(this.getDataSource(), this, arguments); if (connectionPromise) { return connectionPromise; } - var Model = this; - var connector = Model.getConnector(); + let Model = this; + const connector = Model.getConnector(); assert(typeof connector.create === 'function', 'create() must be implemented by the connector'); - var self = this; + const self = this; if (options === undefined && cb === undefined) { if (typeof data === 'function') { @@ -282,13 +282,13 @@ DataAccessObject.create = function(data, options, cb) { assert(typeof options === 'object', 'The options argument must be an object'); assert(typeof cb === 'function', 'The cb argument must be a function'); - var hookState = {}; + const hookState = {}; if (Array.isArray(data)) { // Undefined item will be skipped by async.map() which internally uses // Array.prototype.map(). The following loop makes sure all items are // iterated - for (var i = 0, n = data.length; i < n; i++) { + for (let i = 0, n = data.length; i < n; i++) { if (data[i] === undefined) { data[i] = {}; } @@ -303,9 +303,9 @@ DataAccessObject.create = function(data, options, cb) { return cb(err, results); } // Convert the results into two arrays - var errors = null; - var data = []; - for (var i = 0, n = results.length; i < n; i++) { + let errors = null; + const data = []; + for (let i = 0, n = results.length; i < n; i++) { if (results[i].err) { if (!errors) { errors = []; @@ -319,9 +319,9 @@ DataAccessObject.create = function(data, options, cb) { return cb.promise; } - var enforced = {}; - var obj; - var idValue = getIdValue(this, data); + const enforced = {}; + let obj; + const idValue = getIdValue(this, data); try { // if we come from save @@ -340,7 +340,7 @@ DataAccessObject.create = function(data, options, cb) { Model = this.lookupModel(data); // data-specific if (Model !== obj.constructor) obj = new Model(data); - var context = { + let context = { Model: Model, instance: obj, isNewInstance: true, @@ -375,8 +375,8 @@ DataAccessObject.create = function(data, options, cb) { function create() { obj.trigger('create', function(createDone) { obj.trigger('save', function(saveDone) { - var _idName = idName(Model); - var val = Model._sanitizeData(obj.toObject(true), options); + const _idName = idName(Model); + let val = Model._sanitizeData(obj.toObject(true), options); function createCallback(err, id, rev) { if (id) { obj.__data[_idName] = id; @@ -390,7 +390,7 @@ DataAccessObject.create = function(data, options, cb) { } obj.__persisted = true; - var context = { + const context = { Model: Model, data: val, isNewInstance: true, @@ -412,7 +412,7 @@ DataAccessObject.create = function(data, options, cb) { if (err) { return cb(err, obj); } - var context = { + const context = { Model: Model, instance: obj, isNewInstance: true, @@ -458,9 +458,9 @@ function stillConnecting(dataSource, obj, args) { } // promise variant - var promiseArgs = Array.prototype.slice.call(args); + const promiseArgs = Array.prototype.slice.call(args); promiseArgs.callee = args.callee; - var cb = utils.createPromiseCallback(); + const cb = utils.createPromiseCallback(); promiseArgs.push(cb); if (dataSource.ready(obj, promiseArgs)) { return cb.promise; @@ -485,7 +485,7 @@ function stillConnecting(dataSource, obj, args) { DataAccessObject.updateOrCreate = DataAccessObject.patchOrCreate = DataAccessObject.upsert = function(data, options, cb) { - var connectionPromise = stillConnecting(this.getDataSource(), this, arguments); + const connectionPromise = stillConnecting(this.getDataSource(), this, arguments); if (connectionPromise) { return connectionPromise; } @@ -517,17 +517,17 @@ DataAccessObject.upsert = function(data, options, cb) { return cb.promise; } - var hookState = {}; + const hookState = {}; - var self = this; - var Model = this; - var connector = Model.getConnector(); + const self = this; + let Model = this; + const connector = Model.getConnector(); - var id = getIdValue(this, data); + const id = getIdValue(this, data); if (id === undefined || id === null) { return this.create(data, options, cb); } - var doValidate = undefined; + let doValidate = undefined; if (options.validate === undefined) { if (Model.settings.validateUpsert === undefined) { if (Model.settings.automaticValidation !== undefined) { @@ -540,7 +540,7 @@ DataAccessObject.upsert = function(data, options, cb) { doValidate = options.validate; } - var forceId = this.settings.forceId; + const forceId = this.settings.forceId; if (forceId) { options = Object.create(options); options.validate = !!doValidate; @@ -552,7 +552,7 @@ DataAccessObject.upsert = function(data, options, cb) { return cb.promise; } - var context = { + const context = { Model: Model, query: byIdQuery(Model, id), hookState: hookState, @@ -563,9 +563,9 @@ DataAccessObject.upsert = function(data, options, cb) { function doUpdateOrCreate(err, ctx) { if (err) return cb(err); - var isOriginalQuery = isWhereByGivenId(Model, ctx.query.where, id); + const isOriginalQuery = isWhereByGivenId(Model, ctx.query.where, id); if (connector.updateOrCreate && isOriginalQuery) { - var context = { + let context = { Model: Model, where: ctx.query.where, data: data, @@ -576,8 +576,8 @@ DataAccessObject.upsert = function(data, options, cb) { if (err) return cb(err); data = ctx.data; - var update = data; - var inst = data; + let update = data; + let inst = data; if (!(data instanceof Model)) { inst = new Model(data, {applyDefaultValues: false}); } @@ -621,7 +621,7 @@ DataAccessObject.upsert = function(data, options, cb) { } function done(err, data, info) { if (err) return cb(err); - var context = { + const context = { Model: Model, data: data, isNewInstance: info && info.isNewInstance, @@ -631,7 +631,7 @@ DataAccessObject.upsert = function(data, options, cb) { Model.notifyObserversOf('loaded', context, function(err) { if (err) return cb(err); - var obj; + let obj; if (data && !(data instanceof Model)) { inst._initProperties(data, {persisted: true}); obj = inst; @@ -641,7 +641,7 @@ DataAccessObject.upsert = function(data, options, cb) { if (err) { cb(err, obj); } else { - var context = { + const context = { Model: Model, instance: obj, isNewInstance: info ? info.isNewInstance : undefined, @@ -661,7 +661,7 @@ DataAccessObject.upsert = function(data, options, cb) { } }); } else { - var opts = {notify: false}; + const opts = {notify: false}; if (ctx.options && ctx.options.transaction) { opts.transaction = ctx.options.transaction; } @@ -678,7 +678,7 @@ DataAccessObject.upsert = function(data, options, cb) { inst.updateAttributes(data, options, cb); } else { Model = self.lookupModel(data); - var obj = new Model(data); + const obj = new Model(data); obj.save(options, cb); } }); @@ -704,7 +704,7 @@ DataAccessObject.upsert = function(data, options, cb) { */ DataAccessObject.patchOrCreateWithWhere = DataAccessObject.upsertWithWhere = function(where, data, options, cb) { - var connectionPromise = stillConnecting(this.getDataSource(), this, arguments); + const connectionPromise = stillConnecting(this.getDataSource(), this, arguments); if (connectionPromise) { return connectionPromise; } if (cb === undefined) { if (typeof options === 'function') { @@ -720,17 +720,17 @@ DataAccessObject.upsertWithWhere = function(where, data, options, cb) { assert(typeof options === 'object', 'The options argument must be an object'); assert(typeof cb === 'function', 'The cb argument must be a function'); if (Object.keys(data).length === 0) { - var err = new Error('data object cannot be empty!'); + const err = new Error('data object cannot be empty!'); err.statusCode = 400; process.nextTick(function() { cb(err); }); return cb.promise; } - var hookState = {}; - var self = this; - var Model = this; - var connector = Model.getConnector(); - var query = {where: where}; - var context = { + const hookState = {}; + const self = this; + let Model = this; + const connector = Model.getConnector(); + const query = {where: where}; + const context = { Model: Model, query: query, hookState: hookState, @@ -741,7 +741,7 @@ DataAccessObject.upsertWithWhere = function(where, data, options, cb) { if (err) return cb(err); ctx.data = data; if (connector.upsertWithWhere) { - var context = { + let context = { Model: Model, where: ctx.query.where, data: ctx.data, @@ -751,8 +751,8 @@ DataAccessObject.upsertWithWhere = function(where, data, options, cb) { Model.notifyObserversOf('before save', context, function(err, ctx) { if (err) return cb(err); data = ctx.data; - var update = data; - var inst = data; + let update = data; + let inst = data; if (!(data instanceof Model)) { inst = new Model(data, {applyDefaultValues: false}); } @@ -797,7 +797,7 @@ DataAccessObject.upsertWithWhere = function(where, data, options, cb) { } function done(err, data, info) { if (err) return cb(err); - var contxt = { + const contxt = { Model: Model, data: data, isNewInstance: info && info.isNewInstance, @@ -806,14 +806,14 @@ DataAccessObject.upsertWithWhere = function(where, data, options, cb) { }; Model.notifyObserversOf('loaded', contxt, function(err) { if (err) return cb(err); - var obj; + let obj; if (contxt.data && !(contxt.data instanceof Model)) { inst._initProperties(contxt.data, {persisted: true}); obj = inst; } else { obj = contxt.data; } - var context = { + const context = { Model: Model, instance: obj, isNewInstance: info ? info.isNewInstance : undefined, @@ -827,21 +827,21 @@ DataAccessObject.upsertWithWhere = function(where, data, options, cb) { } }); } else { - var opts = {notify: false}; + const opts = {notify: false}; if (ctx.options && ctx.options.transaction) { opts.transaction = ctx.options.transaction; } self.find({where: ctx.query.where}, opts, function(err, instances) { if (err) return cb(err); - var modelsLength = instances.length; + const modelsLength = instances.length; if (modelsLength === 0) { self.create(data, options, cb); } else if (modelsLength === 1) { - var modelInst = instances[0]; + const modelInst = instances[0]; modelInst.updateAttributes(data, options, cb); } else { process.nextTick(function() { - var error = new Error('There are multiple instances found.' + + const error = new Error('There are multiple instances found.' + 'Upsert Operation will not be performed!'); error.statusCode = 400; cb(error); @@ -862,7 +862,7 @@ DataAccessObject.upsertWithWhere = function(where, data, options, cb) { */ DataAccessObject.replaceOrCreate = function replaceOrCreate(data, options, cb) { - var connectionPromise = stillConnecting(this.getDataSource(), this, arguments); + const connectionPromise = stillConnecting(this.getDataSource(), this, arguments); if (connectionPromise) { return connectionPromise; } @@ -883,31 +883,31 @@ DataAccessObject.replaceOrCreate = function replaceOrCreate(data, options, cb) { assert(typeof options === 'object', 'The options argument must be an object'); assert(typeof cb === 'function', 'The cb argument must be a function'); - var hookState = {}; + const hookState = {}; - var self = this; - var Model = this; - var connector = Model.getConnector(); + const self = this; + let Model = this; + const connector = Model.getConnector(); - var id = getIdValue(this, data); + let id = getIdValue(this, data); if (id === undefined || id === null) { return this.create(data, options, cb); } - var forceId = this.settings.forceId; + const forceId = this.settings.forceId; if (forceId) { return Model.replaceById(id, data, options, cb); } - var inst; + let inst; if (data instanceof Model) { inst = data; } else { inst = new Model(data); } - var strict = inst.__strict; - var context = { + const strict = inst.__strict; + const context = { Model: Model, query: byIdQuery(Model, id), hookState: hookState, @@ -918,10 +918,10 @@ DataAccessObject.replaceOrCreate = function replaceOrCreate(data, options, cb) { function doReplaceOrCreate(err, ctx) { if (err) return cb(err); - var isOriginalQuery = isWhereByGivenId(Model, ctx.query.where, id); - var where = ctx.query.where; + const isOriginalQuery = isWhereByGivenId(Model, ctx.query.where, id); + const where = ctx.query.where; if (connector.replaceOrCreate && isOriginalQuery) { - var context = { + let context = { Model: Model, instance: inst, hookState: hookState, @@ -929,7 +929,7 @@ DataAccessObject.replaceOrCreate = function replaceOrCreate(data, options, cb) { }; Model.notifyObserversOf('before save', context, function(err, ctx) { if (err) return cb(err); - var update = inst.toObject(false); + let update = inst.toObject(false); if (strict) { applyStrictCheck(Model, strict, update, inst, validateAndCallConnector); } else { @@ -972,7 +972,7 @@ DataAccessObject.replaceOrCreate = function replaceOrCreate(data, options, cb) { } function done(err, data, info) { if (err) return cb(err); - var context = { + const context = { Model: Model, data: data, isNewInstance: info ? info.isNewInstance : undefined, @@ -982,7 +982,7 @@ DataAccessObject.replaceOrCreate = function replaceOrCreate(data, options, cb) { Model.notifyObserversOf('loaded', context, function(err) { if (err) return cb(err); - var obj; + let obj; if (data && !(data instanceof Model)) { inst._initProperties(data, {persisted: true}); obj = inst; @@ -992,7 +992,7 @@ DataAccessObject.replaceOrCreate = function replaceOrCreate(data, options, cb) { if (err) { cb(err, obj); } else { - var context = { + const context = { Model: Model, instance: obj, isNewInstance: info ? info.isNewInstance : undefined, @@ -1009,7 +1009,7 @@ DataAccessObject.replaceOrCreate = function replaceOrCreate(data, options, cb) { } }); } else { - var opts = {notify: false}; + const opts = {notify: false}; if (ctx.options && ctx.options.transaction) { opts.transaction = ctx.options.transaction; } @@ -1018,7 +1018,7 @@ DataAccessObject.replaceOrCreate = function replaceOrCreate(data, options, cb) { if (!isOriginalQuery) { // The custom query returned from a hook may hide the fact that // there is already a model with `id` value `data[idName(Model)]` - var pkName = idName(Model); + const pkName = idName(Model); delete data[pkName]; if (found) id = found[pkName]; } @@ -1026,7 +1026,7 @@ DataAccessObject.replaceOrCreate = function replaceOrCreate(data, options, cb) { self.replaceById(id, data, options, cb); } else { Model = self.lookupModel(data); - var obj = new Model(data); + const obj = new Model(data); obj.save(options, cb); } }); @@ -1047,7 +1047,7 @@ DataAccessObject.replaceOrCreate = function replaceOrCreate(data, options, cb) { * @param {Function} cb Callback called with (err, instance, created) */ DataAccessObject.findOrCreate = function findOrCreate(query, data, options, cb) { - var connectionPromise = stillConnecting(this.getDataSource(), this, arguments); + const connectionPromise = stillConnecting(this.getDataSource(), this, arguments); if (connectionPromise) { return connectionPromise; } @@ -1085,16 +1085,16 @@ DataAccessObject.findOrCreate = function findOrCreate(query, data, options, cb) assert(typeof options === 'object', 'The options argument must be an object'); assert(typeof cb === 'function', 'The cb argument must be a function'); - var hookState = {}; + const hookState = {}; - var Model = this; - var self = this; - var connector = Model.getConnector(); + const Model = this; + const self = this; + const connector = Model.getConnector(); function _findOrCreate(query, data, currentInstance) { function findOrCreateCallback(err, data, created) { if (err) return cb(err); - var context = { + const context = { Model: Model, data: data, isNewInstance: created, @@ -1105,7 +1105,7 @@ DataAccessObject.findOrCreate = function findOrCreate(query, data, options, cb) if (err) return cb(err); data = ctx.data; - var obj, Model = self.lookupModel(data); + let obj, Model = self.lookupModel(data); if (data) { obj = new Model(data, {fields: query.fields, applySetters: false, @@ -1113,7 +1113,7 @@ DataAccessObject.findOrCreate = function findOrCreate(query, data, options, cb) } if (created) { - var context = { + const context = { Model: Model, instance: obj, isNewInstance: true, @@ -1138,7 +1138,7 @@ DataAccessObject.findOrCreate = function findOrCreate(query, data, options, cb) } data = Model._sanitizeData(data, options); - var context = { + const context = { Model: Model, where: query.where, data: data, @@ -1169,7 +1169,7 @@ DataAccessObject.findOrCreate = function findOrCreate(query, data, options, cb) this.applyScope(query); - var context = { + const context = { Model: Model, query: query, hookState: hookState, @@ -1178,16 +1178,16 @@ DataAccessObject.findOrCreate = function findOrCreate(query, data, options, cb) Model.notifyObserversOf('access', context, function(err, ctx) { if (err) return cb(err); - var query = ctx.query; + const query = ctx.query; - var enforced = {}; - var Model = self.lookupModel(data); - var obj = data instanceof Model ? data : new Model(data); + const enforced = {}; + const Model = self.lookupModel(data); + const obj = data instanceof Model ? data : new Model(data); Model.applyProperties(enforced, obj); obj.setAttributes(enforced); - var context = { + const context = { Model: Model, instance: obj, isNewInstance: true, @@ -1197,8 +1197,8 @@ DataAccessObject.findOrCreate = function findOrCreate(query, data, options, cb) Model.notifyObserversOf('before save', context, function(err, ctx) { if (err) return cb(err); - var obj = ctx.instance; - var data = obj.toObject(true); + const obj = ctx.instance; + const data = obj.toObject(true); // options has precedence on model-setting if (options.validate === false) { @@ -1250,7 +1250,7 @@ DataAccessObject.findOrCreate = function findOrCreate(query, data, options, cb) * @param {Function} cb Callback function called with (err, exists: Bool) */ DataAccessObject.exists = function exists(id, options, cb) { - var connectionPromise = stillConnecting(this.getDataSource(), this, arguments); + const connectionPromise = stillConnecting(this.getDataSource(), this, arguments); if (connectionPromise) { return connectionPromise; } @@ -1300,7 +1300,7 @@ DataAccessObject.exists = function exists(id, options, cb) { * @param {Function} cb Callback called with (err, instance) */ DataAccessObject.findById = function findById(id, filter, options, cb) { - var connectionPromise = stillConnecting(this.getDataSource(), this, arguments); + const connectionPromise = stillConnecting(this.getDataSource(), this, arguments); if (connectionPromise) { return connectionPromise; } @@ -1341,7 +1341,7 @@ DataAccessObject.findById = function findById(id, filter, options, cb) { cb(new Error(g.f('{{Model::findById}} requires the {{id}} argument'))); }); } else { - var query = byIdQuery(this, id); + const query = byIdQuery(this, id); if (filter.include) { query.include = filter.include; } @@ -1391,14 +1391,14 @@ DataAccessObject.findByIds = function(ids, query, options, cb) { return cb.promise; } - var filter = {where: {}}; - var pk = idName(this); + const filter = {where: {}}; + const 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; + const toSortObjectsByIds = filter.order ? false : true; this.find(filter, options, function(err, results) { cb(err, toSortObjectsByIds ? utils.sortObjectsByIds(pk, ids, results) : results); @@ -1409,10 +1409,10 @@ DataAccessObject.findByIds = function(ids, query, options, cb) { function convertNullToNotFoundError(ctx, cb) { if (ctx.result !== null) return cb(); - var modelName = ctx.method.sharedClass.name; - var id = ctx.getArgByName('id'); - var msg = g.f('Unknown "%s" {{id}} "%s".', modelName, id); - var error = new Error(msg); + const modelName = ctx.method.sharedClass.name; + const id = ctx.getArgByName('id'); + const msg = g.f('Unknown "%s" {{id}} "%s".', modelName, id); + const error = new Error(msg); error.statusCode = error.status = 404; cb(error); } @@ -1483,7 +1483,7 @@ DataAccessObject.all = function() { */ DataAccessObject.find = function find(query, options, cb) { - var connectionPromise = stillConnecting(this.getDataSource(), this, arguments); + const connectionPromise = stillConnecting(this.getDataSource(), this, arguments); if (connectionPromise) { return connectionPromise; } @@ -1510,9 +1510,9 @@ DataAccessObject.find = function find(query, options, cb) { assert(typeof options === 'object', 'The options argument must be an object'); assert(typeof cb === 'function', 'The cb argument must be a function'); - var hookState = {}; - var self = this; - var connector = self.getConnector(); + const hookState = {}; + const self = this; + const connector = self.getConnector(); assert(typeof connector.all === 'function', 'all() must be implemented by the connector'); @@ -1528,8 +1528,8 @@ DataAccessObject.find = function find(query, options, cb) { this.applyScope(query); - var near = query && geo.nearFilter(query.where); - var supportsGeo = !!connector.buildNearFilter; + const near = query && geo.nearFilter(query.where); + const supportsGeo = !!connector.buildNearFilter; if (near) { if (supportsGeo) { @@ -1546,7 +1546,7 @@ DataAccessObject.find = function find(query, options, cb) { } function withNotifyGeo() { - var context = { + const context = { Model: self, query: query, hookState: hookState, @@ -1560,8 +1560,8 @@ DataAccessObject.find = function find(query, options, cb) { function queryGeo(query) { function geoCallbackWithoutNotify(err, data) { - var memory = new Memory(); - var modelName = self.modelName; + const memory = new Memory(); + const modelName = self.modelName; if (err) { cb(err); @@ -1589,7 +1589,7 @@ DataAccessObject.find = function find(query, options, cb) { if (err) return cb(err); async.map(data, function(item, next) { - var context = { + const context = { Model: self, data: item, isNewInstance: false, @@ -1607,7 +1607,7 @@ DataAccessObject.find = function find(query, options, cb) { }); } - var geoCallback = options.notify === false ? geoCallbackWithoutNotify : geoCallbackWithNotify; + const geoCallback = options.notify === false ? geoCallbackWithoutNotify : geoCallbackWithNotify; invokeConnectorMethod(connector, 'all', self, [{}], options, geoCallback); } // already handled @@ -1615,10 +1615,10 @@ DataAccessObject.find = function find(query, options, cb) { } } - var allCb = function(err, data) { + const allCb = function(err, data) { if (!err && Array.isArray(data)) { async.map(data, function(item, next) { - var Model = self.lookupModel(item); + const Model = self.lookupModel(item); if (options.notify === false) { buildResult(item, next); } else { @@ -1626,12 +1626,12 @@ DataAccessObject.find = function find(query, options, cb) { } function buildResult(data, callback) { - var ctorOpts = { + const ctorOpts = { fields: query.fields, applySetters: false, persisted: true, }; - var obj; + let obj; try { obj = new Model(data, ctorOpts); } catch (err) { @@ -1651,15 +1651,15 @@ DataAccessObject.find = function find(query, options, cb) { // This handles the case to return parent items including the related // models. For example, Article.find({include: 'tags'}, ...); // Try to normalize the include - var includes = Inclusion.normalizeInclude(query.include || []); + const includes = Inclusion.normalizeInclude(query.include || []); includes.forEach(function(inc) { - var relationName = inc; + let relationName = inc; if (utils.isPlainObject(inc)) { relationName = Object.keys(inc)[0]; } // Promote the included model as a direct property - var included = obj.__cachedRelations[relationName]; + let included = obj.__cachedRelations[relationName]; if (Array.isArray(included)) { included = new List(included, null, obj); } @@ -1673,7 +1673,7 @@ DataAccessObject.find = function find(query, options, cb) { } function withNotify(data, callback) { - var context = { + const context = { Model: Model, data: data, isNewInstance: false, @@ -1713,7 +1713,7 @@ DataAccessObject.find = function find(query, options, cb) { if (options.notify === false) { invokeConnectorMethod(connector, 'all', self, [query], options, allCb); } else { - var context = { + const context = { Model: this, query: query, hookState: hookState, @@ -1740,7 +1740,7 @@ function isDefined(value) { * @param {Function} cb Callback function called with (err, instance) */ DataAccessObject.findOne = function findOne(query, options, cb) { - var connectionPromise = stillConnecting(this.getDataSource(), this, arguments); + const connectionPromise = stillConnecting(this.getDataSource(), this, arguments); if (connectionPromise) { return connectionPromise; } @@ -1790,13 +1790,13 @@ DataAccessObject.findOne = function findOne(query, options, cb) { DataAccessObject.remove = DataAccessObject.deleteAll = DataAccessObject.destroyAll = function destroyAll(where, options, cb) { - var connectionPromise = stillConnecting(this.getDataSource(), this, arguments); + const connectionPromise = stillConnecting(this.getDataSource(), this, arguments); if (connectionPromise) { return connectionPromise; } - var Model = this; - var connector = Model.getConnector(); + const Model = this; + const connector = Model.getConnector(); assert(typeof connector.destroyAll === 'function', 'destroyAll() must be implemented by the connector'); @@ -1821,9 +1821,9 @@ DataAccessObject.destroyAll = function destroyAll(where, options, cb) { assert(typeof options === 'object', 'The options argument must be an object'); assert(typeof cb === 'function', 'The cb argument must be a function'); - var hookState = {}; + const hookState = {}; - var query = {where: where}; + let query = {where: where}; this.applyScope(query); where = query.where; @@ -1832,7 +1832,7 @@ DataAccessObject.destroyAll = function destroyAll(where, options, cb) { doDelete(where); } else { query = {where: whereIsEmpty(where) ? {} : where}; - var context = { + const context = { Model: Model, query: query, hookState: hookState, @@ -1840,7 +1840,7 @@ DataAccessObject.destroyAll = function destroyAll(where, options, cb) { }; Model.notifyObserversOf('access', context, function(err, ctx) { if (err) return cb(err); - var context = { + const context = { Model: Model, where: ctx.query.where, hookState: hookState, @@ -1854,7 +1854,7 @@ DataAccessObject.destroyAll = function destroyAll(where, options, cb) { } function doDelete(where) { - var context = { + const context = { Model: Model, where: whereIsEmpty(where) ? {} : where, hookState: hookState, @@ -1885,7 +1885,7 @@ DataAccessObject.destroyAll = function destroyAll(where, options, cb) { return cb(err, info); } - var context = { + const context = { Model: Model, where: where, hookState: hookState, @@ -1918,7 +1918,7 @@ function whereIsEmpty(where) { DataAccessObject.removeById = DataAccessObject.destroyById = DataAccessObject.deleteById = function deleteById(id, options, cb) { - var connectionPromise = stillConnecting(this.getDataSource(), this, arguments); + const connectionPromise = stillConnecting(this.getDataSource(), this, arguments); if (connectionPromise) { return connectionPromise; } @@ -1947,11 +1947,11 @@ DataAccessObject.deleteById = function deleteById(id, options, cb) { return cb.promise; } - var Model = this; + const Model = this; this.remove(byIdQuery(this, id).where, options, function(err, info) { if (err) return cb(err); - var deleted = info && info.count > 0; + const deleted = info && info.count > 0; if (Model.settings.strictDelete && !deleted) { err = new Error(g.f('No instance with {{id}} %s found for %s', id, Model.modelName)); err.code = 'NOT_FOUND'; @@ -1979,7 +1979,7 @@ DataAccessObject.deleteById = function deleteById(id, options, cb) { * @param {Function} cb Callback, called with (err, count) */ DataAccessObject.count = function(where, options, cb) { - var connectionPromise = stillConnecting(this.getDataSource(), this, arguments); + const connectionPromise = stillConnecting(this.getDataSource(), this, arguments); if (connectionPromise) { return connectionPromise; } @@ -2006,16 +2006,16 @@ DataAccessObject.count = function(where, options, cb) { assert(typeof options === 'object', 'The options argument must be an object'); assert(typeof cb === 'function', 'The cb argument must be a function'); - var Model = this; - var connector = Model.getConnector(); + const Model = this; + const connector = Model.getConnector(); assert(typeof connector.count === 'function', 'count() must be implemented by the connector'); assert(connector.count.length >= 3, 'count() must take at least 3 arguments'); - var hookState = {}; + const hookState = {}; - var query = {where: where}; + const query = {where: where}; this.applyScope(query); where = query.where; @@ -2030,7 +2030,7 @@ DataAccessObject.count = function(where, options, cb) { return cb.promise; } - var context = { + const context = { Model: Model, query: {where: where}, hookState: hookState, @@ -2052,11 +2052,11 @@ DataAccessObject.count = function(where, options, cb) { * @param {Function} cb Callback function with err and object arguments */ DataAccessObject.prototype.save = function(options, cb) { - var connectionPromise = stillConnecting(this.getDataSource(), this, arguments); + const connectionPromise = stillConnecting(this.getDataSource(), this, arguments); if (connectionPromise) { return connectionPromise; } - var Model = this.constructor; + const Model = this.constructor; if (typeof options === 'function') { cb = options; @@ -2075,7 +2075,7 @@ DataAccessObject.prototype.save = function(options, cb) { return Model.create(this, options, cb); } - var hookState = {}; + const hookState = {}; if (options.validate === undefined) { if (Model.settings.automaticValidation === undefined) { @@ -2089,10 +2089,10 @@ DataAccessObject.prototype.save = function(options, cb) { options.throws = false; } - var inst = this; - var connector = inst.getConnector(); + const inst = this; + const connector = inst.getConnector(); - var context = { + let context = { Model: Model, instance: inst, hookState: hookState, @@ -2101,7 +2101,7 @@ DataAccessObject.prototype.save = function(options, cb) { Model.notifyObserversOf('before save', context, function(err) { if (err) return cb(err); - var data = inst.toObject(true); + let data = inst.toObject(true); Model.applyProperties(data, inst); inst.setAttributes(data); @@ -2114,7 +2114,7 @@ DataAccessObject.prototype.save = function(options, cb) { if (valid) { save(); } else { - var err = new ValidationError(inst); + const err = new ValidationError(inst); // throws option is dangerous for async usage if (options.throws) { throw err; @@ -2133,7 +2133,7 @@ DataAccessObject.prototype.save = function(options, cb) { return cb(err, inst); } - var context = { + const context = { Model: Model, data: data, isNewInstance: result && result.isNewInstance, @@ -2146,7 +2146,7 @@ DataAccessObject.prototype.save = function(options, cb) { data = ctx.data; inst._initProperties(data, {persisted: true}); - var context = { + const context = { Model: Model, instance: inst, isNewInstance: result && result.isNewInstance, @@ -2204,7 +2204,7 @@ DataAccessObject.prototype.save = function(options, cb) { */ DataAccessObject.update = DataAccessObject.updateAll = function(where, data, options, cb) { - var connectionPromise = stillConnecting(this.getDataSource(), this, arguments); + const connectionPromise = stillConnecting(this.getDataSource(), this, arguments); if (connectionPromise) { return connectionPromise; } @@ -2242,18 +2242,18 @@ DataAccessObject.updateAll = function(where, data, options, cb) { assert(typeof options === 'object', 'The options argument must be an object'); assert(typeof cb === 'function', 'The cb argument must be a function'); - var Model = this; - var connector = Model.getDataSource().connector; + const Model = this; + const connector = Model.getDataSource().connector; assert(typeof connector.update === 'function', 'update() must be implemented by the connector'); - var hookState = {}; + const hookState = {}; - var query = {where: where}; + const query = {where: where}; this.applyScope(query); this.applyProperties(data); - var doValidate = false; + let doValidate = false; if (options.validate === undefined) { if (Model.settings.validateUpdate === undefined) { if (Model.settings.automaticValidation !== undefined) { @@ -2268,7 +2268,7 @@ DataAccessObject.updateAll = function(where, data, options, cb) { where = query.where; - var context = { + const context = { Model: Model, query: {where: where}, hookState: hookState, @@ -2276,7 +2276,7 @@ DataAccessObject.updateAll = function(where, data, options, cb) { }; Model.notifyObserversOf('access', context, function(err, ctx) { if (err) return cb(err); - var context = { + const context = { Model: Model, where: ctx.query.where, data: data, @@ -2288,7 +2288,7 @@ DataAccessObject.updateAll = function(where, data, options, cb) { if (err) return cb(err); data = ctx.data; - var inst = data; + let inst = data; if (!(data instanceof Model)) { try { inst = new Model(data, {applyDefaultValues: false}); @@ -2327,7 +2327,7 @@ DataAccessObject.updateAll = function(where, data, options, cb) { function updateCallback(err, info) { if (err) return cb(err); - var context = { + const context = { Model: Model, where: where, data: data, @@ -2340,7 +2340,7 @@ DataAccessObject.updateAll = function(where, data, options, cb) { }); } - var context = { + const context = { Model: Model, where: where, data: data, @@ -2379,7 +2379,7 @@ DataAccessObject.prototype.getConnector = function() { DataAccessObject.prototype.remove = DataAccessObject.prototype.delete = DataAccessObject.prototype.destroy = function(options, cb) { - var connectionPromise = stillConnecting(this.getDataSource(), this, arguments); + const connectionPromise = stillConnecting(this.getDataSource(), this, arguments); if (connectionPromise) { return connectionPromise; } @@ -2395,17 +2395,17 @@ DataAccessObject.prototype.remove = assert(typeof options === 'object', 'The options argument should be an object'); assert(typeof cb === 'function', 'The cb argument should be a function'); - var inst = this; - var connector = this.getConnector(); + const inst = this; + const connector = this.getConnector(); - var Model = this.constructor; - var id = getIdValue(this.constructor, this); - var hookState = {}; + const Model = this.constructor; + const id = getIdValue(this.constructor, this); + const hookState = {}; if (isPKMissing(Model, cb)) return cb.promise; - var context = { + const context = { Model: Model, query: byIdQuery(Model, id), hookState: hookState, @@ -2414,7 +2414,7 @@ DataAccessObject.prototype.remove = Model.notifyObserversOf('access', context, function(err, ctx) { if (err) return cb(err); - var context = { + const context = { Model: Model, where: ctx.query.where, instance: inst, @@ -2434,14 +2434,14 @@ DataAccessObject.prototype.remove = // We must switch to full query-based delete. Model.deleteAll(where, {notify: false}, function(err, info) { if (err) return cb(err, false); - var deleted = info && info.count > 0; + const deleted = info && info.count > 0; if (Model.settings.strictDelete && !deleted) { err = new Error(g.f('No instance with {{id}} %s found for %s', id, Model.modelName)); err.code = 'NOT_FOUND'; err.statusCode = 404; return cb(err, false); } - var context = { + const context = { Model: Model, where: where, instance: inst, @@ -2459,7 +2459,7 @@ DataAccessObject.prototype.remove = inst.trigger('destroy', function(destroyed) { function destroyCallback(err, info) { if (err) return cb(err); - var deleted = info && info.count > 0; + const deleted = info && info.count > 0; if (Model.settings.strictDelete && !deleted) { err = new Error(g.f('No instance with {{id}} %s found for %s', id, Model.modelName)); err.code = 'NOT_FOUND'; @@ -2468,7 +2468,7 @@ DataAccessObject.prototype.remove = } destroyed(function() { - var context = { + const context = { Model: Model, where: where, instance: inst, @@ -2508,7 +2508,7 @@ DataAccessObject.prototype.setAttribute = function setAttribute(name, value) { * @param {Function} cb Callback function called with (err, instance) */ DataAccessObject.prototype.updateAttribute = function updateAttribute(name, value, options, cb) { - var data = {}; + const data = {}; data[name] = value; return this.updateAttributes(data, options, cb); }; @@ -2524,11 +2524,11 @@ DataAccessObject.prototype.setAttributes = function setAttributes(data) { this.constructor.applyProperties(data, this); - var Model = this.constructor; - var inst = this; + const Model = this.constructor; + const inst = this; // update instance's properties - for (var key in data) { + for (const key in data) { inst.setAttribute(key, data[key]); } @@ -2554,13 +2554,13 @@ DataAccessObject.prototype.unsetAttribute = function unsetAttribute(name, nullif * @param {Function} cb Callback function called with (err, instance) */ DataAccessObject.prototype.replaceAttributes = function(data, options, cb) { - var Model = this.constructor; - var id = getIdValue(this.constructor, this); + const Model = this.constructor; + const id = getIdValue(this.constructor, this); return Model.replaceById(id, data, options, cb); }; DataAccessObject.replaceById = function(id, data, options, cb) { - var connectionPromise = stillConnecting(this.getDataSource(), this, arguments); + const connectionPromise = stillConnecting(this.getDataSource(), this, arguments); if (connectionPromise) { return connectionPromise; } @@ -2580,9 +2580,9 @@ DataAccessObject.replaceById = function(id, data, options, cb) { assert(typeof options === 'object', 'The options argument must be an object'); assert(typeof cb === 'function', 'The cb argument must be a function'); - var connector = this.getConnector(); + const connector = this.getConnector(); - var err; + let err; if (typeof connector.replaceById !== 'function') { err = new Error(g.f( 'The connector %s does not support {{replaceById}} operation. This is not a bug in LoopBack. ' + @@ -2592,12 +2592,12 @@ DataAccessObject.replaceById = function(id, data, options, cb) { return cb(err); } - var pkName = idName(this); + const pkName = idName(this); if (!data[pkName]) data[pkName] = id; try { var Model = this; var inst = new Model(data, {persisted: true}); - var enforced = {}; + const enforced = {}; this.applyProperties(enforced, inst); inst.setAttributes(enforced); @@ -2607,12 +2607,12 @@ DataAccessObject.replaceById = function(id, data, options, cb) { Model = this.lookupModel(data); // data-specific if (Model !== inst.constructor) inst = new Model(data); - var strict = inst.__strict; + const strict = inst.__strict; if (isPKMissing(Model, cb)) return cb.promise; - var hookState = {}; + const hookState = {}; if (id !== data[pkName]) { err = new Error(g.f('{{id}} property (%s) ' + @@ -2622,7 +2622,7 @@ DataAccessObject.replaceById = function(id, data, options, cb) { return cb.promise; } - var context = { + let context = { Model: Model, instance: inst, isNewInstance: false, @@ -2653,7 +2653,7 @@ DataAccessObject.replaceById = function(id, data, options, cb) { // update instance's properties inst.setAttributes(data); - var doValidate = true; + let doValidate = true; if (options.validate === undefined) { if (Model.settings.automaticValidation !== undefined) { doValidate = Model.settings.automaticValidation; @@ -2674,7 +2674,7 @@ DataAccessObject.replaceById = function(id, data, options, cb) { function callConnector() { copyData(data, inst); - var typedData = convertSubsetOfPropertiesByType(inst, data); + const typedData = convertSubsetOfPropertiesByType(inst, data); context.data = typedData; // Depending on the connector, the database response can @@ -2687,7 +2687,7 @@ DataAccessObject.replaceById = function(id, data, options, cb) { if (typeof connector.generateContextData === 'function') { context = connector.generateContextData(context, dbResponse); } - var ctx = { + const ctx = { Model: Model, hookState: hookState, data: context.data, @@ -2708,7 +2708,7 @@ DataAccessObject.replaceById = function(id, data, options, cb) { ctx.data[pkName] = id; inst.setAttributes(ctx.data); - var context = { + const context = { Model: Model, instance: inst, isNewInstance: false, @@ -2721,7 +2721,7 @@ DataAccessObject.replaceById = function(id, data, options, cb) { }); } - var ctx = { + const ctx = { Model: Model, where: byIdQuery(Model, id).where, data: context.data, @@ -2756,8 +2756,8 @@ DataAccessObject.replaceById = function(id, data, options, cb) { DataAccessObject.prototype.updateAttributes = DataAccessObject.prototype.patchAttributes = function(data, options, cb) { - var self = this; - var connectionPromise = stillConnecting(this.getDataSource(), this, arguments); + const self = this; + const connectionPromise = stillConnecting(this.getDataSource(), this, arguments); if (connectionPromise) { return connectionPromise; } @@ -2784,18 +2784,18 @@ function(data, options, cb) { assert(typeof options === 'object', 'The options argument must be an object'); assert(typeof cb === 'function', 'The cb argument must be a function'); - var inst = this; - var Model = this.constructor; - var connector = inst.getConnector(); + const inst = this; + const Model = this.constructor; + const connector = inst.getConnector(); assert(typeof connector.updateAttributes === 'function', 'updateAttributes() must be implemented by the connector'); if (isPKMissing(Model, cb)) return cb.promise; - var allowExtendedOperators = Model._allowExtendedOperators(options); - var strict = this.__strict; - var hookState = {}; + const allowExtendedOperators = Model._allowExtendedOperators(options); + const strict = this.__strict; + const hookState = {}; // Convert the data to be plain object so that update won't be confused if (data instanceof Model) { @@ -2804,9 +2804,9 @@ function(data, options, cb) { data = Model._sanitizeData(data, options); // Make sure id(s) cannot be changed - var idNames = Model.definition.idNames(); - for (var i = 0, n = idNames.length; i < n; i++) { - var idName = idNames[i]; + const idNames = Model.definition.idNames(); + for (let i = 0, n = idNames.length; i < n; i++) { + const idName = idNames[i]; if (data[idName] !== undefined && !idEquals(data[idName], inst[idName])) { var err = new Error(g.f('{{id}} cannot be updated from ' + '%s to %s when {{forceId}} is set to true', @@ -2819,7 +2819,7 @@ function(data, options, cb) { } } - var context = { + let context = { Model: Model, where: byIdQuery(Model, getIdValue(Model, inst)).where, data: data, @@ -2840,7 +2840,7 @@ function(data, options, cb) { function validateAndSave(err, data) { if (err) return cb(err); - var doValidate = true; + let doValidate = true; if (options.validate === undefined) { if (Model.settings.automaticValidation !== undefined) { doValidate = Model.settings.automaticValidation; @@ -2873,7 +2873,7 @@ function(data, options, cb) { inst.trigger('save', function(saveDone) { inst.trigger('update', function(done) { copyData(data, inst); - var typedData = convertSubsetOfPropertiesByType(inst, data); + const typedData = convertSubsetOfPropertiesByType(inst, data); context.data = Model._sanitizeData(typedData, options); // Depending on the connector, the database response can @@ -2884,7 +2884,7 @@ function(data, options, cb) { if (typeof connector.generateContextData === 'function') { context = connector.generateContextData(context, dbResponse); } - var ctx = { + const ctx = { Model: Model, data: context.data, hookState: hookState, @@ -2907,7 +2907,7 @@ function(data, options, cb) { saveDone.call(inst, function() { if (err) return cb(err, inst); - var context = { + const context = { Model: Model, instance: inst, isNewInstance: false, @@ -2922,7 +2922,7 @@ function(data, options, cb) { }); } - var ctx = { + const ctx = { Model: Model, where: byIdQuery(Model, getIdValue(Model, inst)).where, data: context.data, @@ -2954,7 +2954,7 @@ function(data, options, cb) { * @private */ DataAccessObject.prototype.reload = function reload(cb) { - var connectionPromise = stillConnecting(this.getDataSource(), this, arguments); + const connectionPromise = stillConnecting(this.getDataSource(), this, arguments); if (connectionPromise) { return connectionPromise; } @@ -2979,7 +2979,7 @@ function defineReadonlyProp(obj, key, value) { }); } -var defineScope = require('./scope.js').defineScope; +const defineScope = require('./scope.js').defineScope; /** * Define a scope for the model class. Scopes enable you to specify commonly-used @@ -2991,7 +2991,7 @@ var defineScope = require('./scope.js').defineScope; * the declaring model */ DataAccessObject.scope = function(name, query, targetClass, methods, options) { - var cls = this; + let cls = this; if (options && options.isStatic === false) { cls = cls.prototype; } @@ -3020,7 +3020,7 @@ function PKMissingError(modelName) { PKMissingError.prototype = new Error(); function isPKMissing(modelClass, cb) { - var hasPK = modelClass.definition.hasPK(); + const hasPK = modelClass.definition.hasPK(); if (hasPK) return false; process.nextTick(function() { cb(new PKMissingError(modelClass.modelName)); diff --git a/lib/datasource.js b/lib/datasource.js index f97afd1d..fa300e36 100644 --- a/lib/datasource.js +++ b/lib/datasource.js @@ -10,30 +10,30 @@ /*! * Module dependencies */ -var ModelBuilder = require('./model-builder.js').ModelBuilder; -var ModelDefinition = require('./model-definition.js'); -var RelationDefinition = require('./relation-definition.js'); -var OberserverMixin = require('./observer'); -var jutil = require('./jutil'); -var utils = require('./utils'); -var ModelBaseClass = require('./model.js'); -var DataAccessObject = require('./dao.js'); -var defineScope = require('./scope.js').defineScope; -var EventEmitter = require('events').EventEmitter; -var util = require('util'); -var assert = require('assert'); -var async = require('async'); -var traverse = require('traverse'); -var g = require('strong-globalize')(); -var juggler = require('..'); -var deprecated = require('depd')('loopback-datasource-juggler'); -var Transaction = require('loopback-connector').Transaction; +const ModelBuilder = require('./model-builder.js').ModelBuilder; +const ModelDefinition = require('./model-definition.js'); +const RelationDefinition = require('./relation-definition.js'); +const OberserverMixin = require('./observer'); +const jutil = require('./jutil'); +const utils = require('./utils'); +const ModelBaseClass = require('./model.js'); +const DataAccessObject = require('./dao.js'); +const defineScope = require('./scope.js').defineScope; +const EventEmitter = require('events').EventEmitter; +const util = require('util'); +const assert = require('assert'); +const async = require('async'); +const traverse = require('traverse'); +const g = require('strong-globalize')(); +const juggler = require('..'); +const deprecated = require('depd')('loopback-datasource-juggler'); +const Transaction = require('loopback-connector').Transaction; if (process.env.DEBUG === 'loopback') { // For back-compatibility process.env.DEBUG = 'loopback:*'; } -var debug = require('debug')('loopback:datasource'); +const debug = require('debug')('loopback:datasource'); /*! * Export public API @@ -43,7 +43,7 @@ exports.DataSource = DataSource; /*! * Helpers */ -var slice = Array.prototype.slice; +const slice = Array.prototype.slice; /** * LoopBack models can manipulate data via the DataSource object. @@ -140,16 +140,16 @@ function DataSource(name, settings, modelBuilder) { this._setupConnector(); // connector - var connector = this.connector; + const connector = this.connector; // DataAccessObject - connector defined or supply the default - var dao = (connector && connector.DataAccessObject) || this.constructor.DataAccessObject; + const dao = (connector && connector.DataAccessObject) || this.constructor.DataAccessObject; this.DataAccessObject = function() { }; // define DataAccessObject methods Object.keys(dao).forEach(function(name) { - var fn = dao[name]; + const fn = dao[name]; this.DataAccessObject[name] = fn; if (typeof fn === 'function') { @@ -166,7 +166,7 @@ function DataSource(name, settings, modelBuilder) { // define DataAccessObject.prototype methods Object.keys(dao.prototype || []).forEach(function(name) { - var fn = dao.prototype[name]; + const fn = dao.prototype[name]; this.DataAccessObject.prototype[name] = fn; if (typeof fn === 'function') { this.defineOperation(name, { @@ -199,14 +199,14 @@ DataSource.prototype._setupConnector = function() { // Set up the dataSource if the connector doesn't do so this.connector.dataSource = this; } - var dataSource = this; + const dataSource = this; this.connector.log = function(query, start) { dataSource.log(query, start); }; this.connector.logger = function(query) { - var t1 = Date.now(); - var log = this.log; + const t1 = Date.now(); + const log = this.log; return function(q) { log(q || query, t1); }; @@ -218,7 +218,7 @@ DataSource.prototype._setupConnector = function() { // List possible connector module names function connectorModuleNames(name) { - var names = []; // Check the name as is + const names = []; // Check the name as is if (!name.match(/^\//)) { names.push('./connectors/' + name); // Check built-in connectors if (name.indexOf('loopback-connector-') !== 0) { @@ -235,13 +235,13 @@ function connectorModuleNames(name) { // testable with DI function tryModules(names, loader) { - var mod; + let mod; loader = loader || require; - for (var m = 0; m < names.length; m++) { + for (let m = 0; m < names.length; m++) { try { mod = loader(names[m]); } catch (e) { - var notFound = e.code === 'MODULE_NOT_FOUND' && + const notFound = e.code === 'MODULE_NOT_FOUND' && e.message && e.message.indexOf(names[m]) > 0; if (notFound) { @@ -266,9 +266,9 @@ function tryModules(names, loader) { * @private */ DataSource._resolveConnector = function(name, loader) { - var names = connectorModuleNames(name); - var connector = tryModules(names, loader); - var error = null; + const names = connectorModuleNames(name); + const connector = tryModules(names, loader); + let error = null; if (!connector) { error = g.f('\nWARNING: {{LoopBack}} connector "%s" is not installed ' + 'as any of the following modules:\n\n %s\n\nTo fix, run:\n\n {{npm install %s --save}}\n', @@ -290,7 +290,7 @@ DataSource._resolveConnector = function(name, loader) { */ DataSource.prototype.connect = function(callback) { callback = callback || utils.createPromiseCallback(); - var self = this; + const self = this; if (this.connected) { // The data source is already connected, return immediately process.nextTick(callback); @@ -317,7 +317,7 @@ DataSource.prototype.connect = function(callback) { this.connector.connect(function(err, result) { self.connecting = false; if (!err) self.connected = true; - var cbs = self.pendingConnectCallbacks; + const cbs = self.pendingConnectCallbacks; self.pendingConnectCallbacks = []; if (!err) { self.emit('connected'); @@ -362,8 +362,8 @@ DataSource.prototype.connect = function(callback) { * @private */ DataSource.prototype.setup = function(dsName, settings) { - var dataSource = this; - var connector; + const dataSource = this; + let connector; // First argument is an `object` if (dsName && typeof dsName === 'object') { @@ -424,7 +424,7 @@ DataSource.prototype.setup = function(dsName, settings) { this.name = dsName || (typeof this.settings.name === 'string' && this.settings.name); - var connectorName; + let connectorName; if (typeof connector === 'string') { // Connector needs to be resolved by name connectorName = connector; @@ -441,7 +441,7 @@ DataSource.prototype.setup = function(dsName, settings) { if ((!connector) && connectorName) { // The connector has not been resolved - var result = DataSource._resolveConnector(connectorName); + const result = DataSource._resolveConnector(connectorName); connector = result.connector; if (!connector) { console.error(result.error); @@ -451,7 +451,7 @@ DataSource.prototype.setup = function(dsName, settings) { } if (connector) { - var postInit = function postInit(err, result) { + const postInit = function postInit(err, result) { this._setupConnector(); // we have an connector now? if (!this.connector) { @@ -532,7 +532,7 @@ function isModelDataSourceAttached(model) { */ DataSource.prototype.defineScopes = function(modelClass, scopes) { if (scopes) { - for (var s in scopes) { + for (const s in scopes) { defineScope(modelClass, modelClass, s, scopes[s], {}, scopes[s].options); } } @@ -547,16 +547,16 @@ DataSource.prototype.defineScopes = function(modelClass, scopes) { * object definitions. */ DataSource.prototype.defineRelations = function(modelClass, relations) { - var self = this; + const self = this; // Wait for target/through models to be attached before setting up the relation - var deferRelationSetup = function(relationName, relation, targetModel, throughModel) { + const deferRelationSetup = function(relationName, relation, targetModel, throughModel) { if (!isModelDataSourceAttached(targetModel)) { targetModel.once('dataAccessConfigured', function(targetModel) { // Check if the through model doesn't exist or resolved if (!throughModel || isModelDataSourceAttached(throughModel)) { // The target model is resolved - var params = traverse(relation).clone(); + const params = traverse(relation).clone(); params.as = relationName; params.model = targetModel; if (throughModel) { @@ -572,7 +572,7 @@ DataSource.prototype.defineRelations = function(modelClass, relations) { throughModel.once('dataAccessConfigured', function(throughModel) { if (isModelDataSourceAttached(targetModel)) { // The target model is resolved - var params = traverse(relation).clone(); + const params = traverse(relation).clone(); params.as = relationName; params.model = targetModel; params.through = throughModel; @@ -585,8 +585,8 @@ DataSource.prototype.defineRelations = function(modelClass, relations) { // Set up the relations if (relations) { Object.keys(relations).forEach(function(relationName) { - var targetModel; - var r = relations[relationName]; + let targetModel; + const r = relations[relationName]; validateRelation(relationName, r); @@ -594,7 +594,7 @@ DataSource.prototype.defineRelations = function(modelClass, relations) { targetModel = isModelClass(r.model) ? r.model : self.getModel(r.model, true); } - var throughModel = null; + let throughModel = null; if (r.through) { throughModel = isModelClass(r.through) ? r.through : self.getModel(r.through, true); } @@ -605,7 +605,7 @@ DataSource.prototype.defineRelations = function(modelClass, relations) { deferRelationSetup(relationName, r, targetModel, throughModel); } else { // The target model is resolved - var params = traverse(r).clone(); + const params = traverse(r).clone(); params.as = relationName; params.model = targetModel; if (throughModel) { @@ -618,9 +618,9 @@ DataSource.prototype.defineRelations = function(modelClass, relations) { }; function validateRelation(relationName, relation) { - var rn = relationName; - var r = relation; - var msg, code; + const rn = relationName; + const r = relation; + let msg, code; assert(DataSource.relationTypes.indexOf(r.type) !== -1, 'Invalid relation type: ' + r.type); assert(isValidRelationName(rn), 'Invalid relation name: ' + rn); @@ -668,7 +668,7 @@ function validateRelation(relationName, relation) { } if (msg) { - var error = new Error(msg); + const error = new Error(msg); error.details = {code: code, rType: r.type, rName: rn}; throw error; } @@ -683,7 +683,7 @@ function validateRelation(relationName, relation) { } function isValidRelationName(relationName) { - var invalidRelationNames = ['trigger']; + const invalidRelationNames = ['trigger']; return invalidRelationNames.indexOf(relationName) === -1; } @@ -697,11 +697,11 @@ function isValidRelationName(relationName) { DataSource.prototype.setupDataAccess = function(modelClass, settings) { if (this.connector) { // Check if the id property should be generated - var idName = modelClass.definition.idName(); - var idProp = modelClass.definition.rawProperties[idName]; + const idName = modelClass.definition.idName(); + const idProp = modelClass.definition.rawProperties[idName]; if (idProp && idProp.generated && this.connector.getDefaultIdType) { // Set the default id type from connector's ability - var idType = this.connector.getDefaultIdType() || String; + const idType = this.connector.getDefaultIdType() || String; idProp.type = idType; modelClass.definition.rawProperties[idName].type = idType; modelClass.definition.properties[idName].type = idType; @@ -720,7 +720,7 @@ DataSource.prototype.setupDataAccess = function(modelClass, settings) { this.mixin(modelClass); // define relations from LDL (options.relations) - var relations = settings.relationships || settings.relations; + const relations = settings.relationships || settings.relations; this.defineRelations(modelClass, relations); // Emit the dataAccessConfigured event to indicate all the methods for data @@ -728,7 +728,7 @@ DataSource.prototype.setupDataAccess = function(modelClass, settings) { modelClass.emit('dataAccessConfigured', modelClass); // define scopes from LDL (options.relations) - var scopes = settings.scopes || {}; + const scopes = settings.scopes || {}; this.defineScopes(modelClass, scopes); }; @@ -783,7 +783,7 @@ DataSource.prototype.setupDataAccess = function(modelClass, settings) { DataSource.prototype.createModel = DataSource.prototype.define = function defineClass(className, properties, settings) { - var args = slice.call(arguments); + const args = slice.call(arguments); if (!className) { throw new Error(g.f('Class name required')); @@ -810,7 +810,7 @@ DataSource.prototype.define = function defineClass(className, properties, settin } } - var modelClass = this.modelBuilder.define(className, properties, settings); + const modelClass = this.modelBuilder.define(className, properties, settings); modelClass.dataSource = this; if (settings.unresolved) { @@ -841,16 +841,16 @@ DataSource.prototype.deleteModelByName = function(modelName) { */ DataSource.prototype.mixin = function(ModelCtor) { - var ops = this.operations(); - var DAO = this.DataAccessObject; + const ops = this.operations(); + const DAO = this.DataAccessObject; // mixin DAO jutil.mixin(ModelCtor, DAO, {proxyFunctions: true, override: true}); // decorate operations as alias functions Object.keys(ops).forEach(function(name) { - var op = ops[name]; - var scope; + const op = ops[name]; + let scope; if (op.enabled) { scope = op.prototype ? ModelCtor.prototype : ModelCtor; @@ -908,8 +908,8 @@ DataSource.prototype.getModelDefinition = function(name) { * no subtype. */ DataSource.prototype.getTypes = function() { - var getTypes = this.connector && this.connector.getTypes; - var types = getTypes && getTypes() || []; + const getTypes = this.connector && this.connector.getTypes; + let types = getTypes && getTypes() || []; if (typeof types === 'string') { types = types.split(/[\s,\/]+/); } @@ -922,10 +922,10 @@ DataSource.prototype.getTypes = function() { * @returns {Boolean} true if all types are supported by the data source */ DataSource.prototype.supportTypes = function(types) { - var supportedTypes = this.getTypes(); + const supportedTypes = this.getTypes(); if (Array.isArray(types)) { // Check each of the types - for (var i = 0; i < types.length; i++) { + for (let i = 0; i < types.length; i++) { if (supportedTypes.indexOf(types[i]) === -1) { // Not supported return false; @@ -983,7 +983,7 @@ DataSource.prototype.attach = function(modelClass) { DataSource.prototype.defineProperty = function(model, prop, params) { this.modelBuilder.defineProperty(model, prop, params); - var resolvedProp = this.getModelDefinition(model).properties[prop]; + const resolvedProp = this.getModelDefinition(model).properties[prop]; if (this.connector && this.connector.defineProperty) { this.connector.defineProperty(model, prop, resolvedProp); } @@ -1024,7 +1024,7 @@ DataSource.prototype.automigrate = function(models, cb) { models = [models]; } - var attachedModels = this.connector._models; + const attachedModels = this.connector._models; if (attachedModels && typeof attachedModels === 'object') { models = models || Object.keys(attachedModels); @@ -1034,7 +1034,7 @@ DataSource.prototype.automigrate = function(models, cb) { return cb.promise; } - var invalidModels = models.filter(function(m) { + const invalidModels = models.filter(function(m) { return !(m in attachedModels); }); @@ -1085,7 +1085,7 @@ DataSource.prototype.autoupdate = function(models, cb) { models = [models]; } - var attachedModels = this.connector._models; + const attachedModels = this.connector._models; if (attachedModels && typeof attachedModels === 'object') { models = models || Object.keys(attachedModels); @@ -1095,7 +1095,7 @@ DataSource.prototype.autoupdate = function(models, cb) { return cb.promise; } - var invalidModels = models.filter(function(m) { + const invalidModels = models.filter(function(m) { return !(m in attachedModels); }); @@ -1406,10 +1406,10 @@ function fromDBName(dbName, camelCase) { if (!dbName) { return dbName; } - var parts = dbName.split(/-|_/); + const parts = dbName.split(/-|_/); parts[0] = camelCase ? parts[0].toLowerCase() : capitalize(parts[0]); - for (var i = 1; i < parts.length; i++) { + for (let i = 1; i < parts.length; i++) { parts[i] = capitalize(parts[i]); } return parts.join(''); @@ -1492,7 +1492,7 @@ DataSource.prototype.discoverSchema = function(tableName, options, cb) { cb && cb(err, schemas); return; } - for (var s in schemas) { + for (const s in schemas) { cb && cb(null, schemas[s]); return; } @@ -1522,10 +1522,10 @@ DataSource.prototype.discoverSchemas = function(tableName, options, cb) { cb = cb || utils.createPromiseCallback(); - var self = this; - var dbType = this.connector.name; + const self = this; + const dbType = this.connector.name; - var nameMapper; + let nameMapper; if (options.nameMapper === null) { // No mapping nameMapper = function(type, name) { @@ -1553,11 +1553,11 @@ DataSource.prototype.discoverSchemas = function(tableName, options, cb) { return cb.promise; } - var tasks = [ + const tasks = [ this.discoverModelProperties.bind(this, tableName, options), this.discoverPrimaryKeys.bind(this, tableName, options)]; - var followingRelations = options.associations || options.relations; + const followingRelations = options.associations || options.relations; if (followingRelations) { tasks.push(this.discoverForeignKeys.bind(this, tableName, options)); } @@ -1568,15 +1568,15 @@ DataSource.prototype.discoverSchemas = function(tableName, options, cb) { return cb.promise; } - var columns = results[0]; + const columns = results[0]; if (!columns || columns.length === 0) { cb(new Error(g.f('Table \'%s\' does not exist.', tableName))); return cb.promise; } // Handle primary keys - var primaryKeys = results[1] || []; - var pks = {}; + const primaryKeys = results[1] || []; + const pks = {}; primaryKeys.forEach(function(pk) { pks[pk.columnName] = pk.keySeq; }); @@ -1585,7 +1585,7 @@ DataSource.prototype.discoverSchemas = function(tableName, options, cb) { debug('Primary keys: ', pks); } - var schema = { + const schema = { name: nameMapper('table', tableName), options: { idInjection: false, // DO NOT add id property @@ -1599,7 +1599,7 @@ DataSource.prototype.discoverSchemas = function(tableName, options, cb) { }; columns.forEach(function(item) { - var propName = nameMapper('column', item.columnName); + const propName = nameMapper('column', item.columnName); schema.properties[propName] = { type: item.type, required: (item.nullable === 'N' || item.nullable === 'NO' || @@ -1612,7 +1612,7 @@ DataSource.prototype.discoverSchemas = function(tableName, options, cb) { if (pks[item.columnName]) { schema.properties[propName].id = pks[item.columnName]; } - var dbSpecific = schema.properties[propName][dbType] = { + const dbSpecific = schema.properties[propName][dbType] = { columnName: item.columnName, dataType: item.dataType, dataLength: item.dataLength, @@ -1622,7 +1622,7 @@ DataSource.prototype.discoverSchemas = function(tableName, options, cb) { }; // merge connector-specific properties if (item[dbType]) { - for (var k in item[dbType]) { + for (const k in item[dbType]) { dbSpecific[k] = item[dbType][k]; } } @@ -1630,7 +1630,7 @@ DataSource.prototype.discoverSchemas = function(tableName, options, cb) { // Add current modelName to the visited tables options.visited = options.visited || {}; - var schemaKey = columns[0].owner + '.' + tableName; + const schemaKey = columns[0].owner + '.' + tableName; if (!options.visited.hasOwnProperty(schemaKey)) { if (self.settings.debug) { debug('Adding schema for ' + schemaKey); @@ -1638,13 +1638,13 @@ DataSource.prototype.discoverSchemas = function(tableName, options, cb) { options.visited[schemaKey] = schema; } - var otherTables = {}; + const otherTables = {}; if (followingRelations) { // Handle foreign keys - var fks = {}; - var foreignKeys = results[2] || []; + const fks = {}; + const foreignKeys = results[2] || []; foreignKeys.forEach(function(fk) { - var fkInfo = { + const fkInfo = { keySeq: fk.keySeq, owner: fk.pkOwner, tableName: fk.pkTableName, @@ -1663,14 +1663,14 @@ DataSource.prototype.discoverSchemas = function(tableName, options, cb) { schema.options.relations = {}; foreignKeys.forEach(function(fk) { - var propName = nameMapper('fk', (fk.fkName || fk.pkTableName)); + const propName = nameMapper('fk', (fk.fkName || fk.pkTableName)); schema.options.relations[propName] = { model: nameMapper('table', fk.pkTableName), type: 'belongsTo', foreignKey: nameMapper('column', fk.fkColumnName), }; - var key = fk.pkOwner + '.' + fk.pkTableName; + const key = fk.pkOwner + '.' + fk.pkTableName; if (!options.visited.hasOwnProperty(key) && !otherTables.hasOwnProperty(key)) { otherTables[key] = {owner: fk.pkOwner, tableName: fk.pkTableName}; } @@ -1680,13 +1680,13 @@ DataSource.prototype.discoverSchemas = function(tableName, options, cb) { if (Object.keys(otherTables).length === 0) { cb(null, options.visited); } else { - var moreTasks = []; - for (var t in otherTables) { + const moreTasks = []; + for (const t in otherTables) { if (self.settings.debug) { debug('Discovering related schema for ' + schemaKey); } - var newOptions = {}; - for (var key in options) { + const newOptions = {}; + for (const key in options) { newOptions[key] = options[key]; } newOptions.owner = otherTables[t].owner; @@ -1694,7 +1694,7 @@ DataSource.prototype.discoverSchemas = function(tableName, options, cb) { moreTasks.push(DataSource.prototype.discoverSchemas.bind(self, otherTables[t].tableName, newOptions)); } async.parallel(moreTasks, function(err, results) { - var result = results && results[0]; + const result = results && results[0]; cb(err, result); }); } @@ -1715,15 +1715,15 @@ DataSource.prototype.discoverSchemas = function(tableName, options, cb) { * @returns {Array} An array of schema definition objects. */ DataSource.prototype.discoverSchemasSync = function(modelName, options) { - var self = this; - var dbType = this.connector.name; + const self = this; + const dbType = this.connector.name; - var columns = this.discoverModelPropertiesSync(modelName, options); + const columns = this.discoverModelPropertiesSync(modelName, options); if (!columns || columns.length === 0) { return []; } - var nameMapper = options.nameMapper || function mapName(type, name) { + const nameMapper = options.nameMapper || function mapName(type, name) { if (type === 'table' || type === 'model') { return fromDBName(name, false); } else { @@ -1732,8 +1732,8 @@ DataSource.prototype.discoverSchemasSync = function(modelName, options) { }; // Handle primary keys - var primaryKeys = this.discoverPrimaryKeysSync(modelName, options); - var pks = {}; + const primaryKeys = this.discoverPrimaryKeysSync(modelName, options); + const pks = {}; primaryKeys.forEach(function(pk) { pks[pk.columnName] = pk.keySeq; }); @@ -1742,7 +1742,7 @@ DataSource.prototype.discoverSchemasSync = function(modelName, options) { debug('Primary keys: ', pks); } - var schema = { + const schema = { name: nameMapper('table', modelName), options: { idInjection: false, // DO NOT add id property @@ -1756,9 +1756,9 @@ DataSource.prototype.discoverSchemasSync = function(modelName, options) { }; columns.forEach(function(item) { - var i = item; + const i = item; - var propName = nameMapper('column', item.columnName); + const propName = nameMapper('column', item.columnName); schema.properties[propName] = { type: item.type, required: (item.nullable === 'N'), @@ -1782,7 +1782,7 @@ DataSource.prototype.discoverSchemasSync = function(modelName, options) { // Add current modelName to the visited tables options.visited = options.visited || {}; - var schemaKey = columns[0].owner + '.' + modelName; + const schemaKey = columns[0].owner + '.' + modelName; if (!options.visited.hasOwnProperty(schemaKey)) { if (self.settings.debug) { debug('Adding schema for ' + schemaKey); @@ -1790,14 +1790,14 @@ DataSource.prototype.discoverSchemasSync = function(modelName, options) { options.visited[schemaKey] = schema; } - var otherTables = {}; - var followingRelations = options.associations || options.relations; + const otherTables = {}; + const followingRelations = options.associations || options.relations; if (followingRelations) { // Handle foreign keys - var fks = {}; - var foreignKeys = this.discoverForeignKeysSync(modelName, options); + const fks = {}; + const foreignKeys = this.discoverForeignKeysSync(modelName, options); foreignKeys.forEach(function(fk) { - var fkInfo = { + const fkInfo = { keySeq: fk.keySeq, owner: fk.pkOwner, tableName: fk.pkTableName, @@ -1816,14 +1816,14 @@ DataSource.prototype.discoverSchemasSync = function(modelName, options) { schema.options.relations = {}; foreignKeys.forEach(function(fk) { - var propName = nameMapper('column', fk.pkTableName); + const propName = nameMapper('column', fk.pkTableName); schema.options.relations[propName] = { model: nameMapper('table', fk.pkTableName), type: 'belongsTo', foreignKey: nameMapper('column', fk.fkColumnName), }; - var key = fk.pkOwner + '.' + fk.pkTableName; + const key = fk.pkOwner + '.' + fk.pkTableName; if (!options.visited.hasOwnProperty(key) && !otherTables.hasOwnProperty(key)) { otherTables[key] = {owner: fk.pkOwner, tableName: fk.pkTableName}; } @@ -1833,13 +1833,13 @@ DataSource.prototype.discoverSchemasSync = function(modelName, options) { if (Object.keys(otherTables).length === 0) { return options.visited; } else { - var moreTasks = []; - for (var t in otherTables) { + const moreTasks = []; + for (const t in otherTables) { if (self.settings.debug) { debug('Discovering related schema for ' + schemaKey); } - var newOptions = {}; - for (var key in options) { + const newOptions = {}; + for (const key in options) { newOptions[key] = options[key]; } newOptions.owner = otherTables[t].owner; @@ -1863,7 +1863,7 @@ DataSource.prototype.discoverSchemasSync = function(modelName, options) { * constructors, keyed by model name */ DataSource.prototype.discoverAndBuildModels = function(modelName, options, cb) { - var self = this; + const self = this; options = options || {}; this.discoverSchemas(modelName, options, function(err, schemas) { if (err) { @@ -1871,9 +1871,9 @@ DataSource.prototype.discoverAndBuildModels = function(modelName, options, cb) { return; } - var schemaList = []; - for (var s in schemas) { - var schema = schemas[s]; + const schemaList = []; + for (const s in schemas) { + const schema = schemas[s]; if (options.base) { schema.options = schema.options || {}; schema.options.base = options.base; @@ -1881,7 +1881,7 @@ DataSource.prototype.discoverAndBuildModels = function(modelName, options, cb) { schemaList.push(schema); } - var models = self.modelBuilder.buildModels(schemaList, + const models = self.modelBuilder.buildModels(schemaList, self.createModel.bind(self)); cb && cb(err, models); @@ -1905,11 +1905,11 @@ DataSource.prototype.discoverAndBuildModels = function(modelName, options, cb) { */ DataSource.prototype.discoverAndBuildModelsSync = function(modelName, options) { options = options || {}; - var schemas = this.discoverSchemasSync(modelName, options); + const schemas = this.discoverSchemasSync(modelName, options); - var schemaList = []; - for (var s in schemas) { - var schema = schemas[s]; + const schemaList = []; + for (const s in schemas) { + const schema = schemas[s]; if (options.base) { schema.options = schema.options || {}; schema.options.base = options.base; @@ -1917,7 +1917,7 @@ DataSource.prototype.discoverAndBuildModelsSync = function(modelName, options) { schemaList.push(schema); } - var models = this.modelBuilder.buildModels(schemaList, + const models = this.modelBuilder.buildModels(schemaList, this.createModel.bind(this)); return models; @@ -1932,7 +1932,7 @@ DataSource.prototype.discoverAndBuildModelsSync = function(modelName, options) { */ DataSource.prototype.buildModelFromInstance = function(name, json, options) { // Introspect the JSON document to generate a schema - var schema = ModelBuilder.introspect(json); + const schema = ModelBuilder.introspect(json); // Create a model for the generated schema return this.createModel(name, schema, options); @@ -2063,8 +2063,8 @@ DataSource.prototype.idNames = function(modelName) { * @returns {Object} The id property definition */ DataSource.prototype.idProperty = function(modelName) { - var def = this.getModelDefinition(modelName); - var idProps = def && def.ids(); + const def = this.getModelDefinition(modelName); + const idProps = def && def.ids(); return idProps && idProps[0] && idProps[0].property; }; @@ -2076,13 +2076,13 @@ DataSource.prototype.idProperty = function(modelName) { * @param {String} pkName (optional) primary key used for foreignKey */ DataSource.prototype.defineForeignKey = function defineForeignKey(className, key, foreignClassName, pkName) { - var pkType = null; - var foreignModel = this.getModelDefinition(foreignClassName); + let pkType = null; + const foreignModel = this.getModelDefinition(foreignClassName); pkName = pkName || foreignModel && foreignModel.idName(); if (pkName) { pkType = foreignModel.properties[pkName].type; } - var model = this.getModelDefinition(className); + const model = this.getModelDefinition(className); if (model.properties[key]) { if (pkType) { // Reset the type of the foreign key @@ -2091,8 +2091,8 @@ DataSource.prototype.defineForeignKey = function defineForeignKey(className, key return; } - var fkDef = {type: pkType}; - var foreignMeta = this.columnMetadata(foreignClassName, pkName); + const fkDef = {type: pkType}; + const foreignMeta = this.columnMetadata(foreignClassName, pkName); if (foreignMeta && (foreignMeta.dataType || foreignMeta.dataLength)) { fkDef[this.connector.name] = {}; if (foreignMeta.dataType) { @@ -2103,7 +2103,7 @@ DataSource.prototype.defineForeignKey = function defineForeignKey(className, key } } if (this.connector.defineForeignKey) { - var cb = function(err, keyType) { + const cb = function(err, keyType) { if (err) throw err; fkDef.type = keyType || pkType; // Add the foreign key property to the data source _models @@ -2130,7 +2130,7 @@ DataSource.prototype.defineForeignKey = function defineForeignKey(className, key */ DataSource.prototype.disconnect = function disconnect(cb) { cb = cb || utils.createPromiseCallback(); - var self = this; + const self = this; if (this.connected && (typeof this.connector.disconnect === 'function')) { this.connector.disconnect(function(err, result) { self.connected = false; @@ -2153,10 +2153,10 @@ DataSource.prototype.disconnect = function disconnect(cb) { * @private */ DataSource.prototype.copyModel = function copyModel(Master) { - var dataSource = this; - var className = Master.modelName; - var md = Master.modelBuilder.getModelDefinition(className); - var Slave = function SlaveModel() { + const dataSource = this; + const className = Master.modelName; + const md = Master.modelBuilder.getModelDefinition(className); + const Slave = function SlaveModel() { Master.apply(this, [].slice.call(arguments)); }; @@ -2234,10 +2234,10 @@ DataSource.prototype.transaction = function(execute, options, cb) { options = options || {}; } - var dataSource = this; - var transaction = new EventEmitter(); + const dataSource = this; + const transaction = new EventEmitter(); - for (var p in dataSource) { + for (const p in dataSource) { transaction[p] = dataSource[p]; } @@ -2252,8 +2252,8 @@ DataSource.prototype.transaction = function(execute, options, cb) { }; // Create a blank pool for the slave models bound to this transaction. - var modelBuilder = new ModelBuilder(); - var slaveModels = modelBuilder.models; + const modelBuilder = new ModelBuilder(); + const slaveModels = modelBuilder.models; transaction.modelBuilder = modelBuilder; transaction.models = slaveModels; transaction.definitions = modelBuilder.definitions; @@ -2261,7 +2261,7 @@ DataSource.prototype.transaction = function(execute, options, cb) { // For performance reasons, use a getter per model and only call copyModel() // for the models that are actually used. These getters are then replaced // with the actual values on first use. - var masterModels = dataSource.modelBuilder.models; + const masterModels = dataSource.modelBuilder.models; Object.keys(masterModels).forEach(function(name) { Object.defineProperty(slaveModels, name, { enumerable: true, @@ -2292,7 +2292,7 @@ DataSource.prototype.transaction = function(execute, options, cb) { if (execute) { cb = cb || utils.createPromiseCallback(); try { - var result = execute(slaveModels, done); + const result = execute(slaveModels, done); if (result && typeof result.then === 'function') { result.then(function() { done(); }, done); } @@ -2347,7 +2347,7 @@ DataSource.prototype.transaction = function(execute, options, cb) { return transaction; } - var connector = dataSource.connector; + const connector = dataSource.connector; if (connector.transaction) { // Create a transient or memory source transaction. transaction.connector = connector.transaction(); @@ -2385,7 +2385,7 @@ DataSource.prototype.transaction = function(execute, options, cb) { */ DataSource.prototype.enableRemote = function(operation) { - var op = this.getOperation(operation); + const op = this.getOperation(operation); if (op) { op.remoteEnabled = true; } else { @@ -2414,7 +2414,7 @@ DataSource.prototype.enableRemote = function(operation) { */ DataSource.prototype.disableRemote = function(operation) { - var op = this.getOperation(operation); + const op = this.getOperation(operation); if (op) { op.remoteEnabled = false; } else { @@ -2428,11 +2428,11 @@ DataSource.prototype.disableRemote = function(operation) { */ DataSource.prototype.getOperation = function(operation) { - var ops = this.operations(); - var opKeys = Object.keys(ops); + const ops = this.operations(); + const opKeys = Object.keys(ops); - for (var i = 0; i < opKeys.length; i++) { - var op = ops[opKeys[i]]; + for (let i = 0; i < opKeys.length; i++) { + const op = ops[opKeys[i]]; if (op.name === operation) { return op; @@ -2500,7 +2500,7 @@ DataSource.prototype.isRelational = function() { */ DataSource.prototype.queueInvocation = DataSource.prototype.ready = function(obj, args) { - var self = this; + const self = this; debug('Datasource %s: connected=%s connecting=%s', this.name, this.connected, this.connecting); if (this.connected) { @@ -2508,10 +2508,10 @@ function(obj, args) { return false; } - var method = args.callee; + const method = args.callee; // Set up a callback after the connection is established to continue the method call - var onConnected = null, onError = null, timeoutHandle = null; + let onConnected = null, onError = null, timeoutHandle = null; onConnected = function() { debug('Datasource %s is now connected - executing method %s', self.name, method.name); // Remove the error handler @@ -2519,12 +2519,12 @@ function(obj, args) { if (timeoutHandle) { clearTimeout(timeoutHandle); } - var params = [].slice.call(args); + const params = [].slice.call(args); try { method.apply(obj, params); } catch (err) { // Catch the exception and report it via callback - var cb = params.pop(); + const cb = params.pop(); if (typeof cb === 'function') { process.nextTick(function() { cb(err); @@ -2541,8 +2541,8 @@ function(obj, args) { if (timeoutHandle) { clearTimeout(timeoutHandle); } - var params = [].slice.call(args); - var cb = params.pop(); + const params = [].slice.call(args); + const cb = params.pop(); if (typeof cb === 'function') { process.nextTick(function() { cb(err); @@ -2553,15 +2553,15 @@ function(obj, args) { this.once('error', onError); // Set up a timeout to cancel the invocation - var timeout = this.settings.connectionTimeout || 5000; + const timeout = this.settings.connectionTimeout || 5000; timeoutHandle = setTimeout(function() { debug('Datasource %s fails to connect due to timeout - aborting method %s', self.name, method.name); self.connecting = false; self.removeListener('error', onError); self.removeListener('connected', onConnected); - var params = [].slice.call(args); - var cb = params.pop(); + const params = [].slice.call(args); + const cb = params.pop(); if (typeof cb === 'function') { cb(new Error(g.f('Timeout in connecting after %s ms', timeout))); } @@ -2580,14 +2580,14 @@ function(obj, args) { */ DataSource.prototype.ping = function(cb) { cb = cb || utils.createPromiseCallback(); - var self = this; + const self = this; if (self.connector.ping) { this.connector.ping(cb); } else if (self.connector.discoverModelProperties) { self.discoverModelProperties('dummy', {}, cb); } else { process.nextTick(function() { - var err = self.connected ? null : new Error(g.f('Not connected')); + const err = self.connected ? null : new Error(g.f('Not connected')); cb(err); }); } diff --git a/lib/date-string.js b/lib/date-string.js index 6355d704..905dc5ad 100644 --- a/lib/date-string.js +++ b/lib/date-string.js @@ -5,7 +5,7 @@ 'use strict'; -var inspect = require('util').inspect; +const inspect = require('util').inspect; module.exports = DateString; @@ -60,7 +60,7 @@ function DateString(value) { Object.defineProperty(this, 'when', { get: () => { return this._when; }, set: (val) => { - var d = new Date(val); + const d = new Date(val); if (isNaN(d.getTime())) { throw new Error('Invalid date'); } else { diff --git a/lib/geo.js b/lib/geo.js index 11b51ad1..094fd5e7 100644 --- a/lib/geo.js +++ b/lib/geo.js @@ -5,7 +5,7 @@ 'use strict'; -var assert = require('assert'); +const assert = require('assert'); /*! * Get a near filter from a given where object. For connector use only. @@ -22,12 +22,12 @@ exports.nearFilter = function nearFilter(where) { if (typeof clause[clauseKey] !== 'object' || !clause[clauseKey]) return; if (Array.isArray(clause[clauseKey])) { clause[clauseKey].forEach(function(el, index) { - var ret = nearSearch(el, parentKeys.concat(clauseKey).concat(index)); + const ret = nearSearch(el, parentKeys.concat(clauseKey).concat(index)); if (ret) return ret; }); } else { if (clause[clauseKey].hasOwnProperty('near')) { - var result = clause[clauseKey]; + const result = clause[clauseKey]; nearResults.push({ near: result.near, maxDistance: result.maxDistance, @@ -68,19 +68,19 @@ exports.nearFilter = function nearFilter(where) { */ exports.filter = function(rawResults, filters) { - var distances = {}; - var results = []; + const distances = {}; + const results = []; filters.forEach(function(filter) { - var origin = filter.near; - var max = filter.maxDistance > 0 ? filter.maxDistance : false; - var min = filter.minDistance > 0 ? filter.minDistance : false; - var unit = filter.unit; - var key = filter.key; + const origin = filter.near; + const max = filter.maxDistance > 0 ? filter.maxDistance : false; + const min = filter.minDistance > 0 ? filter.minDistance : false; + const unit = filter.unit; + const key = filter.key; // create distance index rawResults.forEach(function(result) { - var loc = result[key]; + let loc = result[key]; // filter out results without locations if (!loc) return; @@ -90,7 +90,7 @@ exports.filter = function(rawResults, filters) { if (typeof loc.lat !== 'number') return; if (typeof loc.lng !== 'number') return; - var d = GeoPoint.distanceBetween(origin, loc, {type: unit}); + const d = GeoPoint.distanceBetween(origin, loc, {type: unit}); // filter result if distance is either < minDistance or > maxDistance if ((min && d < min) || (max && d > max)) return; @@ -100,12 +100,12 @@ exports.filter = function(rawResults, filters) { }); results.sort(function(resA, resB) { - var a = resA[key]; - var b = resB[key]; + const a = resA[key]; + const b = resB[key]; if (a && b) { - var da = distances[resA.id]; - var db = distances[resB.id]; + const da = distances[resA.id]; + const db = distances[resB.id]; if (db === da) return 0; return da > db ? 1 : -1; @@ -231,11 +231,11 @@ GeoPoint.distanceBetween = function distanceBetween(a, b, options) { b = GeoPoint(b); } - var x1 = a.lat; - var y1 = a.lng; + const x1 = a.lat; + const y1 = a.lng; - var x2 = b.lat; - var y2 = b.lng; + const x2 = b.lat; + const y2 = b.lng; return geoDistance(x1, y1, x2, y2, options); }; @@ -283,13 +283,13 @@ GeoPoint.prototype.toString = function() { */ // factor to convert degrees to radians -var DEG2RAD = 0.01745329252; +const DEG2RAD = 0.01745329252; // factor to convert radians degrees to degrees -var RAD2DEG = 57.29577951308; +const RAD2DEG = 57.29577951308; // radius of the earth -var EARTH_RADIUS = { +const EARTH_RADIUS = { kilometers: 6370.99056, meters: 6370990.56, miles: 3958.75, @@ -299,7 +299,7 @@ var EARTH_RADIUS = { }; function geoDistance(x1, y1, x2, y2, options) { - var type = (options && options.type) || 'miles'; + const type = (options && options.type) || 'miles'; // Convert to radians x1 = x1 * DEG2RAD; @@ -309,11 +309,11 @@ function geoDistance(x1, y1, x2, y2, options) { // 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) { + const haversine = function(a) { return Math.pow(Math.sin(a / 2.0), 2); }; - var f = Math.sqrt(haversine(x2 - x1) + Math.cos(x2) * Math.cos(x1) * haversine(y2 - y1)); + const f = Math.sqrt(haversine(x2 - x1) + Math.cos(x2) * Math.cos(x1) * haversine(y2 - y1)); return 2 * Math.asin(f) * EARTH_RADIUS[type]; } diff --git a/lib/hooks.js b/lib/hooks.js index 52ec8ce2..08d0f56e 100644 --- a/lib/hooks.js +++ b/lib/hooks.js @@ -5,8 +5,8 @@ 'use strict'; -var deprecated = require('depd')('loopback-datasource-juggler'); -var g = require('strong-globalize')(); +const deprecated = require('depd')('loopback-datasource-juggler'); +const g = require('strong-globalize')(); /*! * Module exports @@ -48,16 +48,16 @@ Hookable.afterDestroy = null; * @param {Function} callback */ Hookable.prototype.trigger = function trigger(actionName, work, data, callback) { - var capitalizedName = capitalize(actionName); - var beforeHook = this.constructor['before' + capitalizedName] || + const capitalizedName = capitalize(actionName); + let beforeHook = this.constructor['before' + capitalizedName] || this.constructor['pre' + capitalizedName]; - var afterHook = this.constructor['after' + capitalizedName] || + let afterHook = this.constructor['after' + capitalizedName] || this.constructor['post' + capitalizedName]; if (actionName === 'validate') { beforeHook = beforeHook || this.constructor.beforeValidation; afterHook = afterHook || this.constructor.afterValidation; } - var inst = this; + const inst = this; if (actionName !== 'initialize') { if (beforeHook) @@ -100,11 +100,11 @@ function capitalize(string) { } function deprecateHook(ctor, prefixes, capitalizedName) { - var candidateNames = prefixes.map(function(p) { return p + capitalizedName; }); + const candidateNames = prefixes.map(function(p) { return p + capitalizedName; }); if (capitalizedName === 'Validate') candidateNames.push(prefixes[0] + 'Validation'); - var hookName = candidateNames.filter(function(hook) { return !!ctor[hook]; })[0]; + let hookName = candidateNames.filter(function(hook) { return !!ctor[hook]; })[0]; if (!hookName) return; // just to be sure, this should never happen if (ctor.modelName) hookName = ctor.modelName + '.' + hookName; deprecated(g.f('Model hook "%s" is deprecated, ' + diff --git a/lib/include.js b/lib/include.js index 0762b8fa..28e9e6f3 100644 --- a/lib/include.js +++ b/lib/include.js @@ -5,16 +5,16 @@ 'use strict'; -var async = require('async'); -var g = require('strong-globalize')(); -var utils = require('./utils'); -var List = require('./list'); -var includeUtils = require('./include_utils'); -var isPlainObject = utils.isPlainObject; -var defineCachedRelations = utils.defineCachedRelations; -var uniq = utils.uniq; -var idName = utils.idName; -var debug = require('debug')('loopback:include'); +const async = require('async'); +const g = require('strong-globalize')(); +const utils = require('./utils'); +const List = require('./list'); +const includeUtils = require('./include_utils'); +const isPlainObject = utils.isPlainObject; +const defineCachedRelations = utils.defineCachedRelations; +const uniq = utils.uniq; +const idName = utils.idName; +const debug = require('debug')('loopback:include'); /*! * Normalize the include to be an array @@ -22,19 +22,19 @@ var debug = require('debug')('loopback:include'); * @returns {*} */ function normalizeInclude(include) { - var newInclude; + let newInclude; if (typeof include === 'string') { return [include]; } else if (isPlainObject(include)) { // Build an array of key/value pairs newInclude = []; - var rel = include.rel || include.relation; - var obj = {}; + const rel = include.rel || include.relation; + const obj = {}; if (typeof rel === 'string') { obj[rel] = new IncludeScope(include.scope); newInclude.push(obj); } else { - for (var key in include) { + for (const key in include) { obj[key] = include[key]; newInclude.push(obj); } @@ -42,8 +42,8 @@ function normalizeInclude(include) { return newInclude; } else if (Array.isArray(include)) { newInclude = []; - for (var i = 0, n = include.length; i < n; i++) { - var subIncludes = normalizeInclude(include[i]); + for (let i = 0, n = include.length; i < n; i++) { + const subIncludes = normalizeInclude(include[i]); newInclude = newInclude.concat(subIncludes); } return newInclude; @@ -80,8 +80,8 @@ function lookupModel(models, modelName) { if (models[modelName]) { return models[modelName]; } - var lookupClassName = modelName.toLowerCase(); - for (var name in models) { + const lookupClassName = modelName.toLowerCase(); + for (const name in models) { if (name.toLowerCase() === lookupClassName) { return models[name]; } @@ -161,7 +161,7 @@ Inclusion.include = function(objects, include, options, cb) { cb = options; options = {}; } - var self = this; + const self = this; if (!include || (Array.isArray(include) && include.length === 0) || (Array.isArray(objects) && objects.length === 0) || @@ -176,7 +176,7 @@ Inclusion.include = function(objects, include, options, cb) { debug('include: %j', include); // Find the limit of items for `inq` - var inqLimit = 256; + let inqLimit = 256; if (self.dataSource && self.dataSource.settings && self.dataSource.settings.inqLimit) { inqLimit = self.dataSource.settings.inqLimit; @@ -212,13 +212,13 @@ Inclusion.include = function(objects, include, options, cb) { return cb(e); } - var foreignKeys = []; + let foreignKeys = []; if (filter.where[fkName]) { foreignKeys = filter.where[fkName].inq; } else if (filter.where.and) { // The inq can be embedded inside 'and: []'. No or: [] is needed as // include only uses and. We only deal with the generated inq for include. - for (var j in filter.where.and) { + for (const j in filter.where.and) { if (filter.where.and[j][fkName] && Array.isArray(filter.where.and[j][fkName].inq)) { foreignKeys = filter.where.and[j][fkName].inq; @@ -233,7 +233,7 @@ Inclusion.include = function(objects, include, options, cb) { // Force the find to be performed per FK to honor the pagination pageSize = 1; } - var size = foreignKeys.length; + const size = foreignKeys.length; if (size > inqLimit && pageSize <= 0) { pageSize = inqLimit; } @@ -241,29 +241,29 @@ Inclusion.include = function(objects, include, options, cb) { return model.find(filter, options, cb); } - var listOfFKs = []; + let listOfFKs = []; - for (var i = 0; i < size; i += pageSize) { - var end = i + pageSize; + for (let i = 0; i < size; i += pageSize) { + let end = i + pageSize; if (end > size) { end = size; } listOfFKs.push(foreignKeys.slice(i, end)); } - var items = []; + let items = []; // Optimization: no need to resolve keys that are an empty array listOfFKs = listOfFKs.filter(function(keys) { return keys.length > 0; }); async.each(listOfFKs, function(foreignKeys, done) { - var newFilter = {}; - for (var f in filter) { + const newFilter = {}; + for (const f in filter) { newFilter[f] = filter[f]; } if (filter.where) { newFilter.where = {}; - for (var w in filter.where) { + for (const w in filter.where) { newFilter.where[w] = filter.where[w]; } } @@ -282,10 +282,10 @@ Inclusion.include = function(objects, include, options, cb) { } function processIncludeItem(objs, include, options, cb) { - var relations = self.relations; + const relations = self.relations; - var relationName; - var subInclude = null, scope = null; + let relationName; + let subInclude = null, scope = null; if (isPlainObject(include)) { relationName = Object.keys(include)[0]; @@ -304,13 +304,13 @@ Inclusion.include = function(objects, include, options, cb) { subInclude = null; } - var relation = relations[relationName]; + const relation = relations[relationName]; if (!relation) { cb(new Error(g.f('Relation "%s" is not defined for %s model', relationName, self.modelName))); return; } debug('Relation: %j', relation); - var polymorphic = relation.polymorphic; + const polymorphic = relation.polymorphic; // if (polymorphic && !polymorphic.discriminator) { // cb(new Error('Relation "' + relationName + '" is polymorphic but ' + // 'discriminator is not present')); @@ -330,15 +330,15 @@ Inclusion.include = function(objects, include, options, cb) { return cb(); } // prepare filter and fields for making DB Call - var filter = (scope && scope.conditions()) || {}; + const filter = (scope && scope.conditions()) || {}; if ((relation.multiple || relation.type === 'belongsTo') && scope) { - var includeScope = {}; + const includeScope = {}; // make sure not to miss any fields for sub includes if (filter.fields && Array.isArray(subInclude) && relation.modelTo.relations) { includeScope.fields = []; subInclude.forEach(function(name) { - var rel = relation.modelTo.relations[name]; + const rel = relation.modelTo.relations[name]; if (rel && rel.type === 'belongsTo') { includeScope.fields.push(rel.keyFrom); } @@ -349,7 +349,7 @@ Inclusion.include = function(objects, include, options, cb) { // Let's add a placeholder where query filter.where = filter.where || {}; // if fields are specified, make sure target foreign key is present - var fields = filter.fields; + let fields = filter.fields; if (typeof fields === 'string') { // transform string into array containing this string filter.fields = fields = [fields]; @@ -405,14 +405,14 @@ Inclusion.include = function(objects, include, options, cb) { * @param callback */ function includeHasManyThrough(callback) { - var sourceIds = []; + const sourceIds = []; // Map for Indexing objects by their id for faster retrieval - var objIdMap = {}; - for (var i = 0; i < objs.length; i++) { - var obj = objs[i]; + const objIdMap = {}; + for (let i = 0; i < objs.length; i++) { + const obj = objs[i]; // one-to-many: foreign key reference is modelTo -> modelFrom. // use modelFrom.keyFrom in where filter later - var sourceId = obj[relation.keyFrom]; + const sourceId = obj[relation.keyFrom]; if (sourceId) { sourceIds.push(sourceId); objIdMap[sourceId.toString()] = obj; @@ -423,7 +423,7 @@ 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 = { + const throughFilter = { where: {}, }; throughFilter.where[relation.keyTo] = { @@ -451,25 +451,25 @@ Inclusion.include = function(objects, include, options, cb) { return callback(err); } // start preparing for 2nd DB call. - var targetIds = []; - var targetObjsMap = {}; - for (var i = 0; i < throughObjs.length; i++) { - var throughObj = throughObjs[i]; - var targetId = throughObj[relation.keyThrough]; + const targetIds = []; + const targetObjsMap = {}; + for (let i = 0; i < throughObjs.length; i++) { + const throughObj = throughObjs[i]; + const targetId = throughObj[relation.keyThrough]; if (targetId) { // save targetIds for 2nd DB Call targetIds.push(targetId); - var sourceObj = objIdMap[throughObj[relation.keyTo]]; - var targetIdStr = targetId.toString(); + const sourceObj = objIdMap[throughObj[relation.keyTo]]; + const targetIdStr = targetId.toString(); // Since targetId can be duplicates, multiple source objs are put // into buckets. - var objList = targetObjsMap[targetIdStr] = + const objList = targetObjsMap[targetIdStr] = targetObjsMap[targetIdStr] || []; objList.push(sourceObj); } } // Polymorphic relation does not have idKey of modelTo. Find it manually - var modelToIdName = idName(relation.modelTo); + const modelToIdName = idName(relation.modelTo); filter.where[modelToIdName] = { inq: uniq(targetIds), }; @@ -490,7 +490,7 @@ Inclusion.include = function(objects, include, options, cb) { if (err) { return callback(err); } - var tasks = []; + const tasks = []; // simultaneously process subIncludes. Call it first as it is an async // process. if (subInclude && targets) { @@ -503,13 +503,13 @@ Inclusion.include = function(objects, include, options, cb) { function targetLinkingTask(next) { async.each(targets, linkManyToMany, next); function linkManyToMany(target, next) { - var targetId = target[modelToIdName]; + const targetId = target[modelToIdName]; if (!targetId) { - var err = new Error(g.f('LinkManyToMany received target that doesn\'t contain required "%s"', + const err = new Error(g.f('LinkManyToMany received target that doesn\'t contain required "%s"', modelToIdName)); return next(err); } - var objList = targetObjsMap[targetId.toString()]; + const objList = targetObjsMap[targetId.toString()]; async.each(objList, function(obj, next) { if (!obj) return next(); obj.__cachedRelations[relationName].push(target); @@ -528,15 +528,15 @@ Inclusion.include = function(objects, include, options, cb) { * @param callback */ function includeReferencesMany(callback) { - var modelToIdName = idName(relation.modelTo); - var allTargetIds = []; + const modelToIdName = idName(relation.modelTo); + let allTargetIds = []; // Map for Indexing objects by their id for faster retrieval - var targetObjsMap = {}; - for (var i = 0; i < objs.length; i++) { - var obj = objs[i]; + const targetObjsMap = {}; + for (let i = 0; i < objs.length; i++) { + const obj = objs[i]; // one-to-many: foreign key reference is modelTo -> modelFrom. // use modelFrom.keyFrom in where filter later - var targetIds = obj[relation.keyFrom]; + let targetIds = obj[relation.keyFrom]; if (targetIds) { if (typeof targetIds === 'string') { // For relational DBs, the array is stored as stringified json @@ -546,10 +546,10 @@ Inclusion.include = function(objects, include, options, cb) { // referencesMany has multiple targetIds per obj. We need to concat // them into allTargetIds before DB Call allTargetIds = allTargetIds.concat(targetIds); - for (var j = 0; j < targetIds.length; j++) { - var targetId = targetIds[j]; - var targetIdStr = targetId.toString(); - var objList = targetObjsMap[targetIdStr] = + for (let j = 0; j < targetIds.length; j++) { + const targetId = targetIds[j]; + const targetIdStr = targetId.toString(); + const objList = targetObjsMap[targetIdStr] = targetObjsMap[targetIdStr] || []; objList.push(obj); } @@ -577,7 +577,7 @@ Inclusion.include = function(objects, include, options, cb) { if (err) { return callback(err); } - var tasks = []; + const tasks = []; // simultaneously process subIncludes if (subInclude && targets) { tasks.push(function subIncludesTask(next) { @@ -590,7 +590,7 @@ Inclusion.include = function(objects, include, options, cb) { function targetLinkingTask(next) { async.each(targets, linkManyToMany, next); function linkManyToMany(target, next) { - var objList = targetObjsMap[target[relation.keyTo].toString()]; + const objList = targetObjsMap[target[relation.keyTo].toString()]; async.each(objList, function(obj, next) { if (!obj) return next(); obj.__cachedRelations[relationName].push(target); @@ -609,7 +609,7 @@ Inclusion.include = function(objects, include, options, cb) { */ function includeHasManySimple(callback) { // Map for Indexing objects by their id for faster retrieval - var objIdMap2 = includeUtils.buildOneToOneIdentityMapWithOrigKeys(objs, relation.keyFrom); + const objIdMap2 = includeUtils.buildOneToOneIdentityMapWithOrigKeys(objs, relation.keyFrom); filter.where[relation.keyTo] = { inq: uniq(objIdMap2.getKeys()), @@ -624,7 +624,7 @@ Inclusion.include = function(objects, include, options, cb) { if (err) { return callback(err); } - var targetsIdMap = includeUtils.buildOneToManyIdentityMapWithOrigKeys(targets, relation.keyTo); + const targetsIdMap = includeUtils.buildOneToManyIdentityMapWithOrigKeys(targets, relation.keyTo); includeUtils.join(objIdMap2, targetsIdMap, function(obj1, valueToMergeIn) { defineCachedRelations(obj1); obj1.__cachedRelations[relationName] = valueToMergeIn; @@ -639,14 +639,14 @@ Inclusion.include = function(objects, include, options, cb) { * @param callback */ function includeHasMany(callback) { - var sourceIds = []; + const sourceIds = []; // Map for Indexing objects by their id for faster retrieval - var objIdMap = {}; - for (var i = 0; i < objs.length; i++) { - var obj = objs[i]; + const objIdMap = {}; + for (let i = 0; i < objs.length; i++) { + const obj = objs[i]; // one-to-many: foreign key reference is modelTo -> modelFrom. // use modelFrom.keyFrom in where filter later - var sourceId = obj[relation.keyFrom]; + const sourceId = obj[relation.keyFrom]; if (sourceId) { sourceIds.push(sourceId); objIdMap[sourceId.toString()] = obj; @@ -674,7 +674,7 @@ Inclusion.include = function(objects, include, options, cb) { if (err) { return callback(err); } - var tasks = []; + const tasks = []; // simultaneously process subIncludes if (subInclude && targets) { tasks.push(function subIncludesTask(next) { @@ -693,9 +693,9 @@ Inclusion.include = function(objects, include, options, cb) { async.each(targets, linkManyToOne, next); function linkManyToOne(target, next) { // fix for bug in hasMany with referencesMany - var targetIds = [].concat(target[relation.keyTo]); + const targetIds = [].concat(target[relation.keyTo]); async.each(targetIds, function(targetId, next) { - var obj = objIdMap[targetId.toString()]; + const obj = objIdMap[targetId.toString()]; if (!obj) return next(); obj.__cachedRelations[relationName].push(target); processTargetObj(obj, next); @@ -704,7 +704,7 @@ Inclusion.include = function(objects, include, options, cb) { return next(err); } - var objsWithEmptyRelation = objs.filter(function(obj) { + const objsWithEmptyRelation = objs.filter(function(obj) { return obj.__cachedRelations[relationName].length === 0; }); async.each(objsWithEmptyRelation, function(obj, next) { @@ -725,22 +725,22 @@ Inclusion.include = function(objects, include, options, cb) { * @param callback */ function includePolymorphicBelongsTo(callback) { - var targetIdsByType = {}; + const targetIdsByType = {}; // Map for Indexing objects by their type and targetId for faster retrieval - var targetObjMapByType = {}; - for (var i = 0; i < objs.length; i++) { - var obj = objs[i]; - var discriminator = polymorphic.discriminator; - var modelType = obj[discriminator]; + const targetObjMapByType = {}; + for (let i = 0; i < objs.length; i++) { + const obj = objs[i]; + const discriminator = polymorphic.discriminator; + const modelType = obj[discriminator]; if (modelType) { targetIdsByType[modelType] = targetIdsByType[modelType] || []; targetObjMapByType[modelType] = targetObjMapByType[modelType] || {}; - var targetIds = targetIdsByType[modelType]; - var targetObjsMap = targetObjMapByType[modelType]; - var targetId = obj[relation.keyFrom]; + const targetIds = targetIdsByType[modelType]; + const targetObjsMap = targetObjMapByType[modelType]; + const targetId = obj[relation.keyFrom]; if (targetId) { targetIds.push(targetId); - var targetIdStr = targetId.toString(); + const targetIdStr = targetId.toString(); targetObjsMap[targetIdStr] = targetObjsMap[targetIdStr] || []; // Is belongsTo. Multiple objects can have the same // targetId and therefore map value is an array @@ -758,13 +758,13 @@ Inclusion.include = function(objects, include, options, cb) { * @param callback */ function processPolymorphicType(modelType, callback) { - var typeFilter = {where: {}}; + const typeFilter = {where: {}}; utils.mergeQuery(typeFilter, filter); - var targetIds = targetIdsByType[modelType]; + const targetIds = targetIdsByType[modelType]; typeFilter.where[relation.keyTo] = { inq: uniq(targetIds), }; - var Model = lookupModel(relation.modelFrom.dataSource.modelBuilder. + const Model = lookupModel(relation.modelFrom.dataSource.modelBuilder. models, modelType); if (!Model) { callback(new Error(g.f('Discriminator type %s specified but no model exists with such name', @@ -786,7 +786,7 @@ Inclusion.include = function(objects, include, options, cb) { if (err) { return callback(err); } - var tasks = []; + const tasks = []; // simultaneously process subIncludes if (subInclude && targets) { @@ -797,10 +797,10 @@ Inclusion.include = function(objects, include, options, cb) { // process each target object tasks.push(targetLinkingTask); function targetLinkingTask(next) { - var targetObjsMap = targetObjMapByType[modelType]; + const targetObjsMap = targetObjMapByType[modelType]; async.each(targets, linkOneToMany, next); function linkOneToMany(target, next) { - var objList = targetObjsMap[target[relation.keyTo].toString()]; + const objList = targetObjsMap[target[relation.keyTo].toString()]; async.each(objList, function(obj, next) { if (!obj) return next(); obj.__cachedRelations[relationName] = target; @@ -819,14 +819,14 @@ Inclusion.include = function(objects, include, options, cb) { * @param callback */ function includePolymorphicHasOne(callback) { - var sourceIds = []; + const sourceIds = []; // Map for Indexing objects by their id for faster retrieval - var objIdMap = {}; - for (var i = 0; i < objs.length; i++) { - var obj = objs[i]; + const objIdMap = {}; + for (let i = 0; i < objs.length; i++) { + const obj = objs[i]; // one-to-one: foreign key reference is modelTo -> modelFrom. // use modelFrom.keyFrom in where filter later - var sourceId = obj[relation.keyFrom]; + const sourceId = obj[relation.keyFrom]; if (sourceId) { sourceIds.push(sourceId); objIdMap[sourceId.toString()] = obj; @@ -853,7 +853,7 @@ Inclusion.include = function(objects, include, options, cb) { if (err) { return callback(err); } - var tasks = []; + const tasks = []; // simultaneously process subIncludes if (subInclude && targets) { tasks.push(function subIncludesTask(next) { @@ -865,9 +865,9 @@ Inclusion.include = function(objects, include, options, cb) { function targetLinkingTask(next) { async.each(targets, linkOneToOne, next); function linkOneToOne(target, next) { - var sourceId = target[relation.keyTo]; + const sourceId = target[relation.keyTo]; if (!sourceId) return next(); - var obj = objIdMap[sourceId.toString()]; + const obj = objIdMap[sourceId.toString()]; if (!obj) return next(); obj.__cachedRelations[relationName] = target; processTargetObj(obj, next); @@ -883,10 +883,10 @@ Inclusion.include = function(objects, include, options, cb) { * @param callback */ function includeOneToOne(callback) { - var targetIds = []; - var objTargetIdMap = {}; - for (var i = 0; i < objs.length; i++) { - var obj = objs[i]; + const targetIds = []; + const objTargetIdMap = {}; + for (let i = 0; i < objs.length; i++) { + const obj = objs[i]; if (relation.type === 'belongsTo') { if (obj[relation.keyFrom] == null) { defineCachedRelations(obj); @@ -895,10 +895,10 @@ Inclusion.include = function(objects, include, options, cb) { continue; } } - var targetId = obj[relation.keyFrom]; + const targetId = obj[relation.keyFrom]; if (targetId) { targetIds.push(targetId); - var targetIdStr = targetId.toString(); + const targetIdStr = targetId.toString(); objTargetIdMap[targetIdStr] = objTargetIdMap[targetIdStr] || []; objTargetIdMap[targetIdStr].push(obj); } else { @@ -925,7 +925,7 @@ Inclusion.include = function(objects, include, options, cb) { if (err) { return callback(err); } - var tasks = []; + const tasks = []; // simultaneously process subIncludes if (subInclude && targets) { tasks.push(function subIncludesTask(next) { @@ -937,8 +937,8 @@ Inclusion.include = function(objects, include, options, cb) { function targetLinkingTask(next) { async.each(targets, linkOneToMany, next); function linkOneToMany(target, next) { - var targetId = target[relation.keyTo]; - var objList = objTargetIdMap[targetId.toString()]; + const targetId = target[relation.keyTo]; + const objList = objTargetIdMap[targetId.toString()]; async.each(objList, function(obj, next) { if (!obj) return next(); obj.__cachedRelations[relationName] = target; @@ -973,7 +973,7 @@ Inclusion.include = function(objects, include, options, cb) { * @returns {*} */ function processTargetObj(obj, callback) { - var isInst = obj instanceof self; + const isInst = obj instanceof self; // Calling the relation method on the instance if (relation.type === 'belongsTo') { @@ -1015,21 +1015,21 @@ Inclusion.include = function(objects, include, options, cb) { callback); } - var inst = (obj instanceof self) ? obj : new self(obj); + const inst = (obj instanceof self) ? obj : new self(obj); // If related objects are not cached by include Handlers, directly call // related accessor function even though it is not very efficient - var related; // relation accessor function + let related; // relation accessor function if ((relation.multiple || relation.type === 'belongsTo') && scope) { - var includeScope = {}; - var filter = scope.conditions(); + const includeScope = {}; + const filter = scope.conditions(); // make sure not to miss any fields for sub includes if (filter.fields && Array.isArray(subInclude) && relation.modelTo.relations) { includeScope.fields = []; subInclude.forEach(function(name) { - var rel = relation.modelTo.relations[name]; + const rel = relation.modelTo.relations[name]; if (rel && rel.type === 'belongsTo') { includeScope.fields.push(rel.keyFrom); } diff --git a/lib/include_utils.js b/lib/include_utils.js index e08d722f..57328742 100644 --- a/lib/include_utils.js +++ b/lib/include_utils.js @@ -5,7 +5,7 @@ 'use strict'; -var g = require('strong-globalize')(); +const g = require('strong-globalize')(); module.exports.buildOneToOneIdentityMapWithOrigKeys = buildOneToOneIdentityMapWithOrigKeys; module.exports.buildOneToManyIdentityMapWithOrigKeys = buildOneToManyIdentityMapWithOrigKeys; @@ -15,7 +15,7 @@ module.exports.KVMap = KVMap; const util = require('util'); function getId(obj, idName) { - var id = obj && obj[idName]; + const id = obj && obj[idName]; if (id == null) { const msg = g.f('ID property "%s" is missing for included item: %j. ' + 'Please make sure `fields` include "%s" if it\'s present in the `filter`', @@ -35,21 +35,21 @@ function getId(obj, idName) { * @returns {} object where keys are ids and values are objects itself */ function buildOneToOneIdentityMapWithOrigKeys(objs, idName) { - var kvMap = new KVMap(); - for (var i = 0; i < objs.length; i++) { - var obj = objs[i]; - var id = getId(obj, idName); + const kvMap = new KVMap(); + for (let i = 0; i < objs.length; i++) { + const obj = objs[i]; + const id = getId(obj, idName); kvMap.set(id, obj); } return kvMap; } function buildOneToManyIdentityMapWithOrigKeys(objs, idName) { - var kvMap = new KVMap(); - for (var i = 0; i < objs.length; i++) { - var obj = objs[i]; - var id = getId(obj, idName); - var value = kvMap.get(id) || []; + const kvMap = new KVMap(); + for (let i = 0; i < objs.length; i++) { + const obj = objs[i]; + const id = getId(obj, idName); + const value = kvMap.get(id) || []; value.push(obj); kvMap.set(id, value); } @@ -64,11 +64,11 @@ function buildOneToManyIdentityMapWithOrigKeys(objs, idName) { * @param mergeF function(obj, objectsToMergeIn) */ function join(oneToOneIdMap, oneToManyIdMap, mergeF) { - var ids = oneToOneIdMap.getKeys(); - for (var i = 0; i < ids.length; i++) { - var id = ids[i]; - var obj = oneToOneIdMap.get(id); - var objectsToMergeIn = oneToManyIdMap.get(id) || []; + const ids = oneToOneIdMap.getKeys(); + for (let i = 0; i < ids.length; i++) { + const id = ids[i]; + const obj = oneToOneIdMap.get(id); + const objectsToMergeIn = oneToManyIdMap.get(id) || []; mergeF(obj, objectsToMergeIn); } } @@ -79,20 +79,20 @@ function join(oneToOneIdMap, oneToManyIdMap, mergeF) { * @constructor */ function KVMap() { - var _originalKeyFieldName = 'originalKey'; - var _valueKeyFieldName = 'value'; - var _dict = {}; - var keyToString = function(key) { return key.toString(); }; - var mapImpl = { + const _originalKeyFieldName = 'originalKey'; + const _valueKeyFieldName = 'value'; + const _dict = {}; + const keyToString = function(key) { return key.toString(); }; + const mapImpl = { set: function(key, value) { - var recordObj = {}; + const recordObj = {}; recordObj[_originalKeyFieldName] = key; recordObj[_valueKeyFieldName] = value; _dict[keyToString(key)] = recordObj; return true; }, get: function(key) { - var storeObj = _dict[keyToString(key)]; + const storeObj = _dict[keyToString(key)]; if (storeObj) { return storeObj[_valueKeyFieldName]; } else { @@ -104,12 +104,12 @@ function KVMap() { return true; }, exist: function(key) { - var result = _dict.hasOwnProperty(keyToString(key)); + const result = _dict.hasOwnProperty(keyToString(key)); return result; }, getKeys: function() { - var result = []; - for (var key in _dict) { + const result = []; + for (const key in _dict) { result.push(_dict[key][_originalKeyFieldName]); } return result; diff --git a/lib/introspection.js b/lib/introspection.js index 305f8f1d..a75edf91 100644 --- a/lib/introspection.js +++ b/lib/introspection.js @@ -13,14 +13,14 @@ module.exports = function getIntrospector(ModelBuilder) { } // Check registered schemaTypes - for (var t in ModelBuilder.schemaTypes) { - var st = ModelBuilder.schemaTypes[t]; + for (const t in ModelBuilder.schemaTypes) { + const st = ModelBuilder.schemaTypes[t]; if (st !== Object && st !== Array && (value instanceof st)) { return t; } } - var type = typeof value; + const type = typeof value; if (type === 'string' || type === 'number' || type === 'boolean') { return type; } @@ -29,9 +29,9 @@ module.exports = function getIntrospector(ModelBuilder) { return 'date'; } - var itemType; + let itemType; if (Array.isArray(value)) { - for (var i = 0; i < value.length; i++) { + for (let i = 0; i < value.length; i++) { if (value[i] === null || value[i] === undefined) { continue; } @@ -47,8 +47,8 @@ module.exports = function getIntrospector(ModelBuilder) { return value.constructor.name; } - var properties = {}; - for (var p in value) { + const properties = {}; + for (const p in value) { itemType = introspectType(value[p]); if (itemType) { properties[p] = itemType; diff --git a/lib/jutil.js b/lib/jutil.js index a2650dbc..57538394 100644 --- a/lib/jutil.js +++ b/lib/jutil.js @@ -5,7 +5,7 @@ 'use strict'; -var util = require('util'); +const util = require('util'); /** * @@ -24,7 +24,7 @@ exports.inherits = function(newClass, baseClass, options) { Object.keys(baseClass).forEach(function(classProp) { if (classProp !== 'super_' && (!newClass.hasOwnProperty(classProp) || options.override)) { - var pd = Object.getOwnPropertyDescriptor(baseClass, classProp); + const pd = Object.getOwnPropertyDescriptor(baseClass, classProp); Object.defineProperty(newClass, classProp, pd); } }); @@ -75,13 +75,13 @@ exports.mixin = function(newClass, mixinClass, options) { function mixInto(sourceScope, targetScope, options) { Object.keys(sourceScope).forEach(function(propertyName) { - var targetPropertyExists = targetScope.hasOwnProperty(propertyName); - var sourceProperty = Object.getOwnPropertyDescriptor(sourceScope, propertyName); - var targetProperty = targetPropertyExists && Object.getOwnPropertyDescriptor(targetScope, propertyName); - var sourceIsFunc = typeof sourceProperty.value === 'function'; - var isFunc = targetPropertyExists && typeof targetProperty.value === 'function'; - var isDelegate = isFunc && targetProperty.value._delegate; - var shouldOverride = options.override || !targetPropertyExists || isDelegate; + const targetPropertyExists = targetScope.hasOwnProperty(propertyName); + const sourceProperty = Object.getOwnPropertyDescriptor(sourceScope, propertyName); + const targetProperty = targetPropertyExists && Object.getOwnPropertyDescriptor(targetScope, propertyName); + const sourceIsFunc = typeof sourceProperty.value === 'function'; + const isFunc = targetPropertyExists && typeof targetProperty.value === 'function'; + const isDelegate = isFunc && targetProperty.value._delegate; + const shouldOverride = options.override || !targetPropertyExists || isDelegate; if (propertyName == '_mixins') { mergeMixins(sourceScope._mixins, targetScope._mixins); @@ -96,8 +96,8 @@ function mixInto(sourceScope, targetScope, options) { function mergeMixins(source, target) { // hand-written equivalent of lodash.union() - for (var ix in source) { - var mx = source[ix]; + for (const ix in source) { + const mx = source[ix]; if (target.indexOf(mx) === -1) target.push(mx); } diff --git a/lib/kvao/delete-all.js b/lib/kvao/delete-all.js index f4e21d54..0f9b0ba9 100644 --- a/lib/kvao/delete-all.js +++ b/lib/kvao/delete-all.js @@ -1,9 +1,9 @@ 'use strict'; -var assert = require('assert'); -var async = require('async'); -var debug = require('debug')('loopback:kvao:delete-all'); -var utils = require('../utils'); +const assert = require('assert'); +const async = require('async'); +const debug = require('debug')('loopback:kvao:delete-all'); +const utils = require('../utils'); /** * Delete all keys (and values) associated to the current model. @@ -27,17 +27,17 @@ module.exports = function deleteAll(options, callback) { callback = callback || utils.createPromiseCallback(); - var connector = this.getConnector(); + const connector = this.getConnector(); if (typeof connector.deleteAll === 'function') { connector.deleteAll(this.modelName, options, callback); } else if (typeof connector.delete === 'function') { debug('Falling back to unoptimized key-value pair deletion'); iterateAndDelete(connector, this.modelName, options, callback); } else { - var errMsg = 'Connector does not support key-value pair deletion'; + const errMsg = 'Connector does not support key-value pair deletion'; debug(errMsg); process.nextTick(function() { - var err = new Error(errMsg); + const err = new Error(errMsg); err.statusCode = 501; callback(err); }); @@ -46,8 +46,8 @@ module.exports = function deleteAll(options, callback) { }; function iterateAndDelete(connector, modelName, options, callback) { - var iter = connector.iterateKeys(modelName, {}); - var keys = []; + const iter = connector.iterateKeys(modelName, {}); + const keys = []; iter.next(onNextKey); function onNextKey(err, key) { diff --git a/lib/kvao/delete.js b/lib/kvao/delete.js index b11cafcb..dd2de3db 100644 --- a/lib/kvao/delete.js +++ b/lib/kvao/delete.js @@ -1,8 +1,8 @@ 'use strict'; -var assert = require('assert'); -var debug = require('debug')('loopback:kvao:delete'); -var utils = require('../utils'); +const assert = require('assert'); +const debug = require('debug')('loopback:kvao:delete'); +const utils = require('../utils'); /** * Delete the key-value pair associated to the given key. @@ -28,14 +28,14 @@ module.exports = function keyValueDelete(key, options, callback) { callback = callback || utils.createPromiseCallback(); - var connector = this.getConnector(); + const connector = this.getConnector(); if (typeof connector.delete === 'function') { connector.delete(this.modelName, key, options, callback); } else { - var errMsg = 'Connector does not support key-value pair deletion'; + const errMsg = 'Connector does not support key-value pair deletion'; debug(errMsg); process.nextTick(function() { - var err = new Error(errMsg); + const err = new Error(errMsg); err.statusCode = 501; callback(err); }); diff --git a/lib/kvao/expire.js b/lib/kvao/expire.js index b7546f93..a531f45d 100644 --- a/lib/kvao/expire.js +++ b/lib/kvao/expire.js @@ -1,7 +1,7 @@ 'use strict'; -var assert = require('assert'); -var utils = require('../utils'); +const assert = require('assert'); +const utils = require('../utils'); /** * Set the TTL (time to live) in ms (milliseconds) for a given key. TTL is the diff --git a/lib/kvao/get.js b/lib/kvao/get.js index e844e1f4..c17fda30 100644 --- a/lib/kvao/get.js +++ b/lib/kvao/get.js @@ -1,7 +1,7 @@ 'use strict'; -var assert = require('assert'); -var utils = require('../utils'); +const assert = require('assert'); +const utils = require('../utils'); /** * Return the value associated with a given key. diff --git a/lib/kvao/iterate-keys.js b/lib/kvao/iterate-keys.js index 224d28e4..0dc37389 100644 --- a/lib/kvao/iterate-keys.js +++ b/lib/kvao/iterate-keys.js @@ -1,7 +1,7 @@ 'use strict'; -var assert = require('assert'); -var utils = require('../utils'); +const assert = require('assert'); +const utils = require('../utils'); /** * Asynchronously iterate all keys in the database. Similar to `.keys()` but @@ -26,7 +26,7 @@ module.exports = function keyValueIterateKeys(filter, options) { assert(typeof filter === 'object', 'filter must be an object'); assert(typeof options === 'object', 'options must be an object'); - var iter = this.getConnector().iterateKeys(this.modelName, filter, options); + const iter = this.getConnector().iterateKeys(this.modelName, filter, options); // promisify the returned iterator return { next: function(callback) { diff --git a/lib/kvao/keys.js b/lib/kvao/keys.js index 0d9df0ba..296c346b 100644 --- a/lib/kvao/keys.js +++ b/lib/kvao/keys.js @@ -1,7 +1,7 @@ 'use strict'; -var assert = require('assert'); -var utils = require('../utils'); +const assert = require('assert'); +const utils = require('../utils'); /** * Return all keys in the database. @@ -41,8 +41,8 @@ module.exports = function keyValueKeys(filter, options, callback) { callback = callback || utils.createPromiseCallback(); - var iter = this.iterateKeys(filter, options); - var keys = []; + const iter = this.iterateKeys(filter, options); + const keys = []; iter.next(onNextKey); function onNextKey(err, key) { diff --git a/lib/kvao/set.js b/lib/kvao/set.js index 15bd224b..bd90bf6e 100644 --- a/lib/kvao/set.js +++ b/lib/kvao/set.js @@ -1,7 +1,7 @@ 'use strict'; -var assert = require('assert'); -var utils = require('../utils'); +const assert = require('assert'); +const utils = require('../utils'); /** * Persist a value and associate it with the given key. diff --git a/lib/kvao/ttl.js b/lib/kvao/ttl.js index 336ef7ae..197d33d1 100644 --- a/lib/kvao/ttl.js +++ b/lib/kvao/ttl.js @@ -1,7 +1,7 @@ 'use strict'; -var assert = require('assert'); -var utils = require('../utils'); +const assert = require('assert'); +const utils = require('../utils'); /** * Return the TTL (time to live) for a given key. TTL is the remaining time diff --git a/lib/list.js b/lib/list.js index 331e3851..61e384b6 100644 --- a/lib/list.js +++ b/lib/list.js @@ -5,14 +5,14 @@ 'use strict'; -var g = require('strong-globalize')(); -var util = require('util'); -var Any = require('./types').Types.Any; +const g = require('strong-globalize')(); +const util = require('util'); +const Any = require('./types').Types.Any; module.exports = List; function List(items, itemType, parent) { - var list = this; + const list = this; if (!(list instanceof List)) { return new List(items, itemType, parent); } @@ -27,7 +27,7 @@ function List(items, itemType, parent) { } } - var arr = []; + const arr = []; arr.__proto__ = List.prototype; items = items || []; @@ -80,16 +80,16 @@ function List(items, itemType, parent) { util.inherits(List, Array); -var _push = List.prototype.push; +const _push = List.prototype.push; List.prototype.push = function(obj) { - var item = this.itemType && (obj instanceof this.itemType) ? obj : this.toItem(obj); + const item = this.itemType && (obj instanceof this.itemType) ? obj : this.toItem(obj); _push.call(this, item); return item; }; List.prototype.toObject = function(onlySchema, removeHidden, removeProtected) { - var items = []; + const items = []; this.forEach(function(item) { if (item && typeof item === 'object' && item.toObject) { items.push(item.toObject(onlySchema, removeHidden, removeProtected)); @@ -106,7 +106,7 @@ List.prototype.toObject = function(onlySchema, removeHidden, removeProtected) { * Some modules such as `should` checks prototype for comparison */ List.prototype.toArray = function() { - var items = []; + const items = []; this.forEach(function(item) { items.push(item); }); diff --git a/lib/mixins.js b/lib/mixins.js index 9cff802a..948cb8e1 100644 --- a/lib/mixins.js +++ b/lib/mixins.js @@ -4,9 +4,9 @@ // License text available at https://opensource.org/licenses/MIT 'use strict'; -var debug = require('debug')('loopback:mixin'); -var assert = require('assert'); -var DefaultModelBaseClass = require('./model.js'); +const debug = require('debug')('loopback:mixin'); +const assert = require('assert'); +const DefaultModelBaseClass = require('./model.js'); function isModelClass(cls) { if (!cls) { @@ -29,7 +29,7 @@ function MixinProvider(modelBuilder) { * @param {Object} options */ MixinProvider.prototype.applyMixin = function applyMixin(modelClass, name, options) { - var fn = this.mixins[name]; + const fn = this.mixins[name]; if (typeof fn === 'function') { if (modelClass.dataSource) { fn(modelClass, options || {}); @@ -40,12 +40,12 @@ MixinProvider.prototype.applyMixin = function applyMixin(modelClass, name, optio } } else { // Try model name - var model = this.modelBuilder.getModel(name); + const model = this.modelBuilder.getModel(name); if (model) { debug('Mixin is resolved to a model: %s', name); modelClass.mixin(model, options); } else { - var errMsg = 'Model "' + modelClass.modelName + '" uses unknown mixin: ' + name; + const errMsg = 'Model "' + modelClass.modelName + '" uses unknown mixin: ' + name; debug(errMsg); throw new Error(errMsg); } diff --git a/lib/model-builder.js b/lib/model-builder.js index 95a7b4d6..c9908095 100644 --- a/lib/model-builder.js +++ b/lib/model-builder.js @@ -8,24 +8,24 @@ * Module dependencies */ -var g = require('strong-globalize')(); -var inflection = require('inflection'); -var EventEmitter = require('events').EventEmitter; -var util = require('util'); -var assert = require('assert'); -var deprecated = require('depd')('loopback-datasource-juggler'); -var DefaultModelBaseClass = require('./model.js'); -var List = require('./list.js'); -var ModelDefinition = require('./model-definition.js'); -var deepMerge = require('./utils').deepMerge; -var deepMergeProperty = require('./utils').deepMergeProperty; -var rankArrayElements = require('./utils').rankArrayElements; -var MixinProvider = require('./mixins'); +const g = require('strong-globalize')(); +const inflection = require('inflection'); +const EventEmitter = require('events').EventEmitter; +const util = require('util'); +const assert = require('assert'); +const deprecated = require('depd')('loopback-datasource-juggler'); +const DefaultModelBaseClass = require('./model.js'); +const List = require('./list.js'); +const ModelDefinition = require('./model-definition.js'); +const deepMerge = require('./utils').deepMerge; +const deepMergeProperty = require('./utils').deepMergeProperty; +const rankArrayElements = require('./utils').rankArrayElements; +const MixinProvider = require('./mixins'); // Set up types require('./types')(ModelBuilder); -var introspect = require('./introspection')(ModelBuilder); +const introspect = require('./introspection')(ModelBuilder); /*! * Export public API @@ -35,7 +35,7 @@ exports.ModelBuilder = exports.Schema = ModelBuilder; /*! * Helpers */ -var slice = Array.prototype.slice; +const slice = Array.prototype.slice; /** * ModelBuilder - A builder to define data models. @@ -74,7 +74,7 @@ function isModelClass(cls) { * @returns {ModelClass} The model class */ ModelBuilder.prototype.getModel = function(name, forceCreate) { - var model = this.models[name]; + let model = this.models[name]; if (!model && forceCreate) { model = this.define(name, {}, {unresolved: true}); } @@ -120,13 +120,13 @@ ModelBuilder.prototype.getModelDefinition = function(name) { * */ ModelBuilder.prototype.define = function defineClass(className, properties, settings, parent) { - var modelBuilder = this; - var args = slice.call(arguments); - var pluralName = (settings && settings.plural) || + const modelBuilder = this; + const args = slice.call(arguments); + const pluralName = (settings && settings.plural) || inflection.pluralize(className); - var httpOptions = (settings && settings.http) || {}; - var pathName = httpOptions.path || pluralName; + const httpOptions = (settings && settings.http) || {}; + let pathName = httpOptions.path || pluralName; if (!className) { throw new Error(g.f('Class name required')); @@ -149,8 +149,8 @@ ModelBuilder.prototype.define = function defineClass(className, properties, sett } // Set up the base model class - var ModelBaseClass = parent || this.defaultModelBaseClass; - var baseClass = settings.base || settings['super']; + let ModelBaseClass = parent || this.defaultModelBaseClass; + const baseClass = settings.base || settings['super']; if (baseClass) { // Normalize base model property settings.base = baseClass; @@ -180,7 +180,7 @@ ModelBuilder.prototype.define = function defineClass(className, properties, sett } // Check if there is a unresolved model with the same name - var ModelClass = this.models[className]; + let ModelClass = this.models[className]; // Create the ModelClass if it doesn't exist or it's resolved (override) // TODO: [rfeng] We need to decide what names to use for built-in models such as User. @@ -188,11 +188,11 @@ ModelBuilder.prototype.define = function defineClass(className, properties, sett ModelClass = createModelClassCtor(className, ModelBaseClass); // mix in EventEmitter (don't inherit from) - var events = new EventEmitter(); + const events = new EventEmitter(); // The model can have more than 10 listeners for lazy relationship setup // See https://github.com/strongloop/loopback/issues/404 events.setMaxListeners(32); - for (var f in EventEmitter.prototype) { + for (const f in EventEmitter.prototype) { if (typeof EventEmitter.prototype[f] === 'function') { ModelClass[f] = EventEmitter.prototype[f].bind(events); } @@ -239,7 +239,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) { - var model = settings.models[m]; + const model = settings.models[m]; ModelClass[m] = typeof model === 'string' ? modelBuilder.getModel(model, true) : model; }); } @@ -247,7 +247,7 @@ ModelBuilder.prototype.define = function defineClass(className, properties, sett ModelClass.getter = {}; ModelClass.setter = {}; - for (var p in properties) { + for (const p in properties) { // e.g excludePropertyList = ['id'] - base properties listed in excludePropertyList will be excluded from the model. // excludeBaseProperties is introduced in SOAP model generation only for now and below logic // handles excludeBaseProperties. Generated SOAP model has base as 'Model' which means 'id' property gets added @@ -256,7 +256,7 @@ ModelBuilder.prototype.define = function defineClass(className, properties, sett // work either for SOAP generator case since generators use ModelDefinition.create to create property in the model // dynamically, that execution path has strict validation where doesn't accept 'id: false' in a property. // See https://github.com/strongloop/loopback-workspace/issues/486 for some more details. - var excludePropertyList = settings['excludeBaseProperties']; + const excludePropertyList = settings['excludeBaseProperties']; // Remove properties that reverted by the subclass of the property from excludePropertyList if (properties[p] === null || properties[p] === false || (excludePropertyList != null && excludePropertyList.indexOf(p) != -1)) { @@ -276,7 +276,7 @@ ModelBuilder.prototype.define = function defineClass(className, properties, sett } } - var modelDefinition = new ModelDefinition(this, className, properties, settings); + const modelDefinition = new ModelDefinition(this, className, properties, settings); this.definitions[className] = modelDefinition; @@ -285,13 +285,13 @@ ModelBuilder.prototype.define = function defineClass(className, properties, sett // keep a pointer to settings as models can use it for configuration ModelClass.settings = modelDefinition.settings; - var idInjection = settings.idInjection; + let idInjection = settings.idInjection; if (idInjection !== false) { // Default to true if undefined idInjection = true; } - var idNames = modelDefinition.idNames(); + let idNames = modelDefinition.idNames(); if (idNames.length > 0) { // id already exists idInjection = false; @@ -310,7 +310,7 @@ ModelBuilder.prototype.define = function defineClass(className, properties, sett if (idProp !== 'id') { Object.defineProperty(ModelClass.prototype, 'id', { get: function() { - var idProp = ModelClass.definition.idNames()[0]; + const idProp = ModelClass.definition.idNames()[0]; return this.__data[idProp]; }, configurable: true, @@ -321,8 +321,8 @@ ModelBuilder.prototype.define = function defineClass(className, properties, sett // Now the id property is an object that consists of multiple keys Object.defineProperty(ModelClass.prototype, 'id', { get: function() { - var compositeId = {}; - var idNames = ModelClass.definition.idNames(); + const compositeId = {}; + const idNames = ModelClass.definition.idNames(); for (var i = 0, p; i < idNames.length; i++) { p = idNames[i]; compositeId[p] = this.__data[p]; @@ -336,9 +336,9 @@ ModelBuilder.prototype.define = function defineClass(className, properties, sett // updateOnly property is added to indicate that this property will appear in // the model for update/updateorcreate operations but and not for create operation. - var forceId = ModelClass.settings.forceId; + let forceId = ModelClass.settings.forceId; if (idNames.length > 0) { - var idName = modelDefinition.idName(); + const idName = modelDefinition.idName(); idProp = ModelClass.definition.rawProperties[idName]; if (idProp.generated && forceId !== false) { forceId = 'auto'; @@ -362,9 +362,9 @@ ModelBuilder.prototype.define = function defineClass(className, properties, sett // A function to loop through the properties ModelClass.forEachProperty = function(cb) { - var props = ModelClass.definition.properties; - var keys = Object.keys(props); - for (var i = 0, n = keys.length; i < n; i++) { + const props = ModelClass.definition.properties; + const keys = Object.keys(props); + for (let i = 0, n = keys.length; i < n; i++) { cb(keys[i], props[keys[i]]); } }; @@ -396,15 +396,15 @@ ModelBuilder.prototype.define = function defineClass(className, properties, sett * merged with base model settings. */ ModelClass.extend = function(className, subClassProperties, subClassSettings) { - var baseClassProperties = ModelClass.definition.properties; - var baseClassSettings = ModelClass.definition.settings; + const baseClassProperties = ModelClass.definition.properties; + const baseClassSettings = ModelClass.definition.settings; subClassProperties = subClassProperties || {}; subClassSettings = subClassSettings || {}; // Check if subclass redefines the ids - var idFound = false; - for (var k in subClassProperties) { + let idFound = false; + for (const k in subClassProperties) { if (subClassProperties[k] && subClassProperties[k].id) { idFound = true; break; @@ -412,17 +412,17 @@ ModelBuilder.prototype.define = function defineClass(className, properties, sett } // Merging the properties - var keys = Object.keys(baseClassProperties); - for (var i = 0, n = keys.length; i < n; i++) { - var key = keys[i]; + const keys = Object.keys(baseClassProperties); + for (let i = 0, n = keys.length; i < n; i++) { + const key = keys[i]; if (idFound && baseClassProperties[key].id) { // don't inherit id properties continue; } if (subClassProperties[key] === undefined) { - var baseProp = baseClassProperties[key]; - var basePropCopy = baseProp; + const baseProp = baseClassProperties[key]; + let basePropCopy = baseProp; if (baseProp && typeof baseProp === 'object') { // Deep clone the base properties basePropCopy = deepMerge(baseProp); @@ -432,8 +432,8 @@ ModelBuilder.prototype.define = function defineClass(className, properties, sett } // Merging the settings - var originalSubclassSettings = subClassSettings; - let mergePolicy = ModelClass.getMergePolicy(subClassSettings); + const originalSubclassSettings = subClassSettings; + const mergePolicy = ModelClass.getMergePolicy(subClassSettings); subClassSettings = mergeSettings(baseClassSettings, subClassSettings, mergePolicy); // Ensure 'base' is not inherited. Note we don't have to delete 'super' @@ -444,7 +444,7 @@ ModelBuilder.prototype.define = function defineClass(className, properties, sett } // Define the subclass - var subClass = modelBuilder.define(className, subClassProperties, subClassSettings, ModelClass); + const subClass = modelBuilder.define(className, subClassProperties, subClassSettings, ModelClass); // Calling the setup function if (typeof subClass.setup === 'function') { @@ -492,7 +492,7 @@ ModelBuilder.prototype.define = function defineClass(className, properties, sett */ function mergeSettings(baseClassSettings, subClassSettings, mergePolicy) { // deep clone base class settings - let mergedSettings = deepMerge(baseClassSettings); + const mergedSettings = deepMerge(baseClassSettings); Object.keys(baseClassSettings).forEach(function(key) { // rank base class settings arrays elements where required @@ -545,15 +545,15 @@ ModelBuilder.prototype.define = function defineClass(className, properties, sett * @param {String} propertyName Name of the property. */ ModelClass.registerProperty = function(propertyName) { - var properties = modelDefinition.build(); - var prop = properties[propertyName]; - var DataType = prop.type; + const properties = modelDefinition.build(); + const prop = properties[propertyName]; + const DataType = prop.type; if (!DataType) { throw new Error(g.f('Invalid type for property %s', propertyName)); } if (prop.required) { - var requiredOptions = typeof prop.required === 'object' ? prop.required : undefined; + const requiredOptions = typeof prop.required === 'object' ? prop.required : undefined; ModelClass.validatesPresenceOf(propertyName, requiredOptions); } if (DataType === Date) ModelClass.validatesDateOf(propertyName); @@ -567,7 +567,7 @@ ModelBuilder.prototype.define = function defineClass(className, properties, sett } }, set: function(value) { - var DataType = ModelClass.definition.properties[propertyName].type; + let DataType = ModelClass.definition.properties[propertyName].type; if (Array.isArray(DataType) || DataType === Array) { DataType = List; } else if (DataType === Date) { @@ -578,7 +578,7 @@ ModelBuilder.prototype.define = function defineClass(className, properties, sett DataType = modelBuilder.resolveType(DataType); } - var persistUndefinedAsNull = ModelClass.definition.settings.persistUndefinedAsNull; + const persistUndefinedAsNull = ModelClass.definition.settings.persistUndefinedAsNull; if (value === undefined && persistUndefinedAsNull) { value = null; } @@ -621,20 +621,20 @@ ModelBuilder.prototype.define = function defineClass(className, properties, sett }); }; - var props = ModelClass.definition.properties; - var keys = Object.keys(props); - var size = keys.length; + const props = ModelClass.definition.properties; + let keys = Object.keys(props); + let size = keys.length; for (i = 0; i < size; i++) { - var propertyName = keys[i]; + const propertyName = keys[i]; ModelClass.registerProperty(propertyName); } - var mixinSettings = settings.mixins || {}; + const mixinSettings = settings.mixins || {}; keys = Object.keys(mixinSettings); size = keys.length; for (i = 0; i < size; i++) { var name = keys[i]; - var mixin = mixinSettings[name]; + let mixin = mixinSettings[name]; if (mixin === true) { mixin = {}; } @@ -696,7 +696,7 @@ function createModelClassCtor(name, ModelBaseClass) { // DataType for Date function DateType(arg) { if (arg === null) return null; - var d = new Date(arg); + const d = new Date(arg); return d; } @@ -770,19 +770,19 @@ ModelBuilder.prototype.defineValueType = function(type, aliases) { * @property {Boolean} index True if the property is an index; false otherwise. */ ModelBuilder.prototype.extendModel = function(model, props) { - var t = this; - var keys = Object.keys(props); - for (var i = 0; i < keys.length; i++) { - var definition = props[keys[i]]; + const t = this; + const keys = Object.keys(props); + for (let i = 0; i < keys.length; i++) { + const definition = props[keys[i]]; t.defineProperty(model, keys[i], definition); } }; ModelBuilder.prototype.copyModel = function copyModel(Master) { - var modelBuilder = this; - var className = Master.modelName; - var md = Master.modelBuilder.definitions[className]; - var Slave = function SlaveModel() { + const modelBuilder = this; + const className = Master.modelName; + const md = Master.modelBuilder.definitions[className]; + const Slave = function SlaveModel() { Master.apply(this, [].slice.call(arguments)); }; @@ -858,7 +858,7 @@ ModelBuilder.prototype.resolveType = function(type) { } if (Array.isArray(type) && type.length > 0) { // For array types, the first item should be the type string - var itemType = this.resolveType(type[0]); + const itemType = this.resolveType(type[0]); if (typeof itemType === 'function') { return [itemType]; } else { @@ -866,7 +866,7 @@ ModelBuilder.prototype.resolveType = function(type) { } } if (typeof type === 'string') { - var schemaType = ModelBuilder.schemaTypes[type.toLowerCase()] || this.models[type]; + const schemaType = ModelBuilder.schemaTypes[type.toLowerCase()] || this.models[type]; if (schemaType) { return schemaType; } else { @@ -906,7 +906,7 @@ ModelBuilder.prototype.resolveType = function(type) { * model name. */ ModelBuilder.prototype.buildModels = function(schemas, createModel) { - var models = {}; + const models = {}; // Normalize the schemas to be an array of the schema objects {name: , properties: {}, options: {}} if (!Array.isArray(schemas)) { @@ -925,9 +925,9 @@ ModelBuilder.prototype.buildModels = function(schemas, createModel) { } } - var relations = []; - for (var s = 0, n = schemas.length; s < n; s++) { - var name = this.getSchemaName(schemas[s].name); + let relations = []; + for (let s = 0, n = schemas.length; s < n; s++) { + const name = this.getSchemaName(schemas[s].name); schemas[s].name = name; var model; if (typeof createModel === 'function') { @@ -940,10 +940,10 @@ ModelBuilder.prototype.buildModels = function(schemas, createModel) { } // Connect the models based on the relations - for (var i = 0; i < relations.length; i++) { - var relation = relations[i]; - var sourceModel = models[relation.source]; - var targetModel = models[relation.target]; + for (let i = 0; i < relations.length; i++) { + const relation = relations[i]; + const sourceModel = models[relation.source]; + const targetModel = models[relation.target]; if (sourceModel && targetModel) { if (typeof sourceModel[relation.type] === 'function') { sourceModel[relation.type](targetModel, {as: relation.as}); @@ -962,7 +962,7 @@ ModelBuilder.prototype.buildModels = function(schemas, createModel) { */ ModelBuilder.prototype.buildModelFromInstance = function(name, json, options) { // Introspect the JSON document to generate a schema - var schema = introspect(json); + const schema = introspect(json); // Create a model for the generated schema return this.define(name, schema, options); diff --git a/lib/model-definition.js b/lib/model-definition.js index 90391144..6e4b4fa2 100644 --- a/lib/model-definition.js +++ b/lib/model-definition.js @@ -4,12 +4,12 @@ // License text available at https://opensource.org/licenses/MIT 'use strict'; -var assert = require('assert'); -var util = require('util'); -var EventEmitter = require('events').EventEmitter; -var traverse = require('traverse'); -var ModelBaseClass = require('./model'); -var ModelBuilder = require('./model-builder'); +const assert = require('assert'); +const util = require('util'); +const EventEmitter = require('events').EventEmitter; +const traverse = require('traverse'); +const ModelBaseClass = require('./model'); +const ModelBuilder = require('./model-builder'); /** * Model definition @@ -35,7 +35,7 @@ function ModelDefinition(modelBuilder, name, properties, settings) { assert(name, 'name is missing'); if (arguments.length === 2 && typeof name === 'object') { - var schema = name; + const schema = name; this.name = schema.name; this.rawProperties = schema.properties || {}; // Keep the raw property definitions this.settings = schema.settings || {}; @@ -60,7 +60,7 @@ require('./types')(ModelDefinition); * @param {String} connectorType The connector type, such as 'oracle' or 'mongodb' */ ModelDefinition.prototype.tableName = function(connectorType) { - var settings = this.settings; + const settings = this.settings; if (settings[connectorType]) { return settings[connectorType].table || settings[connectorType].tableName || this.name; } else { @@ -79,7 +79,7 @@ ModelDefinition.prototype.columnName = function(connectorType, propertyName) { return propertyName; } this.build(); - var property = this.properties[propertyName]; + const property = this.properties[propertyName]; if (property && property[connectorType]) { return property[connectorType].column || property[connectorType].columnName || propertyName; } else { @@ -98,7 +98,7 @@ ModelDefinition.prototype.columnMetadata = function(connectorType, propertyName) return propertyName; } this.build(); - var property = this.properties[propertyName]; + const property = this.properties[propertyName]; if (property && property[connectorType]) { return property[connectorType]; } else { @@ -113,9 +113,9 @@ ModelDefinition.prototype.columnMetadata = function(connectorType, propertyName) */ ModelDefinition.prototype.columnNames = function(connectorType) { this.build(); - var props = this.properties; - var cols = []; - for (var p in props) { + const props = this.properties; + const cols = []; + for (const p in props) { if (props[p][connectorType]) { cols.push(props[p][connectorType].column || props[p][connectorType].columnName || p); } else { @@ -133,11 +133,11 @@ ModelDefinition.prototype.ids = function() { if (this._ids) { return this._ids; } - var ids = []; + const ids = []; this.build(); - var props = this.properties; - for (var key in props) { - var id = props[key].id; + const props = this.properties; + for (const key in props) { + let id = props[key].id; if (!id) { continue; } @@ -167,7 +167,7 @@ ModelDefinition.prototype.idColumnName = function(connectorType) { * @returns {String} property name for ID */ ModelDefinition.prototype.idName = function() { - var id = this.ids()[0]; + const id = this.ids()[0]; if (this.properties.id && this.properties.id.id) { return 'id'; } else { @@ -180,8 +180,8 @@ ModelDefinition.prototype.idName = function() { * @returns {String[]} property names for IDs */ ModelDefinition.prototype.idNames = function() { - var ids = this.ids(); - var names = ids.map(function(id) { + const ids = this.ids(); + const names = ids.map(function(id) { return id.name; }); return names; @@ -193,13 +193,13 @@ ModelDefinition.prototype.idNames = function() { */ ModelDefinition.prototype.indexes = function() { this.build(); - var indexes = {}; + const indexes = {}; if (this.settings.indexes) { - for (var i in this.settings.indexes) { + for (const i in this.settings.indexes) { indexes[i] = this.settings.indexes[i]; } } - for (var p in this.properties) { + for (const p in this.properties) { if (this.properties[p].index) { indexes[p + '_index'] = this.properties[p].index; } @@ -222,9 +222,9 @@ ModelDefinition.prototype.build = function(forceRebuild) { return this.properties; } this.properties = {}; - for (var p in this.rawProperties) { - var prop = this.rawProperties[p]; - var type = this.modelBuilder.resolveType(prop); + for (const p in this.rawProperties) { + const prop = this.rawProperties[p]; + const type = this.modelBuilder.resolveType(prop); if (typeof type === 'string') { this.relations.push({ source: this.name, @@ -233,11 +233,11 @@ ModelDefinition.prototype.build = function(forceRebuild) { as: p, }); } else { - var typeDef = { + const typeDef = { type: type, }; if (typeof prop === 'object' && prop !== null) { - for (var a in prop) { + for (const a in prop) { // Skip the type property but don't delete it Model.extend() shares same instances of the properties from the base class if (a !== 'type') { typeDef[a] = prop[a]; @@ -274,14 +274,14 @@ ModelDefinition.prototype.toJSON = function(forceRebuild) { if (this.json) { return this.json; } - var json = { + const json = { name: this.name, properties: {}, settings: this.settings, }; this.build(forceRebuild); - var mapper = function(val) { + const mapper = function(val) { if (val === undefined || val === null) { return val; } @@ -302,7 +302,7 @@ ModelDefinition.prototype.toJSON = function(forceRebuild) { return val; } }; - for (var p in this.properties) { + for (const p in this.properties) { json.properties[p] = traverse(this.properties[p]).map(mapper); } this.json = json; diff --git a/lib/model-utils.js b/lib/model-utils.js index ee36a60d..9e8f9698 100644 --- a/lib/model-utils.js +++ b/lib/model-utils.js @@ -12,12 +12,12 @@ module.exports = ModelUtils; /*! * Module dependencies */ -var g = require('strong-globalize')(); -var geo = require('./geo'); -var utils = require('./utils'); -var fieldsToArray = utils.fieldsToArray; -var sanitizeQueryOrData = utils.sanitizeQuery; -var BaseModel = require('./model'); +const g = require('strong-globalize')(); +const geo = require('./geo'); +const utils = require('./utils'); +const fieldsToArray = utils.fieldsToArray; +const sanitizeQueryOrData = utils.sanitizeQuery; +const BaseModel = require('./model'); /** * A mixin to contain utility methods for DataAccessObject @@ -48,10 +48,10 @@ ModelUtils._allowExtendedOperators = function(options) { */ ModelUtils._getSetting = function(key, options) { // Check method level options - var val = options && options[key]; + let val = options && options[key]; if (val !== undefined) return val; // Check for settings in model - var m = this.definition; + const m = this.definition; if (m && m.settings) { val = m.settings[key]; if (val !== undefined) { @@ -61,7 +61,7 @@ ModelUtils._getSetting = function(key, options) { } // Check for settings in connector - var ds = this.getDataSource(); + const ds = this.getDataSource(); if (ds && ds.settings) { return ds.settings[key]; } @@ -69,7 +69,7 @@ ModelUtils._getSetting = function(key, options) { return undefined; }; -var operators = { +const operators = { eq: '=', gt: '>', gte: '>=', @@ -98,15 +98,15 @@ ModelUtils._normalize = function(filter, options) { if (!filter) { return undefined; } - var err = null; + let err = null; if ((typeof filter !== 'object') || Array.isArray(filter)) { err = new Error(g.f('The query filter %j is not an {{object}}', filter)); err.statusCode = 400; throw err; } if (filter.limit || filter.skip || filter.offset) { - var limit = Number(filter.limit || 100); - var offset = Number(filter.skip || filter.offset || 0); + const limit = Number(filter.limit || 100); + const offset = Number(filter.skip || filter.offset || 0); if (isNaN(limit) || limit <= 0 || Math.ceil(limit) !== limit) { err = new Error(g.f('The {{limit}} parameter %j is not valid', filter.limit)); @@ -125,24 +125,24 @@ ModelUtils._normalize = function(filter, options) { } if (filter.order) { - var order = filter.order; + let order = filter.order; if (!Array.isArray(order)) { order = [order]; } - var fields = []; - for (var i = 0, m = order.length; i < m; i++) { + const fields = []; + for (let i = 0, m = order.length; i < m; i++) { if (typeof order[i] === 'string') { // Normalize 'f1 ASC, f2 DESC, f3' to ['f1 ASC', 'f2 DESC', 'f3'] - var tokens = order[i].split(/(?:\s*,\s*)+/); - for (var t = 0, n = tokens.length; t < n; t++) { - var token = tokens[t]; + const tokens = order[i].split(/(?:\s*,\s*)+/); + for (let t = 0, n = tokens.length; t < n; t++) { + let token = tokens[t]; if (token.length === 0) { // Skip empty token continue; } - var parts = token.split(/\s+/); + const parts = token.split(/\s+/); if (parts.length >= 2) { - var dir = parts[1].toUpperCase(); + const dir = parts[1].toUpperCase(); if (dir === 'ASC' || dir === 'DESC') { token = parts[0] + ' ' + dir; } else { @@ -178,7 +178,7 @@ ModelUtils._normalize = function(filter, options) { }; function DateType(arg) { - var d = new Date(arg); + const d = new Date(arg); if (isNaN(d.getTime())) { throw new Error(g.f('Invalid date: %s', arg)); } @@ -203,7 +203,7 @@ function BooleanType(arg) { } function NumberType(val) { - var num = Number(val); + const num = Number(val); return !isNaN(num) ? num : val; } @@ -217,14 +217,14 @@ function coerceArray(val) { } // It is an object, check if empty - var props = Object.keys(val); + const props = Object.keys(val); if (props.length === 0) { throw new Error(g.f('Value is an empty {{object}}')); } - var arrayVal = new Array(props.length); - for (var i = 0; i < arrayVal.length; ++i) { + const arrayVal = new Array(props.length); + for (let i = 0; i < arrayVal.length; ++i) { if (!val.hasOwnProperty(i)) { throw new Error(g.f('Value is not an {{array}} or {{object}} with sequential numeric indices')); } @@ -244,8 +244,8 @@ function _normalizeAsArray(result) { } else { // See https://github.com/strongloop/loopback-datasource-juggler/issues/1646 // `ModelBaseClass` normalize the properties to an object such as `{secret: true}` - var keys = []; - for (var k in result) { + const keys = []; + for (const k in result) { if (result[k]) keys.push(k); } return keys; @@ -256,8 +256,8 @@ function _normalizeAsArray(result) { * Get an array of hidden property names */ ModelUtils._getHiddenProperties = function() { - var settings = this.definition.settings || {}; - var result = settings.hiddenProperties || settings.hidden || []; + const settings = this.definition.settings || {}; + const result = settings.hiddenProperties || settings.hidden || []; return _normalizeAsArray(result); }; @@ -265,8 +265,8 @@ ModelUtils._getHiddenProperties = function() { * Get an array of protected property names */ ModelUtils._getProtectedProperties = function() { - var settings = this.definition.settings || {}; - var result = settings.protectedProperties || settings.protected || []; + const settings = this.definition.settings || {}; + const result = settings.protectedProperties || settings.protected || []; return _normalizeAsArray(result); }; @@ -276,7 +276,7 @@ ModelUtils._getProtectedProperties = function() { ModelUtils._getMaxDepthOfQuery = function(options, defaultValue) { options = options || {}; // See https://github.com/strongloop/loopback-datasource-juggler/issues/1651 - var maxDepth = this._getSetting('maxDepthOfQuery', options); + let maxDepth = this._getSetting('maxDepthOfQuery', options); if (maxDepth == null) { maxDepth = defaultValue || 32; } @@ -289,7 +289,7 @@ ModelUtils._getMaxDepthOfQuery = function(options, defaultValue) { ModelUtils._getMaxDepthOfData = function(options, defaultValue) { options = options || {}; // See https://github.com/strongloop/loopback-datasource-juggler/issues/1651 - var maxDepth = this._getSetting('maxDepthOfData', options); + let maxDepth = this._getSetting('maxDepthOfData', options); if (maxDepth == null) { maxDepth = defaultValue || 64; } @@ -300,7 +300,7 @@ ModelUtils._getMaxDepthOfData = function(options, defaultValue) { * Get the prohibitHiddenPropertiesInQuery flag */ ModelUtils._getProhibitHiddenPropertiesInQuery = function(options, defaultValue) { - var flag = this._getSetting('prohibitHiddenPropertiesInQuery', options); + const flag = this._getSetting('prohibitHiddenPropertiesInQuery', options); if (flag == null) return !!defaultValue; return !!flag; }; @@ -312,14 +312,14 @@ ModelUtils._sanitizeQuery = function(query, options) { options = options || {}; // Get settings to normalize `undefined` values - var normalizeUndefinedInQuery = this._getSetting('normalizeUndefinedInQuery', options); + const normalizeUndefinedInQuery = this._getSetting('normalizeUndefinedInQuery', options); // Get setting to prohibit hidden/protected properties in query - var prohibitHiddenPropertiesInQuery = this._getProhibitHiddenPropertiesInQuery(options); + const prohibitHiddenPropertiesInQuery = this._getProhibitHiddenPropertiesInQuery(options); // See https://github.com/strongloop/loopback-datasource-juggler/issues/1651 - var maxDepthOfQuery = this._getMaxDepthOfQuery(options); + const maxDepthOfQuery = this._getMaxDepthOfQuery(options); - var prohibitedKeys = []; + let prohibitedKeys = []; // Check violation of keys if (prohibitHiddenPropertiesInQuery) { prohibitedKeys = this._getHiddenProperties(); @@ -355,24 +355,24 @@ ModelUtils._sanitizeData = function(data, options) { * @private */ ModelUtils._coerce = function(where, options) { - var self = this; + const self = this; if (where == null) { return where; } options = options || {}; - var err; + let err; if (typeof where !== 'object' || Array.isArray(where)) { err = new Error(g.f('The where clause %j is not an {{object}}', where)); err.statusCode = 400; throw err; } - var props = self.definition.properties; - for (var p in where) { + const props = self.definition.properties; + for (const p in where) { // Handle logical operators if (p === 'and' || p === 'or' || p === 'nor') { - var clauses = where[p]; + let clauses = where[p]; try { clauses = coerceArray(clauses); } catch (e) { @@ -381,13 +381,13 @@ ModelUtils._coerce = function(where, options) { throw err; } - for (var k = 0; k < clauses.length; k++) { + for (let k = 0; k < clauses.length; k++) { self._coerce(clauses[k], options); } continue; } - var DataType = props[p] && props[p].type; + let DataType = props[p] && props[p].type; if (!DataType) { continue; } @@ -424,15 +424,15 @@ ModelUtils._coerce = function(where, options) { continue; } - var val = where[p]; + let val = where[p]; if (val === null || val === undefined) { continue; } // Check there is an operator - var operator = null; - var exp = val; + let operator = null; + const exp = val; if (val.constructor === Object) { - for (var op in operators) { + for (const op in operators) { if (op in val) { val = val[op]; operator = op; @@ -493,10 +493,10 @@ ModelUtils._coerce = function(where, options) { // NOOP when not coercable into an array. } - var allowExtendedOperators = self._allowExtendedOperators(options); + const allowExtendedOperators = self._allowExtendedOperators(options); // Coerce the array items if (Array.isArray(val)) { - for (var i = 0; i < val.length; i++) { + for (let i = 0; i < val.length; i++) { if (val[i] !== null && val[i] !== undefined) { if (!(val[i] instanceof RegExp)) { val[i] = DataType(val[i]); @@ -517,7 +517,7 @@ ModelUtils._coerce = function(where, options) { // Do not coerce object values when extended operators are allowed } else { if (!allowExtendedOperators) { - var extendedOperators = Object.keys(val).filter(function(k) { + const extendedOperators = Object.keys(val).filter(function(k) { return k[0] === '$'; }); if (extendedOperators.length) { @@ -538,7 +538,7 @@ ModelUtils._coerce = function(where, options) { } // Rebuild {property: {operator: value}} if (operator && operator !== 'eq') { - var value = {}; + const value = {}; value[operator] = val; if (exp.options) { // Keep options for operators diff --git a/lib/model.js b/lib/model.js index e431c00b..d4c2aad1 100644 --- a/lib/model.js +++ b/lib/model.js @@ -16,22 +16,22 @@ module.exports = ModelBaseClass; * Module dependencies */ -var g = require('strong-globalize')(); -var util = require('util'); -var jutil = require('./jutil'); -var List = require('./list'); -var DataAccessUtils = require('./model-utils'); -var Observer = require('./observer'); -var Hookable = require('./hooks'); -var validations = require('./validations'); -var _extend = util._extend; -var utils = require('./utils'); -var fieldsToArray = utils.fieldsToArray; -var uuid = require('uuid'); -var shortid = require('shortid'); +const g = require('strong-globalize')(); +const util = require('util'); +const jutil = require('./jutil'); +const List = require('./list'); +const DataAccessUtils = require('./model-utils'); +const Observer = require('./observer'); +const Hookable = require('./hooks'); +const validations = require('./validations'); +const _extend = util._extend; +const utils = require('./utils'); +const fieldsToArray = utils.fieldsToArray; +const uuid = require('uuid'); +const shortid = require('shortid'); // Set up an object for quick lookup -var BASE_TYPES = { +const BASE_TYPES = { 'String': true, 'Boolean': true, 'Number': true, @@ -73,8 +73,8 @@ function ModelBaseClass(data, options) { * @private */ ModelBaseClass.prototype._initProperties = function(data, options) { - var self = this; - var ctor = this.constructor; + const self = this; + const ctor = this.constructor; if (typeof data !== 'undefined' && data !== null && data.constructor && typeof (data.constructor) !== 'function') { @@ -85,7 +85,7 @@ ModelBaseClass.prototype._initProperties = function(data, options) { // Convert the data to be plain object to avoid pollutions data = data.toObject(false); } - var properties = _extend({}, ctor.definition.properties); + const properties = _extend({}, ctor.definition.properties); data = data || {}; if (typeof ctor.applyProperties === 'function') { @@ -93,9 +93,9 @@ ModelBaseClass.prototype._initProperties = function(data, options) { } options = options || {}; - var applySetters = options.applySetters; - var applyDefaultValues = options.applyDefaultValues; - var strict = options.strict; + const applySetters = options.applySetters; + const applyDefaultValues = options.applyDefaultValues; + let strict = options.strict; if (strict === undefined) { strict = ctor.definition.settings.strict; @@ -105,7 +105,7 @@ ModelBaseClass.prototype._initProperties = function(data, options) { '{{`Validation Error`}} for unknown properties,', ctor.modelName); } - var persistUndefinedAsNull = ctor.definition.settings.persistUndefinedAsNull; + const persistUndefinedAsNull = ctor.definition.settings.persistUndefinedAsNull; if (ctor.hideInternalProperties) { // Object.defineProperty() is expensive. We only try to make the internal @@ -177,7 +177,7 @@ ModelBaseClass.prototype._initProperties = function(data, options) { this.__cachedRelations = data.__cachedRelations; } - var keys = Object.keys(data); + let keys = Object.keys(data); if (Array.isArray(options.fields)) { keys = keys.filter(function(k) { @@ -185,8 +185,8 @@ ModelBaseClass.prototype._initProperties = function(data, options) { }); } - var size = keys.length; - var p, propVal; + let size = keys.length; + let p, propVal; for (var k = 0; k < size; k++) { p = keys[k]; propVal = data[p]; @@ -206,14 +206,14 @@ ModelBaseClass.prototype._initProperties = function(data, options) { self.__data[p] = propVal; } } else if (ctor.relations[p]) { - var relationType = ctor.relations[p].type; + const relationType = ctor.relations[p].type; var modelTo; if (!properties[p]) { modelTo = ctor.relations[p].modelTo || ModelBaseClass; - var multiple = ctor.relations[p].multiple; - var typeName = multiple ? 'Array' : modelTo.modelName; - var propType = multiple ? [modelTo] : modelTo; + const multiple = ctor.relations[p].multiple; + const typeName = multiple ? 'Array' : modelTo.modelName; + const propType = multiple ? [modelTo] : modelTo; properties[p] = {name: typeName, type: propType}; /* Issue #1252 this.setStrict(false); @@ -226,7 +226,7 @@ ModelBaseClass.prototype._initProperties = function(data, options) { self.__data[ctor.relations[p].keyFrom] = propVal[ctor.relations[p].keyTo]; if (ctor.relations[p].options.embedsProperties) { - var fields = fieldsToArray(ctor.relations[p].properties, + const fields = fieldsToArray(ctor.relations[p].properties, modelTo.definition.properties, modelTo.settings.strict); if (!~fields.indexOf(ctor.relations[p].keyTo)) { fields.push(ctor.relations[p].keyTo); @@ -275,11 +275,11 @@ ModelBaseClass.prototype._initProperties = function(data, options) { for (k = 0; k < size; k++) { p = keys[k]; propVal = self.__data[p]; - var type = properties[p].type; + const type = properties[p].type; // Set default values if (applyDefaultValues && propVal === undefined) { - var def = properties[p]['default']; + let def = properties[p]['default']; if (def !== undefined) { if (typeof def === 'function') { if (def === Date) { @@ -301,7 +301,7 @@ ModelBaseClass.prototype._initProperties = function(data, options) { // Set default value using a named function if (applyDefaultValues && propVal === undefined) { - var defn = properties[p].defaultFn; + const defn = properties[p].defaultFn; switch (defn) { case undefined: break; @@ -381,7 +381,7 @@ ModelBaseClass.defineProperty = function(prop, params) { * @returns {String} Name of property type */ ModelBaseClass.getPropertyType = function(propName) { - var prop = this.definition.properties[propName]; + const prop = this.definition.properties[propName]; if (!prop) { // The property is not part of the definition return null; @@ -421,7 +421,7 @@ ModelBaseClass.toString = function() { */ ModelBaseClass.prototype.toObject = function(onlySchema, removeHidden, removeProtected) { if (typeof onlySchema === 'object' && onlySchema != null) { - var options = onlySchema; + const options = onlySchema; onlySchema = options.onlySchema; removeHidden = options.removeHidden; removeProtected = options.removeProtected; @@ -429,22 +429,22 @@ ModelBaseClass.prototype.toObject = function(onlySchema, removeHidden, removePro if (onlySchema === undefined) { onlySchema = true; } - var data = {}; - var self = this; - var Model = this.constructor; + const data = {}; + const self = this; + const Model = this.constructor; // if it is already an Object if (Model === Object) { return self; } - var strict = this.__strict; - var schemaLess = (strict === false) || !onlySchema; - var persistUndefinedAsNull = Model.definition.settings.persistUndefinedAsNull; + const strict = this.__strict; + const schemaLess = (strict === false) || !onlySchema; + const persistUndefinedAsNull = Model.definition.settings.persistUndefinedAsNull; - var props = Model.definition.properties; - var keys = Object.keys(props); - var propertyName, val; + const props = Model.definition.properties; + let keys = Object.keys(props); + let propertyName, val; for (var i = 0; i < keys.length; i++) { propertyName = keys[i]; @@ -482,7 +482,7 @@ ModelBaseClass.prototype.toObject = function(onlySchema, removeHidden, removePro // If the property is not declared in the model definition, no setter will be // triggered to add it to __data keys = Object.keys(self); - var size = keys.length; + let size = keys.length; for (i = 0; i < size; i++) { propertyName = keys[i]; if (props[propertyName]) { @@ -529,7 +529,7 @@ ModelBaseClass.prototype.toObject = function(onlySchema, removeHidden, removePro if (removeProtected && Model.isProtectedProperty(propertyName)) { continue; } - var ownVal = self[propertyName]; + const ownVal = self[propertyName]; // The ownVal can be a relation function val = (ownVal !== undefined && (typeof ownVal !== 'function')) ? ownVal : self.__data[propertyName]; if (typeof val === 'function') { @@ -555,9 +555,9 @@ ModelBaseClass.prototype.toObject = function(onlySchema, removeHidden, removePro * @param {string[]} arr An array of strings */ function asObjectMap(arr) { - var obj = {}; + const obj = {}; if (Array.isArray(arr)) { - for (var i = 0; i < arr.length; i++) { + for (let i = 0; i < arr.length; i++) { obj[arr[i]] = true; } return obj; @@ -570,8 +570,8 @@ function asObjectMap(arr) { * @returns {Boolean} true or false if protected or not. */ ModelBaseClass.isProtectedProperty = function(propertyName) { - var settings = (this.definition && this.definition.settings) || {}; - var protectedProperties = settings.protectedProperties || settings.protected; + const settings = (this.definition && this.definition.settings) || {}; + const protectedProperties = settings.protectedProperties || settings.protected; settings.protectedProperties = asObjectMap(protectedProperties); return settings.protectedProperties[propertyName]; }; @@ -582,8 +582,8 @@ ModelBaseClass.isProtectedProperty = function(propertyName) { * @returns {Boolean} true or false if hidden or not. */ ModelBaseClass.isHiddenProperty = function(propertyName) { - var settings = (this.definition && this.definition.settings) || {}; - var hiddenProperties = settings.hiddenProperties || settings.hidden; + const settings = (this.definition && this.definition.settings) || {}; + const hiddenProperties = settings.hiddenProperties || settings.hidden; settings.hiddenProperties = asObjectMap(hiddenProperties); return settings.hiddenProperties[propertyName]; }; @@ -593,7 +593,7 @@ ModelBaseClass.prototype.toJSON = function() { }; ModelBaseClass.prototype.fromObject = function(obj) { - for (var key in obj) { + for (const key in obj) { this[key] = obj[key]; } }; @@ -604,8 +604,8 @@ ModelBaseClass.prototype.fromObject = function(obj) { * initial state. */ ModelBaseClass.prototype.reset = function() { - var obj = this; - for (var k in obj) { + const obj = this; + for (const k in obj) { if (k !== 'id' && !obj.constructor.dataSource.definitions[obj.constructor.modelName].properties[k]) { delete obj[k]; } @@ -615,11 +615,11 @@ ModelBaseClass.prototype.reset = function() { // Node v0.11+ allows custom inspect functions to return an object // instead of string. That way options like `showHidden` and `colors` // can be preserved. -var versionParts = process.versions && process.versions.node ? +const versionParts = process.versions && process.versions.node ? process.versions.node.split(/\./g).map(function(v) { return +v; }) : [1, 0, 0]; // browserify ships 1.0-compatible version of util.inspect -var INSPECT_SUPPORTS_OBJECT_RETVAL = +const INSPECT_SUPPORTS_OBJECT_RETVAL = versionParts[0] > 0 || versionParts[1] > 11 || (versionParts[0] === 11 && versionParts[1] >= 14); @@ -648,8 +648,8 @@ ModelBaseClass.mixin = function(anotherClass, options) { this.modelBuilder.mixins.applyMixin(this, anotherClass, options); } else { if (anotherClass.prototype instanceof ModelBaseClass) { - var props = anotherClass.definition.properties; - for (var i in props) { + const props = anotherClass.definition.properties; + for (const i in props) { if (this.definition.properties[i]) { continue; } @@ -780,7 +780,7 @@ ModelBaseClass.getMergePolicy = function(options) { // + fix for description arrays that should not be merged // + fix for relations that should patch matching relations // + ranking of ACLs - var mergePolicy = { + let mergePolicy = { description: {replace: true}, // string or array properties: {patch: true}, // object hidden: {replace: false}, // array @@ -789,7 +789,7 @@ ModelBaseClass.getMergePolicy = function(options) { acls: {rank: true}, // array }; - var config = (options || {}).configureModelMerge; + const config = (options || {}).configureModelMerge; if (config === true) { // NOTE: recommended merge policy from datasource-juggler v3.6.2 diff --git a/lib/observer.js b/lib/observer.js index d26e59e2..1e783401 100644 --- a/lib/observer.js +++ b/lib/observer.js @@ -4,8 +4,8 @@ // License text available at https://opensource.org/licenses/MIT 'use strict'; -var async = require('async'); -var utils = require('./utils'); +const async = require('async'); +const utils = require('./utils'); module.exports = ObserverMixin; @@ -74,7 +74,7 @@ ObserverMixin.observe = function(operation, listener) { ObserverMixin.removeObserver = function(operation, listener) { if (!(this._observers && this._observers[operation])) return; - var index = this._observers[operation].indexOf(listener); + const index = this._observers[operation].indexOf(listener); if (index !== -1) { return this._observers[operation].splice(index, 1); } @@ -127,7 +127,7 @@ ObserverMixin.clearObservers = function(operation) { * have finished. */ ObserverMixin.notifyObserversOf = function(operation, context, callback) { - var self = this; + const self = this; if (!callback) callback = utils.createPromiseCallback(); function createNotifier(op) { @@ -141,14 +141,14 @@ ObserverMixin.notifyObserversOf = function(operation, context, callback) { } if (Array.isArray(operation)) { - var tasks = []; - for (var i = 0, n = operation.length; i < n; i++) { + const tasks = []; + for (let i = 0, n = operation.length; i < n; i++) { tasks.push(createNotifier(operation[i])); } return async.waterfall(tasks, callback); } - var observers = this._observers && this._observers[operation]; + const observers = this._observers && this._observers[operation]; this._notifyBaseObservers(operation, context, function doNotify(err) { if (err) return callback(err, context); @@ -157,7 +157,7 @@ ObserverMixin.notifyObserversOf = function(operation, context, callback) { async.eachSeries( observers, function notifySingleObserver(fn, next) { - var retval = fn(context, next); + const retval = fn(context, next); if (retval && typeof retval.then === 'function') { retval.then( function() { next(); return null; }, @@ -217,7 +217,7 @@ ObserverMixin._notifyBaseObservers = function(operation, context, callback) { * @returns {*} */ ObserverMixin.notifyObserversAround = function(operation, context, fn, callback) { - var self = this; + const self = this; context = context || {}; // Add callback to the context object so that an observer can skip other // ones by calling the callback function directly and not calling next @@ -230,23 +230,23 @@ ObserverMixin.notifyObserversAround = function(operation, context, fn, callback) if (err) return callback(err); function cbForWork(err) { - var args = [].slice.call(arguments, 0); + const args = [].slice.call(arguments, 0); if (err) return callback.apply(null, args); // Find the list of params from the callback in addition to err - var returnedArgs = args.slice(1); + const returnedArgs = args.slice(1); // Set up the array of results context.results = returnedArgs; // Notify after observers self.notifyObserversOf('after ' + operation, context, function(err, context) { if (err) return callback(err, context); - var results = returnedArgs; + let results = returnedArgs; if (context && Array.isArray(context.results)) { // Pickup the results from context results = context.results; } // Build the list of params for final callback - var args = [err].concat(results); + const args = [err].concat(results); callback.apply(null, args); }); } diff --git a/lib/relation-definition.js b/lib/relation-definition.js index b73e614a..7e5e4eb8 100644 --- a/lib/relation-definition.js +++ b/lib/relation-definition.js @@ -8,23 +8,23 @@ /*! * Dependencies */ -var assert = require('assert'); -var util = require('util'); -var async = require('async'); -var utils = require('./utils'); -var i8n = require('inflection'); -var defineScope = require('./scope.js').defineScope; -var g = require('strong-globalize')(); -var mergeQuery = utils.mergeQuery; -var idEquals = utils.idEquals; -var idsHaveDuplicates = utils.idsHaveDuplicates; -var ModelBaseClass = require('./model.js'); -var applyFilter = require('./connectors/memory').applyFilter; -var ValidationError = require('./validations.js').ValidationError; -var deprecated = require('depd')('loopback-datasource-juggler'); -var debug = require('debug')('loopback:relations'); +const assert = require('assert'); +const util = require('util'); +const async = require('async'); +const utils = require('./utils'); +const i8n = require('inflection'); +const defineScope = require('./scope.js').defineScope; +const g = require('strong-globalize')(); +const mergeQuery = utils.mergeQuery; +const idEquals = utils.idEquals; +const idsHaveDuplicates = utils.idsHaveDuplicates; +const ModelBaseClass = require('./model.js'); +const applyFilter = require('./connectors/memory').applyFilter; +const ValidationError = require('./validations.js').ValidationError; +const deprecated = require('depd')('loopback-datasource-juggler'); +const debug = require('debug')('loopback:relations'); -var RelationTypes = { +const RelationTypes = { belongsTo: 'belongsTo', hasMany: 'hasMany', hasOne: 'hasOne', @@ -34,7 +34,7 @@ var RelationTypes = { embedsMany: 'embedsMany', }; -var RelationClasses = { +const RelationClasses = { belongsTo: BelongsTo, hasMany: HasMany, hasManyThrough: HasManyThrough, @@ -64,8 +64,8 @@ function normalizeType(type) { if (!type) { return type; } - var t1 = type.toLowerCase(); - for (var t2 in RelationTypes) { + const t1 = type.toLowerCase(); + for (const t2 in RelationTypes) { if (t2.toLowerCase() === t1) { return t2; } @@ -74,8 +74,8 @@ function normalizeType(type) { } function extendScopeMethods(definition, scopeMethods, ext) { - var customMethods = []; - var relationClass = RelationClasses[definition.type]; + let customMethods = []; + let relationClass = RelationClasses[definition.type]; if (definition.type === RelationTypes.hasMany && definition.modelThrough) { relationClass = RelationClasses.hasManyThrough; } @@ -84,13 +84,13 @@ function extendScopeMethods(definition, scopeMethods, ext) { } else if (typeof ext === 'object') { function createFunc(definition, relationMethod) { return function() { - var relation = new relationClass(definition, this); + const relation = new relationClass(definition, this); return relationMethod.apply(relation, arguments); }; } - for (var key in ext) { - var relationMethod = ext[key]; - var method = scopeMethods[key] = createFunc(definition, relationMethod); + for (const key in ext) { + const relationMethod = ext[key]; + const method = scopeMethods[key] = createFunc(definition, relationMethod); if (relationMethod.shared) { sharedMethod(definition, key, method, relationMethod); } @@ -101,7 +101,7 @@ function extendScopeMethods(definition, scopeMethods, ext) { } function bindRelationMethods(relation, relationMethod, definition) { - var methods = definition.methods || {}; + const methods = definition.methods || {}; Object.keys(methods).forEach(function(m) { if (typeof methods[m] !== 'function') return; relationMethod[m] = methods[m].bind(relation); @@ -155,14 +155,14 @@ function RelationDefinition(definition) { } RelationDefinition.prototype.toJSON = function() { - var polymorphic = typeof this.polymorphic === 'object'; + const polymorphic = typeof this.polymorphic === 'object'; - var modelToName = this.modelTo && this.modelTo.modelName; + let modelToName = this.modelTo && this.modelTo.modelName; if (!modelToName && polymorphic && this.type === 'belongsTo') { modelToName = ''; } - var json = { + const json = { name: this.name, type: this.type, modelFrom: this.modelFrom.modelName, @@ -187,22 +187,22 @@ RelationDefinition.prototype.toJSON = function() { * @param {Function} function to define */ RelationDefinition.prototype.defineMethod = function(name, fn) { - var relationClass = RelationClasses[this.type]; - var relationName = this.name; - var modelFrom = this.modelFrom; - var definition = this; - var method; + const relationClass = RelationClasses[this.type]; + const relationName = this.name; + const modelFrom = this.modelFrom; + const definition = this; + let method; if (definition.multiple) { - var scope = this.modelFrom.scopes[this.name]; + const scope = this.modelFrom.scopes[this.name]; if (!scope) throw new Error(g.f('Unknown relation {{scope}}: %s', this.name)); method = scope.defineMethod(name, function() { - var relation = new relationClass(definition, this); + const relation = new relationClass(definition, this); return fn.apply(relation, arguments); }); } else { definition.methods[name] = fn; method = function() { - var rel = this[relationName]; + const rel = this[relationName]; return rel[name].apply(rel, arguments); }; } @@ -223,14 +223,14 @@ RelationDefinition.prototype.applyScope = function(modelInstance, filter) { filter.where = filter.where || {}; if ((this.type !== 'belongsTo' || this.type === 'hasOne') && typeof this.polymorphic === 'object') { // polymorphic - var discriminator = this.polymorphic.discriminator; + const discriminator = this.polymorphic.discriminator; if (this.polymorphic.invert) { filter.where[discriminator] = this.modelTo.modelName; } else { filter.where[discriminator] = this.modelFrom.modelName; } } - var scope; + let scope; if (typeof this.scope === 'function') { scope = this.scope.call(this, modelInstance, filter); } else { @@ -247,7 +247,7 @@ RelationDefinition.prototype.applyScope = function(modelInstance, filter) { * @param {Object} target */ RelationDefinition.prototype.applyProperties = function(modelInstance, obj) { - var source = modelInstance, target = obj; + let source = modelInstance, target = obj; if (this.options.invertProperties) { source = obj; target = modelInstance; @@ -256,9 +256,9 @@ RelationDefinition.prototype.applyProperties = function(modelInstance, obj) { target = target.__data[this.name] = {}; target[this.keyTo] = source[this.keyTo]; } - var k, key; + let k, key; if (typeof this.properties === 'function') { - var data = this.properties.call(this, source, target); + const data = this.properties.call(this, source, target); for (k in data) { target[k] = data[k]; } @@ -275,7 +275,7 @@ RelationDefinition.prototype.applyProperties = function(modelInstance, obj) { } if ((this.type !== 'belongsTo' || this.type === 'hasOne') && typeof this.polymorphic === 'object') { // polymorphic - var discriminator = this.polymorphic.discriminator; + const discriminator = this.polymorphic.discriminator; if (this.polymorphic.invert) { target[discriminator] = this.modelTo.modelName; } else { @@ -313,9 +313,9 @@ Relation.prototype.getCache = function() { }; Relation.prototype.callScopeMethod = function(methodName) { - var args = Array.prototype.slice.call(arguments, 1); - var modelInstance = this.modelInstance; - var rel = modelInstance[this.definition.name]; + const args = Array.prototype.slice.call(arguments, 1); + const modelInstance = this.modelInstance; + const rel = modelInstance[this.definition.name]; if (rel && typeof rel[methodName] === 'function') { return rel[methodName].apply(rel, args); } else { @@ -352,10 +352,10 @@ function HasMany(definition, modelInstance) { util.inherits(HasMany, Relation); HasMany.prototype.removeFromCache = function(id) { - var cache = this.modelInstance.__cachedRelations[this.definition.name]; - var idName = this.definition.modelTo.definition.idName(); + const cache = this.modelInstance.__cachedRelations[this.definition.name]; + const idName = this.definition.modelTo.definition.idName(); if (Array.isArray(cache)) { - for (var i = 0, n = cache.length; i < n; i++) { + for (let i = 0, n = cache.length; i < n; i++) { if (idEquals(cache[i][idName], id)) { return cache.splice(i, 1); } @@ -368,13 +368,13 @@ HasMany.prototype.addToCache = function(inst) { if (!inst) { return; } - var cache = this.modelInstance.__cachedRelations[this.definition.name]; + let cache = this.modelInstance.__cachedRelations[this.definition.name]; if (cache === undefined) { cache = this.modelInstance.__cachedRelations[this.definition.name] = []; } - var idName = this.definition.modelTo.definition.idName(); + const idName = this.definition.modelTo.definition.idName(); if (Array.isArray(cache)) { - for (var i = 0, n = cache.length; i < n; i++) { + for (let i = 0, n = cache.length; i < n; i++) { if (idEquals(cache[i][idName], inst[idName])) { cache[i] = inst; return; @@ -539,8 +539,8 @@ function lookupModel(models, modelName) { if (models[modelName]) { return models[modelName]; } - var lookupClassName = modelName.toLowerCase(); - for (var name in models) { + const lookupClassName = modelName.toLowerCase(); + for (const name in models) { if (name.toLowerCase() === lookupClassName) { return models[name]; } @@ -557,14 +557,14 @@ function lookupModel(models, modelName) { * @return {Object} modelTo Instance of the 'to' model */ function lookupModelTo(modelFrom, modelToRef, params, singularize) { - var modelTo; + let modelTo; if (typeof modelToRef !== 'string') { // modelToRef might already be an instance of model modelTo = modelToRef; } else { // lookup modelTo based on relation params and modelToRef - var modelToName; + let modelToName; modelTo = params.model || modelToRef; // modelToRef might be modelTo name if (typeof modelTo === 'string') { @@ -576,7 +576,7 @@ function lookupModelTo(modelFrom, modelToRef, params, singularize) { if (!modelTo) { // lookup by modelTo name was not successful. Now looking-up by relationTo name - var relationToName = params.as || modelToRef; // modelToRef might be relationTo name + const relationToName = params.as || modelToRef; // modelToRef might be relationTo name modelToName = (singularize ? i8n.singularize(relationToName) : relationToName).toLowerCase(); modelTo = lookupModel(modelFrom.dataSource.modelBuilder.models, modelToName); } @@ -611,7 +611,7 @@ function normalizePolymorphic(polymorphic, relationName) { assert(polymorphic, 'polymorphic param can\'t be false, null or undefined'); assert(!Array.isArray(polymorphic, 'unexpected type for polymorphic param: \'Array\'')); - var selector; + let selector; if (typeof polymorphic === 'string') { // relation type is different from belongsTo (hasMany, hasManyThrough, hasAndBelongsToMany, ...) @@ -671,17 +671,17 @@ function normalizePolymorphic(polymorphic, relationName) { * @property {Object} model Model object */ RelationDefinition.hasMany = function hasMany(modelFrom, modelToRef, params) { - var thisClassName = modelFrom.modelName; + const thisClassName = modelFrom.modelName; params = params || {}; normalizeRelationAs(params, modelToRef); - var modelTo = lookupModelTo(modelFrom, modelToRef, params, true); + const modelTo = lookupModelTo(modelFrom, modelToRef, params, true); - var relationName = params.as || i8n.camelize(modelTo.pluralModelName, true); - var fk = params.foreignKey || i8n.camelize(thisClassName + '_id', true); - var keyThrough = params.keyThrough || i8n.camelize(modelTo.modelName + '_id', true); + const relationName = params.as || i8n.camelize(modelTo.pluralModelName, true); + let fk = params.foreignKey || i8n.camelize(thisClassName + '_id', true); + let keyThrough = params.keyThrough || i8n.camelize(modelTo.modelName + '_id', true); - var pkName = params.primaryKey || modelFrom.dataSource.idName(modelFrom.modelName) || 'id'; - var discriminator, polymorphic; + const pkName = params.primaryKey || modelFrom.dataSource.idName(modelFrom.modelName) || 'id'; + let discriminator, polymorphic; if (params.polymorphic) { polymorphic = normalizePolymorphic(params.polymorphic, relationName); @@ -698,7 +698,7 @@ RelationDefinition.hasMany = function hasMany(modelFrom, modelToRef, params) { } } - var definition = new RelationDefinition({ + const definition = new RelationDefinition({ name: relationName, type: RelationTypes.hasMany, modelFrom: modelFrom, @@ -724,23 +724,23 @@ RelationDefinition.hasMany = function hasMany(modelFrom, modelToRef, params) { modelTo.dataSource.defineForeignKey(modelTo.modelName, fk, modelFrom.modelName, pkName); } - var scopeMethods = { + const scopeMethods = { findById: scopeMethod(definition, 'findById'), destroy: scopeMethod(definition, 'destroyById'), updateById: scopeMethod(definition, 'updateById'), exists: scopeMethod(definition, 'exists'), }; - var findByIdFunc = scopeMethods.findById; + const findByIdFunc = scopeMethods.findById; modelFrom.prototype['__findById__' + relationName] = findByIdFunc; - var destroyByIdFunc = scopeMethods.destroy; + const destroyByIdFunc = scopeMethods.destroy; modelFrom.prototype['__destroyById__' + relationName] = destroyByIdFunc; - var updateByIdFunc = scopeMethods.updateById; + const updateByIdFunc = scopeMethods.updateById; modelFrom.prototype['__updateById__' + relationName] = updateByIdFunc; - var existsByIdFunc = scopeMethods.exists; + const existsByIdFunc = scopeMethods.exists; modelFrom.prototype['__exists__' + relationName] = existsByIdFunc; if (definition.modelThrough) { @@ -748,21 +748,21 @@ RelationDefinition.hasMany = function hasMany(modelFrom, modelToRef, params) { scopeMethods.add = scopeMethod(definition, 'add'); scopeMethods.remove = scopeMethod(definition, 'remove'); - var addFunc = scopeMethods.add; + const addFunc = scopeMethods.add; modelFrom.prototype['__link__' + relationName] = addFunc; - var removeFunc = scopeMethods.remove; + const removeFunc = scopeMethods.remove; modelFrom.prototype['__unlink__' + relationName] = removeFunc; } else { scopeMethods.create = scopeMethod(definition, 'create'); scopeMethods.build = scopeMethod(definition, 'build'); } - var customMethods = extendScopeMethods(definition, scopeMethods, params.scopeMethods); + const customMethods = extendScopeMethods(definition, scopeMethods, params.scopeMethods); - for (var i = 0; i < customMethods.length; i++) { - var methodName = customMethods[i]; - var method = scopeMethods[methodName]; + for (let i = 0; i < customMethods.length; i++) { + const methodName = customMethods[i]; + const method = scopeMethods[methodName]; if (typeof method === 'function' && method.shared === true) { modelFrom.prototype['__' + methodName + '__' + relationName] = method; } @@ -770,18 +770,18 @@ RelationDefinition.hasMany = function hasMany(modelFrom, modelToRef, params) { // Mix the property and scoped methods into the prototype class defineScope(modelFrom.prototype, params.through || modelTo, relationName, function() { - var filter = {}; + const filter = {}; filter.where = {}; filter.where[fk] = this[pkName]; definition.applyScope(this, filter); if (definition.modelThrough) { - var throughRelationName; + let throughRelationName; // find corresponding belongsTo relations from through model as collect - for (var r in definition.modelThrough.relations) { - var relation = definition.modelThrough.relations[r]; + for (const r in definition.modelThrough.relations) { + const relation = definition.modelThrough.relations[r]; // should be a belongsTo and match modelTo and keyThrough // if relation is polymorphic then check keyThrough only @@ -810,16 +810,16 @@ RelationDefinition.hasMany = function hasMany(modelFrom, modelToRef, params) { }; function scopeMethod(definition, methodName) { - var relationClass = RelationClasses[definition.type]; + let relationClass = RelationClasses[definition.type]; if (definition.type === RelationTypes.hasMany && definition.modelThrough) { relationClass = RelationClasses.hasManyThrough; } - var method = function() { - var relation = new relationClass(definition, this); + const method = function() { + const relation = new relationClass(definition, this); return relation[methodName].apply(relation, arguments); }; - var relationMethod = relationClass.prototype[methodName]; + const relationMethod = relationClass.prototype[methodName]; if (relationMethod.shared) { sharedMethod(definition, methodName, method, relationMethod); } @@ -845,14 +845,14 @@ HasMany.prototype.findById = function(fkId, options, cb) { cb = options; options = {}; } - var modelTo = this.definition.modelTo; - var modelFrom = this.definition.modelFrom; - var fk = this.definition.keyTo; - var pk = this.definition.keyFrom; - var modelInstance = this.modelInstance; + const modelTo = this.definition.modelTo; + const modelFrom = this.definition.modelFrom; + const fk = this.definition.keyTo; + const pk = this.definition.keyFrom; + const modelInstance = this.modelInstance; - var idName = this.definition.modelTo.definition.idName(); - var filter = {}; + const idName = this.definition.modelTo.definition.idName(); + const filter = {}; filter.where = {}; filter.where[idName] = fkId; filter.where[fk] = modelInstance[pk]; @@ -899,9 +899,9 @@ HasMany.prototype.exists = function(fkId, options, cb) { cb = options; options = {}; } - var fk = this.definition.keyTo; - var pk = this.definition.keyFrom; - var modelInstance = this.modelInstance; + const fk = this.definition.keyTo; + const pk = this.definition.keyFrom; + const modelInstance = this.modelInstance; cb = cb || utils.createPromiseCallback(); this.findById(fkId, function(err, inst) { @@ -934,14 +934,14 @@ HasMany.prototype.updateById = function(fkId, data, options, cb) { options = {}; } cb = cb || utils.createPromiseCallback(); - var fk = this.definition.keyTo; + const fk = this.definition.keyTo; this.findById(fkId, options, function(err, inst) { if (err) { return cb && cb(err); } // Ensure Foreign Key cannot be changed! - var fkErr = preventFkOverride(inst, data, fk); + const fkErr = preventFkOverride(inst, data, fk); if (fkErr) return cb(fkErr); inst.updateAttributes(data, options, cb); }); @@ -960,7 +960,7 @@ HasMany.prototype.destroyById = function(fkId, options, cb) { options = {}; } cb = cb || utils.createPromiseCallback(); - var self = this; + const self = this; this.findById(fkId, options, function(err, inst) { if (err) { return cb(err); @@ -971,9 +971,9 @@ HasMany.prototype.destroyById = function(fkId, options, cb) { return cb.promise; }; -var throughKeys = function(definition) { - var modelThrough = definition.modelThrough; - var pk2 = definition.modelTo.definition.idName(); +const throughKeys = function(definition) { + const modelThrough = definition.modelThrough; + const pk2 = definition.modelTo.definition.idName(); let fk1, fk2; if (typeof definition.polymorphic === 'object') { // polymorphic @@ -1010,11 +1010,11 @@ HasManyThrough.prototype.findById = function(fkId, options, cb) { cb = options; options = {}; } - var self = this; - var modelTo = this.definition.modelTo; - var pk = this.definition.keyFrom; - var modelInstance = this.modelInstance; - var modelThrough = this.definition.modelThrough; + const self = this; + const modelTo = this.definition.modelTo; + const pk = this.definition.keyFrom; + const modelInstance = this.modelInstance; + const modelThrough = this.definition.modelThrough; cb = cb || utils.createPromiseCallback(); @@ -1055,11 +1055,11 @@ HasManyThrough.prototype.destroyById = function(fkId, options, cb) { cb = options; options = {}; } - var self = this; - var modelTo = this.definition.modelTo; - var pk = this.definition.keyFrom; - var modelInstance = this.modelInstance; - var modelThrough = this.definition.modelThrough; + const self = this; + const modelTo = this.definition.modelTo; + const pk = this.definition.keyFrom; + const modelInstance = this.modelInstance; + const modelThrough = this.definition.modelThrough; cb = cb || utils.createPromiseCallback(); @@ -1090,10 +1090,10 @@ HasManyThrough.prototype.create = function create(data, options, cb) { cb = options; options = {}; } - var self = this; - var definition = this.definition; - var modelTo = definition.modelTo; - var modelThrough = definition.modelThrough; + const self = this; + const definition = this.definition; + const modelTo = definition.modelTo; + const modelThrough = definition.modelThrough; if (typeof data === 'function' && !cb) { cb = data; @@ -1101,7 +1101,7 @@ HasManyThrough.prototype.create = function create(data, options, cb) { } cb = cb || utils.createPromiseCallback(); - var modelInstance = this.modelInstance; + const modelInstance = this.modelInstance; // First create the target model modelTo.create(data, options, function(err, to) { @@ -1109,13 +1109,13 @@ HasManyThrough.prototype.create = function create(data, options, cb) { return cb(err, to); } // The primary key for the target model - var pk2 = definition.modelTo.definition.idName(); - var keys = throughKeys(definition); - var fk1 = keys[0]; - var fk2 = keys[1]; + const pk2 = definition.modelTo.definition.idName(); + const keys = throughKeys(definition); + const fk1 = keys[0]; + const fk2 = keys[1]; function createRelation(to, next) { - var d = {}, q = {}, filter = {where: q}; + const d = {}, q = {}, filter = {where: q}; d[fk1] = q[fk1] = modelInstance[definition.keyFrom]; d[fk2] = q[fk2] = to[pk2]; definition.applyProperties(modelInstance, d); @@ -1156,31 +1156,31 @@ HasManyThrough.prototype.add = function(acInst, data, options, cb) { cb = options; options = {}; } - var self = this; - var definition = this.definition; - var modelThrough = definition.modelThrough; - var pk1 = definition.keyFrom; + const self = this; + const definition = this.definition; + const modelThrough = definition.modelThrough; + const pk1 = definition.keyFrom; if (typeof data === 'function') { cb = data; data = {}; } - var query = {}; + const query = {}; data = data || {}; cb = cb || utils.createPromiseCallback(); // The primary key for the target model - var pk2 = definition.modelTo.definition.idName(); + const pk2 = definition.modelTo.definition.idName(); - var keys = throughKeys(definition); - var fk1 = keys[0]; - var fk2 = keys[1]; + const keys = throughKeys(definition); + const fk1 = keys[0]; + const fk2 = keys[1]; query[fk1] = this.modelInstance[pk1]; query[fk2] = (acInst instanceof definition.modelTo) ? acInst[pk2] : acInst; - var filter = {where: query}; + const filter = {where: query}; definition.applyScope(this.modelInstance, filter); @@ -1210,23 +1210,23 @@ HasManyThrough.prototype.exists = function(acInst, options, cb) { cb = options; options = {}; } - var definition = this.definition; - var modelThrough = definition.modelThrough; - var pk1 = definition.keyFrom; + const definition = this.definition; + const modelThrough = definition.modelThrough; + const pk1 = definition.keyFrom; - var query = {}; + const query = {}; // The primary key for the target model - var pk2 = definition.modelTo.definition.idName(); + const pk2 = definition.modelTo.definition.idName(); - var keys = throughKeys(definition); - var fk1 = keys[0]; - var fk2 = keys[1]; + const keys = throughKeys(definition); + const fk1 = keys[0]; + const fk2 = keys[1]; query[fk1] = this.modelInstance[pk1]; query[fk2] = (acInst instanceof definition.modelTo) ? acInst[pk2] : acInst; - var filter = {where: query}; + const filter = {where: query}; definition.applyScope(this.modelInstance, filter); @@ -1247,24 +1247,24 @@ HasManyThrough.prototype.remove = function(acInst, options, cb) { cb = options; options = {}; } - var self = this; - var definition = this.definition; - var modelThrough = definition.modelThrough; - var pk1 = definition.keyFrom; + const self = this; + const definition = this.definition; + const modelThrough = definition.modelThrough; + const pk1 = definition.keyFrom; - var query = {}; + const query = {}; // The primary key for the target model - var pk2 = definition.modelTo.definition.idName(); + const pk2 = definition.modelTo.definition.idName(); - var keys = throughKeys(definition); - var fk1 = keys[0]; - var fk2 = keys[1]; + const keys = throughKeys(definition); + const fk1 = keys[0]; + const fk2 = keys[1]; query[fk1] = this.modelInstance[pk1]; query[fk2] = (acInst instanceof definition.modelTo) ? acInst[pk2] : acInst; - var filter = {where: query}; + const filter = {where: query}; definition.applyScope(this.modelInstance, filter); @@ -1304,10 +1304,10 @@ HasManyThrough.prototype.remove = function(acInst, options, cb) { * */ RelationDefinition.belongsTo = function(modelFrom, modelToRef, params) { - var modelTo, discriminator, polymorphic; + let modelTo, discriminator, polymorphic; params = params || {}; - var pkName, relationName, fk; + let pkName, relationName, fk; if (params.polymorphic) { relationName = params.as || (typeof modelToRef === 'string' ? modelToRef : null); polymorphic = normalizePolymorphic(params.polymorphic, relationName); @@ -1336,7 +1336,7 @@ RelationDefinition.belongsTo = function(modelFrom, modelToRef, params) { modelFrom.dataSource.defineForeignKey(modelFrom.modelName, fk, modelTo.modelName, pkName); } - var definition = modelFrom.relations[relationName] = new RelationDefinition({ + const definition = modelFrom.relations[relationName] = new RelationDefinition({ name: relationName, type: RelationTypes.belongsTo, modelFrom: modelFrom, @@ -1356,8 +1356,8 @@ RelationDefinition.belongsTo = function(modelFrom, modelToRef, params) { enumerable: true, configurable: true, get: function() { - var relation = new BelongsTo(definition, this); - var relationMethod = relation.related.bind(relation); + const relation = new BelongsTo(definition, this); + const relationMethod = relation.related.bind(relation); relationMethod.get = relation.get.bind(relation); relationMethod.getAsync = function() { deprecated(g.f('BelongsTo method "getAsync()" is deprecated, use "get()" instead.')); @@ -1378,8 +1378,8 @@ RelationDefinition.belongsTo = function(modelFrom, modelToRef, params) { // FIXME: [rfeng] Wrap the property into a function for remoting // so that it can be accessed as /api/// // For example, /api/orders/1/customer - var fn = function() { - var f = this[relationName]; + const fn = function() { + const f = this[relationName]; f.apply(this, arguments); }; modelFrom.prototype['__get__' + relationName] = fn; @@ -1392,11 +1392,11 @@ BelongsTo.prototype.create = function(targetModelData, options, cb) { cb = options; options = {}; } - var self = this; - var modelTo = this.definition.modelTo; - var fk = this.definition.keyFrom; - var pk = this.definition.keyTo; - var modelInstance = this.modelInstance; + const self = this; + const modelTo = this.definition.modelTo; + const fk = this.definition.keyFrom; + const pk = this.definition.keyTo; + const modelInstance = this.modelInstance; if (typeof targetModelData === 'function' && !cb) { cb = targetModelData; @@ -1427,7 +1427,7 @@ BelongsTo.prototype.create = function(targetModelData, options, cb) { }; BelongsTo.prototype.build = function(targetModelData) { - var modelTo = this.definition.modelTo; + const modelTo = this.definition.modelTo; this.definition.applyProperties(this.modelInstance, targetModelData || {}); return new modelTo(targetModelData); }; @@ -1438,13 +1438,13 @@ BelongsTo.prototype.update = function(targetModelData, options, cb) { options = {}; } cb = cb || utils.createPromiseCallback(); - var definition = this.definition; - var fk = definition.keyTo; + const definition = this.definition; + const fk = definition.keyTo; this.fetch(options, function(err, inst) { if (inst instanceof ModelBaseClass) { // Ensures Foreign Key cannot be changed! - var fkErr = preventFkOverride(inst, targetModelData, fk); + const fkErr = preventFkOverride(inst, targetModelData, fk); if (fkErr) return cb(fkErr); inst.updateAttributes(targetModelData, options, cb); } else { @@ -1460,9 +1460,9 @@ BelongsTo.prototype.destroy = function(options, cb) { options = {}; } - var definition = this.definition; - var modelInstance = this.modelInstance; - var fk = definition.keyFrom; + const definition = this.definition; + const modelInstance = this.modelInstance; + const fk = definition.keyFrom; cb = cb || utils.createPromiseCallback(); @@ -1492,15 +1492,15 @@ BelongsTo.prototype.destroy = function(options, cb) { * @returns {*} */ BelongsTo.prototype.related = function(condOrRefresh, options, cb) { - var self = this; - var modelFrom = this.definition.modelFrom; - var modelTo = this.definition.modelTo; - var pk = this.definition.keyTo; - var fk = this.definition.keyFrom; - var modelInstance = this.modelInstance; - var discriminator; - var scopeQuery = null; - var newValue; + const self = this; + const modelFrom = this.definition.modelFrom; + let modelTo = this.definition.modelTo; + const pk = this.definition.keyTo; + const fk = this.definition.keyFrom; + const modelInstance = this.modelInstance; + let discriminator; + let scopeQuery = null; + let newValue; if ((condOrRefresh instanceof ModelBaseClass) && options === undefined && cb === undefined) { @@ -1525,7 +1525,7 @@ BelongsTo.prototype.related = function(condOrRefresh, options, cb) { discriminator = this.definition.polymorphic.discriminator; } - var cachedValue; + let cachedValue; if (!condOrRefresh) { cachedValue = self.getCache(); } @@ -1541,7 +1541,7 @@ BelongsTo.prototype.related = function(condOrRefresh, options, cb) { self.resetCache(newValue); } else if (typeof cb === 'function') { // acts as async getter if (discriminator) { - var modelToName = modelInstance[discriminator]; + let modelToName = modelInstance[discriminator]; if (typeof modelToName !== 'string') { throw new Error(g.f('{{Polymorphic}} model not found: `%s` not set', discriminator)); } @@ -1553,7 +1553,7 @@ BelongsTo.prototype.related = function(condOrRefresh, options, cb) { } if (cachedValue === undefined || !(cachedValue instanceof ModelBaseClass)) { - var query = {where: {}}; + const query = {where: {}}; query.where[pk] = modelInstance[fk]; if (query.where[pk] === undefined || query.where[pk] === null) { @@ -1639,9 +1639,9 @@ BelongsTo.prototype.get = function(options, cb) { RelationDefinition.hasAndBelongsToMany = function hasAndBelongsToMany(modelFrom, modelToRef, params) { params = params || {}; normalizeRelationAs(params, modelToRef); - var modelTo = lookupModelTo(modelFrom, modelToRef, params, true); + const modelTo = lookupModelTo(modelFrom, modelToRef, params, true); - var models = modelFrom.dataSource.modelBuilder.models; + const models = modelFrom.dataSource.modelBuilder.models; if (!params.through) { if (params.polymorphic) throw new Error(g.f('{{Polymorphic}} relations need a through model')); @@ -1649,14 +1649,14 @@ RelationDefinition.hasAndBelongsToMany = function hasAndBelongsToMany(modelFrom, if (params.throughTable) { params.through = modelFrom.dataSource.define(params.throughTable); } else { - var name1 = modelFrom.modelName + modelTo.modelName; - var name2 = modelTo.modelName + modelFrom.modelName; + const name1 = modelFrom.modelName + modelTo.modelName; + const name2 = modelTo.modelName + modelFrom.modelName; params.through = lookupModel(models, name1) || lookupModel(models, name2) || modelFrom.dataSource.define(name1); } } - var options = {as: params.as, through: params.through}; + const options = {as: params.as, through: params.through}; options.properties = params.properties; options.scope = params.scope; @@ -1664,10 +1664,10 @@ RelationDefinition.hasAndBelongsToMany = function hasAndBelongsToMany(modelFrom, options.options = params.options; if (params.polymorphic) { - var relationName = params.as || i8n.camelize(modelTo.pluralModelName, true); - var polymorphic = normalizePolymorphic(params.polymorphic, relationName); + const relationName = params.as || i8n.camelize(modelTo.pluralModelName, true); + const polymorphic = normalizePolymorphic(params.polymorphic, relationName); options.polymorphic = polymorphic; // pass through - var accessor = params.through.prototype[polymorphic.selector]; + const accessor = params.through.prototype[polymorphic.selector]; if (typeof accessor !== 'function') { // declare once // use the name of the polymorphic selector, not modelTo params.through.belongsTo(polymorphic.selector, {polymorphic: true}); @@ -1699,13 +1699,13 @@ RelationDefinition.hasAndBelongsToMany = function hasAndBelongsToMany(modelFrom, RelationDefinition.hasOne = function(modelFrom, modelToRef, params) { params = params || {}; normalizeRelationAs(params, modelToRef); - var modelTo = lookupModelTo(modelFrom, modelToRef, params); + const modelTo = lookupModelTo(modelFrom, modelToRef, params); - var pk = params.primaryKey || modelFrom.dataSource.idName(modelFrom.modelName) || 'id'; - var relationName = params.as || i8n.camelize(modelTo.modelName, true); + const pk = params.primaryKey || modelFrom.dataSource.idName(modelFrom.modelName) || 'id'; + const relationName = params.as || i8n.camelize(modelTo.modelName, true); - var fk = params.foreignKey || i8n.camelize(modelFrom.modelName + '_id', true); - var discriminator, polymorphic; + let fk = params.foreignKey || i8n.camelize(modelFrom.modelName + '_id', true); + let discriminator, polymorphic; if (params.polymorphic) { polymorphic = normalizePolymorphic(params.polymorphic, relationName); @@ -1716,7 +1716,7 @@ RelationDefinition.hasOne = function(modelFrom, modelToRef, params) { } } - var definition = modelFrom.relations[relationName] = new RelationDefinition({ + const definition = modelFrom.relations[relationName] = new RelationDefinition({ name: relationName, type: RelationTypes.hasOne, modelFrom: modelFrom, @@ -1738,8 +1738,8 @@ RelationDefinition.hasOne = function(modelFrom, modelToRef, params) { enumerable: true, configurable: true, get: function() { - var relation = new HasOne(definition, this); - var relationMethod = relation.related.bind(relation); + const relation = new HasOne(definition, this); + const relationMethod = relation.related.bind(relation); relationMethod.get = relation.get.bind(relation); relationMethod.getAsync = function() { deprecated(g.f('HasOne method "getAsync()" is deprecated, use "get()" instead.')); @@ -1759,22 +1759,22 @@ RelationDefinition.hasOne = function(modelFrom, modelToRef, params) { // so that it can be accessed as /api/// // For example, /api/orders/1/customer modelFrom.prototype['__get__' + relationName] = function() { - var f = this[relationName]; + const f = this[relationName]; f.apply(this, arguments); }; modelFrom.prototype['__create__' + relationName] = function() { - var f = this[relationName].create; + const f = this[relationName].create; f.apply(this, arguments); }; modelFrom.prototype['__update__' + relationName] = function() { - var f = this[relationName].update; + const f = this[relationName].update; f.apply(this, arguments); }; modelFrom.prototype['__destroy__' + relationName] = function() { - var f = this[relationName].destroy; + const f = this[relationName].destroy; f.apply(this, arguments); }; @@ -1794,11 +1794,11 @@ HasOne.prototype.create = function(targetModelData, options, cb) { cb = options; options = {}; } - var self = this; - var modelTo = this.definition.modelTo; - var fk = this.definition.keyTo; - var pk = this.definition.keyFrom; - var modelInstance = this.modelInstance; + const self = this; + const modelTo = this.definition.modelTo; + const fk = this.definition.keyTo; + const pk = this.definition.keyFrom; + const modelInstance = this.modelInstance; if (typeof targetModelData === 'function' && !cb) { cb = targetModelData; @@ -1808,7 +1808,7 @@ HasOne.prototype.create = function(targetModelData, options, cb) { cb = cb || utils.createPromiseCallback(); targetModelData[fk] = modelInstance[pk]; - var query = {where: {}}; + const query = {where: {}}; query.where[fk] = targetModelData[fk]; this.definition.applyScope(modelInstance, query); @@ -1840,12 +1840,12 @@ HasOne.prototype.update = function(targetModelData, options, cb) { options = {}; } cb = cb || utils.createPromiseCallback(); - var definition = this.definition; - var fk = this.definition.keyTo; + const definition = this.definition; + const fk = this.definition.keyTo; this.fetch(function(err, targetModel) { if (targetModel instanceof ModelBaseClass) { // Ensures Foreign Key cannot be changed! - var fkErr = preventFkOverride(targetModel, targetModelData, fk); + const fkErr = preventFkOverride(targetModel, targetModelData, fk); if (fkErr) return cb(fkErr); targetModel.updateAttributes(targetModelData, options, cb); } else { @@ -1862,7 +1862,7 @@ HasOne.prototype.destroy = function(options, cb) { options = {}; } cb = cb || utils.createPromiseCallback(); - var definition = this.definition; + const definition = this.definition; this.fetch(function(err, targetModel) { if (targetModel instanceof ModelBaseClass) { targetModel.destroy(options, cb); @@ -1886,11 +1886,11 @@ HasMany.prototype.create = function(targetModelData, options, cb) { cb = options; options = {}; } - var self = this; - var modelTo = this.definition.modelTo; - var fk = this.definition.keyTo; - var pk = this.definition.keyFrom; - var modelInstance = this.modelInstance; + const self = this; + const modelTo = this.definition.modelTo; + const fk = this.definition.keyTo; + const pk = this.definition.keyFrom; + const modelInstance = this.modelInstance; if (typeof targetModelData === 'function' && !cb) { cb = targetModelData; @@ -1899,12 +1899,12 @@ HasMany.prototype.create = function(targetModelData, options, cb) { targetModelData = targetModelData || {}; cb = cb || utils.createPromiseCallback(); - var fkAndProps = function(item) { + const fkAndProps = function(item) { item[fk] = modelInstance[pk]; self.definition.applyProperties(modelInstance, item); }; - var apply = function(data, fn) { + const apply = function(data, fn) { if (Array.isArray(data)) { data.forEach(fn); } else { @@ -1931,9 +1931,9 @@ HasMany.prototype.create = function(targetModelData, options, cb) { * @returns {Object} The newly built target model instance */ HasMany.prototype.build = HasOne.prototype.build = function(targetModelData) { - var modelTo = this.definition.modelTo; - var pk = this.definition.keyFrom; - var fk = this.definition.keyTo; + const modelTo = this.definition.modelTo; + const pk = this.definition.keyFrom; + const fk = this.definition.keyTo; targetModelData = targetModelData || {}; targetModelData[fk] = this.modelInstance[pk]; @@ -1955,13 +1955,13 @@ HasMany.prototype.build = HasOne.prototype.build = function(targetModelData) { * @returns {Object} */ HasOne.prototype.related = function(condOrRefresh, options, cb) { - var self = this; - var modelTo = this.definition.modelTo; - var fk = this.definition.keyTo; - var pk = this.definition.keyFrom; - var definition = this.definition; - var modelInstance = this.modelInstance; - var newValue; + const self = this; + const modelTo = this.definition.modelTo; + const fk = this.definition.keyTo; + const pk = this.definition.keyFrom; + const definition = this.definition; + const modelInstance = this.modelInstance; + let newValue; if ((condOrRefresh instanceof ModelBaseClass) && options === undefined && cb === undefined) { @@ -1979,7 +1979,7 @@ HasOne.prototype.related = function(condOrRefresh, options, cb) { options = {}; } - var cachedValue; + let cachedValue; if (!condOrRefresh) { cachedValue = self.getCache(); } @@ -1988,7 +1988,7 @@ HasOne.prototype.related = function(condOrRefresh, options, cb) { self.resetCache(newValue); } else if (typeof cb === 'function') { // acts as async getter if (cachedValue === undefined) { - var query = {where: {}}; + const query = {where: {}}; query.where[fk] = modelInstance[pk]; definition.applyScope(modelInstance, query); modelTo.findOne(query, options, function(err, inst) { @@ -2044,12 +2044,12 @@ HasOne.prototype.get = function(options, cb) { RelationDefinition.embedsOne = function(modelFrom, modelToRef, params) { params = params || {}; normalizeRelationAs(params, modelToRef); - var modelTo = lookupModelTo(modelFrom, modelToRef, params); + const modelTo = lookupModelTo(modelFrom, modelToRef, params); - var thisClassName = modelFrom.modelName; - var relationName = params.as || (i8n.camelize(modelTo.modelName, true) + 'Item'); - var propertyName = params.property || i8n.camelize(modelTo.modelName, true); - var idName = modelTo.dataSource.idName(modelTo.modelName) || 'id'; + const thisClassName = modelFrom.modelName; + const relationName = params.as || (i8n.camelize(modelTo.modelName, true) + 'Item'); + let propertyName = params.property || i8n.camelize(modelTo.modelName, true); + const idName = modelTo.dataSource.idName(modelTo.modelName) || 'id'; if (relationName === propertyName) { propertyName = '_' + propertyName; @@ -2057,7 +2057,7 @@ RelationDefinition.embedsOne = function(modelFrom, modelToRef, params) { 'forcing property %s for relation %s', propertyName, relationName); } - var definition = modelFrom.relations[relationName] = new RelationDefinition({ + const definition = modelFrom.relations[relationName] = new RelationDefinition({ name: relationName, type: RelationTypes.embedsOne, modelFrom: modelFrom, @@ -2072,7 +2072,7 @@ RelationDefinition.embedsOne = function(modelFrom, modelToRef, params) { methods: params.methods, }); - var opts = Object.assign( + const opts = Object.assign( params.options && params.options.property ? params.options.property : {}, {type: modelTo} ); @@ -2092,11 +2092,11 @@ RelationDefinition.embedsOne = function(modelFrom, modelToRef, params) { // validate the embedded instance if (definition.options.validate !== false) { modelFrom.validate(relationName, function(err) { - var inst = this[propertyName]; + const inst = this[propertyName]; if (inst instanceof modelTo) { if (!inst.isValid()) { - var first = Object.keys(inst.errors)[0]; - var msg = 'is invalid: `' + first + '` ' + inst.errors[first]; + const first = Object.keys(inst.errors)[0]; + const msg = 'is invalid: `' + first + '` ' + inst.errors[first]; this.errors.add(relationName, msg, 'invalid'); err(false); } @@ -2109,8 +2109,8 @@ RelationDefinition.embedsOne = function(modelFrom, modelToRef, params) { enumerable: true, configurable: true, get: function() { - var relation = new EmbedsOne(definition, this); - var relationMethod = relation.related.bind(relation); + const relation = new EmbedsOne(definition, this); + const relationMethod = relation.related.bind(relation); relationMethod.create = relation.create.bind(relation); relationMethod.build = relation.build.bind(relation); relationMethod.update = relation.update.bind(relation); @@ -2126,22 +2126,22 @@ RelationDefinition.embedsOne = function(modelFrom, modelToRef, params) { // so that it can be accessed as /api/// // For example, /api/orders/1/customer modelFrom.prototype['__get__' + relationName] = function() { - var f = this[relationName]; + const f = this[relationName]; f.apply(this, arguments); }; modelFrom.prototype['__create__' + relationName] = function() { - var f = this[relationName].create; + const f = this[relationName].create; f.apply(this, arguments); }; modelFrom.prototype['__update__' + relationName] = function() { - var f = this[relationName].update; + const f = this[relationName].update; f.apply(this, arguments); }; modelFrom.prototype['__destroy__' + relationName] = function() { - var f = this[relationName].destroy; + const f = this[relationName].destroy; f.apply(this, arguments); }; @@ -2149,10 +2149,10 @@ RelationDefinition.embedsOne = function(modelFrom, modelToRef, params) { }; EmbedsOne.prototype.related = function(condOrRefresh, options, cb) { - var modelTo = this.definition.modelTo; - var modelInstance = this.modelInstance; - var propertyName = this.definition.keyFrom; - var newValue; + const modelTo = this.definition.modelTo; + const modelInstance = this.modelInstance; + const propertyName = this.definition.keyFrom; + let newValue; if ((condOrRefresh instanceof ModelBaseClass) && options === undefined && cb === undefined) { @@ -2178,7 +2178,7 @@ EmbedsOne.prototype.related = function(condOrRefresh, options, cb) { return; } - var embeddedInstance = this.embeddedValue(); + const embeddedInstance = this.embeddedValue(); if (embeddedInstance) { embeddedInstance.__persisted = true; @@ -2195,18 +2195,18 @@ EmbedsOne.prototype.related = function(condOrRefresh, options, cb) { EmbedsOne.prototype.prepareEmbeddedInstance = function(inst) { if (inst && inst.triggerParent !== 'function') { - var self = this; - var propertyName = this.definition.keyFrom; - var modelInstance = this.modelInstance; + const self = this; + const propertyName = this.definition.keyFrom; + const modelInstance = this.modelInstance; if (this.definition.options.persistent) { - var pk = this.definition.keyTo; + const pk = this.definition.keyTo; inst.__persisted = !!inst[pk]; } else { inst.__persisted = true; } inst.triggerParent = function(actionName, callback) { if (actionName === 'save') { - var embeddedValue = self.embeddedValue(); + const embeddedValue = self.embeddedValue(); modelInstance.updateAttribute(propertyName, embeddedValue, function(err, modelInst) { callback(err, err ? null : modelInst); @@ -2221,10 +2221,10 @@ EmbedsOne.prototype.prepareEmbeddedInstance = function(inst) { process.nextTick(callback); } }; - var originalTrigger = inst.trigger; + const originalTrigger = inst.trigger; inst.trigger = function(actionName, work, data, callback) { if (typeof work === 'function') { - var originalWork = work; + const originalWork = work; work = function(next) { originalWork.call(this, function(done) { inst.triggerParent(actionName, function(err, inst) { @@ -2240,7 +2240,7 @@ EmbedsOne.prototype.prepareEmbeddedInstance = function(inst) { EmbedsOne.prototype.embeddedValue = function(modelInstance) { modelInstance = modelInstance || this.modelInstance; - var embeddedValue = modelInstance[this.definition.keyFrom]; + const embeddedValue = modelInstance[this.definition.keyFrom]; this.prepareEmbeddedInstance(embeddedValue); return embeddedValue; }; @@ -2251,9 +2251,9 @@ EmbedsOne.prototype.create = function(targetModelData, options, cb) { cb = options; options = {}; } - var modelTo = this.definition.modelTo; - var propertyName = this.definition.keyFrom; - var modelInstance = this.modelInstance; + const modelTo = this.definition.modelTo; + const propertyName = this.definition.keyFrom; + const modelInstance = this.modelInstance; if (typeof targetModelData === 'function' && !cb) { cb = targetModelData; @@ -2263,9 +2263,9 @@ EmbedsOne.prototype.create = function(targetModelData, options, cb) { targetModelData = targetModelData || {}; cb = cb || utils.createPromiseCallback(); - var inst = this.callScopeMethod('build', targetModelData); + const inst = this.callScopeMethod('build', targetModelData); - var updateEmbedded = function(callback) { + const updateEmbedded = function(callback) { if (modelInstance.isNewRecord()) { modelInstance.setAttribute(propertyName, inst); modelInstance.save(options, function(err) { @@ -2285,7 +2285,7 @@ EmbedsOne.prototype.create = function(targetModelData, options, cb) { updateEmbedded(cb); }); } else { - var context = { + const context = { Model: modelTo, instance: inst, options: options || {}, @@ -2318,29 +2318,29 @@ EmbedsOne.prototype.create = function(targetModelData, options, cb) { }; EmbedsOne.prototype.build = function(targetModelData) { - var modelTo = this.definition.modelTo; - var modelInstance = this.modelInstance; - var propertyName = this.definition.keyFrom; - var forceId = this.definition.options.forceId; - var persistent = this.definition.options.persistent; - var connector = modelTo.dataSource.connector; + const modelTo = this.definition.modelTo; + const modelInstance = this.modelInstance; + const propertyName = this.definition.keyFrom; + const forceId = this.definition.options.forceId; + const persistent = this.definition.options.persistent; + const connector = modelTo.dataSource.connector; targetModelData = targetModelData || {}; this.definition.applyProperties(modelInstance, targetModelData); - var pk = this.definition.keyTo; - var pkProp = modelTo.definition.properties[pk]; + const pk = this.definition.keyTo; + const pkProp = modelTo.definition.properties[pk]; - var assignId = (forceId || targetModelData[pk] === undefined); + let assignId = (forceId || targetModelData[pk] === undefined); assignId = assignId && !persistent && (pkProp && pkProp.generated); if (assignId && typeof connector.generateId === 'function') { - var id = connector.generateId(modelTo.modelName, targetModelData, pk); + const id = connector.generateId(modelTo.modelName, targetModelData, pk); targetModelData[pk] = id; } - var embeddedInstance = new modelTo(targetModelData); + const embeddedInstance = new modelTo(targetModelData); modelInstance[propertyName] = embeddedInstance; this.prepareEmbeddedInstance(embeddedInstance); @@ -2355,18 +2355,18 @@ EmbedsOne.prototype.update = function(targetModelData, options, cb) { options = {}; } - var modelTo = this.definition.modelTo; - var modelInstance = this.modelInstance; - var propertyName = this.definition.keyFrom; + const modelTo = this.definition.modelTo; + const modelInstance = this.modelInstance; + const propertyName = this.definition.keyFrom; - var isInst = targetModelData instanceof ModelBaseClass; - var data = isInst ? targetModelData.toObject() : targetModelData; + const isInst = targetModelData instanceof ModelBaseClass; + const data = isInst ? targetModelData.toObject() : targetModelData; - var embeddedInstance = this.embeddedValue(); + const embeddedInstance = this.embeddedValue(); if (embeddedInstance instanceof modelTo) { cb = cb || utils.createPromiseCallback(); - var hookState = {}; - var context = { + const hookState = {}; + let context = { Model: modelTo, currentInstance: embeddedInstance, data: data, @@ -2412,10 +2412,10 @@ EmbedsOne.prototype.destroy = function(options, cb) { options = {}; } cb = cb || utils.createPromiseCallback(); - var modelTo = this.definition.modelTo; - var modelInstance = this.modelInstance; - var propertyName = this.definition.keyFrom; - var embeddedInstance = modelInstance[propertyName]; + const modelTo = this.definition.modelTo; + const modelInstance = this.modelInstance; + const propertyName = this.definition.keyFrom; + const embeddedInstance = modelInstance[propertyName]; if (!embeddedInstance) { cb(); @@ -2424,7 +2424,7 @@ EmbedsOne.prototype.destroy = function(options, cb) { modelInstance.unsetAttribute(propertyName, true); - var context = { + const context = { Model: modelTo, instance: embeddedInstance, options: options || {}, @@ -2444,12 +2444,12 @@ EmbedsOne.prototype.destroy = function(options, cb) { RelationDefinition.embedsMany = function embedsMany(modelFrom, modelToRef, params) { params = params || {}; normalizeRelationAs(params, modelToRef); - var modelTo = lookupModelTo(modelFrom, modelToRef, params, true); + const modelTo = lookupModelTo(modelFrom, modelToRef, params, true); - var thisClassName = modelFrom.modelName; - var relationName = params.as || (i8n.camelize(modelTo.modelName, true) + 'List'); - var propertyName = params.property || i8n.camelize(modelTo.pluralModelName, true); - var idName = modelTo.dataSource.idName(modelTo.modelName) || 'id'; + const thisClassName = modelFrom.modelName; + const relationName = params.as || (i8n.camelize(modelTo.modelName, true) + 'List'); + let propertyName = params.property || i8n.camelize(modelTo.pluralModelName, true); + const idName = modelTo.dataSource.idName(modelTo.modelName) || 'id'; if (relationName === propertyName) { propertyName = '_' + propertyName; @@ -2457,7 +2457,7 @@ RelationDefinition.embedsMany = function embedsMany(modelFrom, modelToRef, param 'forcing property %s for relation %s', propertyName, relationName); } - var definition = modelFrom.relations[relationName] = new RelationDefinition({ + const definition = modelFrom.relations[relationName] = new RelationDefinition({ name: relationName, type: RelationTypes.embedsMany, modelFrom: modelFrom, @@ -2471,7 +2471,7 @@ RelationDefinition.embedsMany = function embedsMany(modelFrom, modelToRef, param embed: true, }); - var opts = Object.assign( + const opts = Object.assign( params.options && params.options.property ? params.options.property : {}, params.options && params.options.omitDefaultEmbeddedItem ? {type: [modelTo]} : { @@ -2484,13 +2484,13 @@ RelationDefinition.embedsMany = function embedsMany(modelFrom, modelToRef, param if (typeof modelTo.dataSource.connector.generateId !== 'function') { modelFrom.validate(propertyName, function(err) { - var self = this; - var embeddedList = this[propertyName] || []; - var hasErrors = false; + const self = this; + const embeddedList = this[propertyName] || []; + let hasErrors = false; embeddedList.forEach(function(item, idx) { if (item instanceof modelTo && item[idName] == undefined) { hasErrors = true; - var msg = 'contains invalid item at index `' + idx + '`:'; + let msg = 'contains invalid item at index `' + idx + '`:'; msg += ' `' + idName + '` is blank'; self.errors.add(propertyName, msg, 'invalid'); } @@ -2501,8 +2501,8 @@ RelationDefinition.embedsMany = function embedsMany(modelFrom, modelToRef, param if (!params.polymorphic) { modelFrom.validate(propertyName, function(err) { - var embeddedList = this[propertyName] || []; - var ids = embeddedList.map(function(m) { return m[idName] && m[idName].toString(); }); // mongodb + const embeddedList = this[propertyName] || []; + const ids = embeddedList.map(function(m) { return m[idName] && m[idName].toString(); }); // mongodb if (idsHaveDuplicates(ids)) { this.errors.add(propertyName, 'contains duplicate `' + idName + '`', 'uniqueness'); err(false); @@ -2513,15 +2513,15 @@ RelationDefinition.embedsMany = function embedsMany(modelFrom, modelToRef, param // validate all embedded items if (definition.options.validate !== false) { modelFrom.validate(propertyName, function(err) { - var self = this; - var embeddedList = this[propertyName] || []; - var hasErrors = false; + const self = this; + const embeddedList = this[propertyName] || []; + let hasErrors = false; embeddedList.forEach(function(item, idx) { if (item instanceof modelTo) { if (!item.isValid()) { hasErrors = true; - var id = item[idName]; - var first = Object.keys(item.errors)[0]; + const id = item[idName]; + const first = Object.keys(item.errors)[0]; let msg = id ? 'contains invalid item: `' + id + '`' : 'contains invalid item at index `' + idx + '`'; @@ -2537,7 +2537,7 @@ RelationDefinition.embedsMany = function embedsMany(modelFrom, modelToRef, param }); } - var scopeMethods = { + const scopeMethods = { findById: scopeMethod(definition, 'findById'), destroy: scopeMethod(definition, 'destroyById'), updateById: scopeMethod(definition, 'updateById'), @@ -2551,19 +2551,19 @@ RelationDefinition.embedsMany = function embedsMany(modelFrom, modelToRef, param value: scopeMethod(definition, 'embeddedValue'), }; - var findByIdFunc = scopeMethods.findById; + const findByIdFunc = scopeMethods.findById; modelFrom.prototype['__findById__' + relationName] = findByIdFunc; - var destroyByIdFunc = scopeMethods.destroy; + const destroyByIdFunc = scopeMethods.destroy; modelFrom.prototype['__destroyById__' + relationName] = destroyByIdFunc; - var updateByIdFunc = scopeMethods.updateById; + const updateByIdFunc = scopeMethods.updateById; modelFrom.prototype['__updateById__' + relationName] = updateByIdFunc; - var addFunc = scopeMethods.add; + const addFunc = scopeMethods.add; modelFrom.prototype['__link__' + relationName] = addFunc; - var removeFunc = scopeMethods.remove; + const removeFunc = scopeMethods.remove; modelFrom.prototype['__unlink__' + relationName] = removeFunc; scopeMethods.create = scopeMethod(definition, 'create'); @@ -2575,18 +2575,18 @@ RelationDefinition.embedsMany = function embedsMany(modelFrom, modelToRef, param scopeMethods.destroyAll = scopeMethod(definition, 'destroyAll'); } - var customMethods = extendScopeMethods(definition, scopeMethods, params.scopeMethods); + const customMethods = extendScopeMethods(definition, scopeMethods, params.scopeMethods); - for (var i = 0; i < customMethods.length; i++) { - var methodName = customMethods[i]; - var method = scopeMethods[methodName]; + for (let i = 0; i < customMethods.length; i++) { + const methodName = customMethods[i]; + const method = scopeMethods[methodName]; if (typeof method === 'function' && method.shared === true) { modelFrom.prototype['__' + methodName + '__' + relationName] = method; } } // Mix the property and scoped methods into the prototype class - var scopeDefinition = defineScope(modelFrom.prototype, modelTo, relationName, function() { + const scopeDefinition = defineScope(modelFrom.prototype, modelTo, relationName, function() { return {}; }, scopeMethods, definition.options); @@ -2597,20 +2597,20 @@ RelationDefinition.embedsMany = function embedsMany(modelFrom, modelToRef, param EmbedsMany.prototype.prepareEmbeddedInstance = function(inst) { if (inst && inst.triggerParent !== 'function') { - var self = this; - var propertyName = this.definition.keyFrom; - var modelInstance = this.modelInstance; + const self = this; + const propertyName = this.definition.keyFrom; + const modelInstance = this.modelInstance; if (this.definition.options.persistent) { - var pk = this.definition.keyTo; + const pk = this.definition.keyTo; inst.__persisted = !!inst[pk]; } else { inst.__persisted = true; } inst.triggerParent = function(actionName, callback) { if (actionName === 'save' || actionName === 'destroy') { - var embeddedList = self.embeddedList(); + const embeddedList = self.embeddedList(); if (actionName === 'destroy') { - var index = embeddedList.indexOf(inst); + const index = embeddedList.indexOf(inst); if (index > -1) embeddedList.splice(index, 1); } modelInstance.updateAttribute(propertyName, @@ -2621,10 +2621,10 @@ EmbedsMany.prototype.prepareEmbeddedInstance = function(inst) { process.nextTick(callback); } }; - var originalTrigger = inst.trigger; + const originalTrigger = inst.trigger; inst.trigger = function(actionName, work, data, callback) { if (typeof work === 'function') { - var originalWork = work; + const originalWork = work; work = function(next) { originalWork.call(this, function(done) { inst.triggerParent(actionName, function(err, inst) { @@ -2641,16 +2641,16 @@ EmbedsMany.prototype.prepareEmbeddedInstance = function(inst) { EmbedsMany.prototype.embeddedList = EmbedsMany.prototype.embeddedValue = function(modelInstance) { modelInstance = modelInstance || this.modelInstance; - var embeddedList = modelInstance[this.definition.keyFrom] || []; + const 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; - var modelInstance = this.modelInstance; + const modelTo = this.definition.modelTo; + const modelInstance = this.modelInstance; - var actualCond = {}; + let actualCond = {}; if (typeof condOrRefresh === 'function' && options === undefined && cb === undefined) { @@ -2667,17 +2667,17 @@ EmbedsMany.prototype.related = function(receiver, scopeParams, condOrRefresh, op actualCond = condOrRefresh; } - var embeddedList = this.embeddedList(receiver); + let embeddedList = this.embeddedList(receiver); this.definition.applyScope(receiver, actualCond); - var params = mergeQuery(actualCond, scopeParams); + const params = mergeQuery(actualCond, scopeParams); if (params.where && Object.keys(params.where).length > 0) { // TODO [fabien] Support order/sorting embeddedList = embeddedList ? embeddedList.filter(applyFilter(params)) : embeddedList; } - var returnRelated = function(list) { + const returnRelated = function(list) { if (params.include) { modelTo.include(list, params.include, options, cb); } else { @@ -2694,21 +2694,21 @@ EmbedsMany.prototype.findById = function(fkId, options, cb) { cb = options; options = {}; } - var pk = this.definition.keyTo; - var modelTo = this.definition.modelTo; - var modelInstance = this.modelInstance; + const pk = this.definition.keyTo; + const modelTo = this.definition.modelTo; + const modelInstance = this.modelInstance; - var embeddedList = this.embeddedList(); + const embeddedList = this.embeddedList(); - var find = function(id) { - for (var i = 0; i < embeddedList.length; i++) { - var item = embeddedList[i]; + const find = function(id) { + for (let i = 0; i < embeddedList.length; i++) { + const item = embeddedList[i]; if (idEquals(item[pk], id)) return item; } return null; }; - var item = find(fkId.toString()); // in case of explicit id + let item = find(fkId.toString()); // in case of explicit id item = (item instanceof modelTo) ? item : null; if (typeof cb === 'function') { @@ -2726,8 +2726,8 @@ EmbedsMany.prototype.exists = function(fkId, options, cb) { cb = options; options = {}; } - var modelTo = this.definition.modelTo; - var inst = this.findById(fkId, options, function(err, inst) { + const modelTo = this.definition.modelTo; + const inst = this.findById(fkId, options, function(err, inst) { if (cb) cb(err, inst instanceof modelTo); }); return inst instanceof modelTo; // sync @@ -2746,17 +2746,17 @@ EmbedsMany.prototype.updateById = function(fkId, data, options, cb) { } options = options || {}; - var modelTo = this.definition.modelTo; - var propertyName = this.definition.keyFrom; - var modelInstance = this.modelInstance; + const modelTo = this.definition.modelTo; + const propertyName = this.definition.keyFrom; + const modelInstance = this.modelInstance; - var embeddedList = this.embeddedList(); + const embeddedList = this.embeddedList(); - var inst = this.findById(fkId); + const inst = this.findById(fkId); if (inst instanceof modelTo) { - var hookState = {}; - var context = { + const hookState = {}; + let context = { Model: modelTo, currentInstance: inst, data: data, @@ -2811,16 +2811,16 @@ EmbedsMany.prototype.destroyById = function(fkId, options, cb) { cb = options; options = {}; } - var modelTo = this.definition.modelTo; - var propertyName = this.definition.keyFrom; - var modelInstance = this.modelInstance; + const modelTo = this.definition.modelTo; + const propertyName = this.definition.keyFrom; + const modelInstance = this.modelInstance; - var embeddedList = this.embeddedList(); + const embeddedList = this.embeddedList(); - var inst = (fkId instanceof modelTo) ? fkId : this.findById(fkId); + const inst = (fkId instanceof modelTo) ? fkId : this.findById(fkId); if (inst instanceof modelTo) { - var context = { + const context = { Model: modelTo, instance: inst, options: options || {}, @@ -2829,7 +2829,7 @@ EmbedsMany.prototype.destroyById = function(fkId, options, cb) { modelTo.notifyObserversOf('before delete', context, function(err) { if (err) return cb(err); - var index = embeddedList.indexOf(inst); + const index = embeddedList.indexOf(inst); if (index > -1) embeddedList.splice(index, 1); if (typeof cb !== 'function') return; modelInstance.updateAttribute(propertyName, @@ -2857,14 +2857,14 @@ EmbedsMany.prototype.destroyAll = function(where, options, cb) { cb = where; where = {}; } - var propertyName = this.definition.keyFrom; - var modelInstance = this.modelInstance; + const propertyName = this.definition.keyFrom; + const modelInstance = this.modelInstance; - var embeddedList = this.embeddedList(); + let embeddedList = this.embeddedList(); if (where && Object.keys(where).length > 0) { - var filter = applyFilter({where: where}); - var reject = function(v) { return !filter(v); }; + const filter = applyFilter({where: where}); + const reject = function(v) { return !filter(v); }; embeddedList = embeddedList ? embeddedList.filter(reject) : embeddedList; } else { embeddedList = []; @@ -2885,12 +2885,12 @@ EmbedsMany.prototype.set = EmbedsMany.prototype.updateById; EmbedsMany.prototype.unset = EmbedsMany.prototype.destroyById; EmbedsMany.prototype.at = function(index, cb) { - var modelTo = this.definition.modelTo; - var modelInstance = this.modelInstance; + const modelTo = this.definition.modelTo; + const modelInstance = this.modelInstance; - var embeddedList = this.embeddedList(); + const embeddedList = this.embeddedList(); - var item = embeddedList[parseInt(index)]; + let item = embeddedList[parseInt(index)]; item = (item instanceof modelTo) ? item : null; if (typeof cb === 'function') { @@ -2903,10 +2903,10 @@ EmbedsMany.prototype.at = function(index, cb) { }; EmbedsMany.prototype.create = function(targetModelData, options, cb) { - var pk = this.definition.keyTo; - var modelTo = this.definition.modelTo; - var propertyName = this.definition.keyFrom; - var modelInstance = this.modelInstance; + const pk = this.definition.keyTo; + const modelTo = this.definition.modelTo; + const propertyName = this.definition.keyFrom; + const modelInstance = this.modelInstance; if (typeof options === 'function' && cb === undefined) { // customer.emails.create(cb) @@ -2921,10 +2921,10 @@ EmbedsMany.prototype.create = function(targetModelData, options, cb) { targetModelData = targetModelData || {}; cb = cb || utils.createPromiseCallback(); - var inst = this.callScopeMethod('build', targetModelData); - var embeddedList = this.embeddedList(); + const inst = this.callScopeMethod('build', targetModelData); + const embeddedList = this.embeddedList(); - var updateEmbedded = function(callback) { + const updateEmbedded = function(callback) { if (modelInstance.isNewRecord()) { modelInstance.setAttribute(propertyName, embeddedList); modelInstance.save(options, function(err) { @@ -2950,7 +2950,7 @@ EmbedsMany.prototype.create = function(targetModelData, options, cb) { cb(err); }); } else { - var context = { + const context = { Model: modelTo, instance: inst, options: options || {}, @@ -2971,26 +2971,26 @@ EmbedsMany.prototype.create = function(targetModelData, options, cb) { }; EmbedsMany.prototype.build = function(targetModelData) { - var modelTo = this.definition.modelTo; - var modelInstance = this.modelInstance; - var forceId = this.definition.options.forceId; - var persistent = this.definition.options.persistent; - var propertyName = this.definition.keyFrom; - var connector = modelTo.dataSource.connector; + const modelTo = this.definition.modelTo; + const modelInstance = this.modelInstance; + const forceId = this.definition.options.forceId; + const persistent = this.definition.options.persistent; + const propertyName = this.definition.keyFrom; + const connector = modelTo.dataSource.connector; - var pk = this.definition.keyTo; - var pkProp = modelTo.definition.properties[pk]; - var pkType = pkProp && pkProp.type; + const pk = this.definition.keyTo; + const pkProp = modelTo.definition.properties[pk]; + const pkType = pkProp && pkProp.type; - var embeddedList = this.embeddedList(); + const embeddedList = this.embeddedList(); targetModelData = targetModelData || {}; - var assignId = (forceId || targetModelData[pk] === undefined); + let assignId = (forceId || targetModelData[pk] === undefined); assignId = assignId && !persistent; if (assignId && pkType === Number) { - var ids = embeddedList.map(function(m) { + const ids = embeddedList.map(function(m) { return (typeof m[pk] === 'number' ? m[pk] : 0); }); if (ids.length > 0) { @@ -2999,13 +2999,13 @@ EmbedsMany.prototype.build = function(targetModelData) { targetModelData[pk] = 1; } } else if (assignId && typeof connector.generateId === 'function') { - var id = connector.generateId(modelTo.modelName, targetModelData, pk); + const id = connector.generateId(modelTo.modelName, targetModelData, pk); targetModelData[pk] = id; } this.definition.applyProperties(modelInstance, targetModelData); - var inst = new modelTo(targetModelData); + const inst = new modelTo(targetModelData); if (this.definition.options.prepend) { embeddedList.unshift(inst); @@ -3037,32 +3037,32 @@ EmbedsMany.prototype.add = function(acInst, data, options, cb) { } cb = cb || utils.createPromiseCallback(); - var self = this; - var definition = this.definition; - var modelTo = this.definition.modelTo; - var modelInstance = this.modelInstance; + const self = this; + const definition = this.definition; + const modelTo = this.definition.modelTo; + const modelInstance = this.modelInstance; - var defOpts = definition.options; - var belongsTo = defOpts.belongsTo && modelTo.relations[defOpts.belongsTo]; + const defOpts = definition.options; + const belongsTo = defOpts.belongsTo && modelTo.relations[defOpts.belongsTo]; if (!belongsTo) { throw new Error('Invalid reference: ' + defOpts.belongsTo || '(none)'); } - var fk2 = belongsTo.keyTo; - var pk2 = belongsTo.modelTo.definition.idName() || 'id'; + const fk2 = belongsTo.keyTo; + const pk2 = belongsTo.modelTo.definition.idName() || 'id'; - var query = {}; + const query = {}; query[fk2] = (acInst instanceof belongsTo.modelTo) ? acInst[pk2] : acInst; - var filter = {where: query}; + const filter = {where: query}; belongsTo.applyScope(modelInstance, filter); belongsTo.modelTo.findOne(filter, options, function(err, ref) { if (ref instanceof belongsTo.modelTo) { - var inst = self.build(data || {}); + const inst = self.build(data || {}); inst[defOpts.belongsTo](ref); modelInstance.save(function(err) { cb(err, err ? null : inst); @@ -3084,26 +3084,26 @@ EmbedsMany.prototype.remove = function(acInst, options, cb) { cb = options; options = {}; } - var self = this; - var definition = this.definition; - var modelTo = this.definition.modelTo; - var modelInstance = this.modelInstance; + const self = this; + const definition = this.definition; + const modelTo = this.definition.modelTo; + const modelInstance = this.modelInstance; - var defOpts = definition.options; - var belongsTo = defOpts.belongsTo && modelTo.relations[defOpts.belongsTo]; + const defOpts = definition.options; + const belongsTo = defOpts.belongsTo && modelTo.relations[defOpts.belongsTo]; if (!belongsTo) { throw new Error('Invalid reference: ' + defOpts.belongsTo || '(none)'); } - var fk2 = belongsTo.keyTo; - var pk2 = belongsTo.modelTo.definition.idName() || 'id'; + const fk2 = belongsTo.keyTo; + const pk2 = belongsTo.modelTo.definition.idName() || 'id'; - var query = {}; + const query = {}; query[fk2] = (acInst instanceof belongsTo.modelTo) ? acInst[pk2] : acInst; - var filter = {where: query}; + const filter = {where: query}; belongsTo.applyScope(modelInstance, filter); @@ -3126,15 +3126,15 @@ EmbedsMany.prototype.remove = function(acInst, options, cb) { RelationDefinition.referencesMany = function referencesMany(modelFrom, modelToRef, params) { params = params || {}; normalizeRelationAs(params, modelToRef); - var modelTo = lookupModelTo(modelFrom, modelToRef, params, true); + const modelTo = lookupModelTo(modelFrom, modelToRef, params, true); - var thisClassName = modelFrom.modelName; - var relationName = params.as || i8n.camelize(modelTo.pluralModelName, true); - var fk = params.foreignKey || i8n.camelize(modelTo.modelName + '_ids', true); - var idName = modelTo.dataSource.idName(modelTo.modelName) || 'id'; - var idType = modelTo.definition.properties[idName].type; + const thisClassName = modelFrom.modelName; + const relationName = params.as || i8n.camelize(modelTo.pluralModelName, true); + const fk = params.foreignKey || i8n.camelize(modelTo.modelName + '_ids', true); + const idName = modelTo.dataSource.idName(modelTo.modelName) || 'id'; + const idType = modelTo.definition.properties[idName].type; - var definition = modelFrom.relations[relationName] = new RelationDefinition({ + const definition = modelFrom.relations[relationName] = new RelationDefinition({ name: relationName, type: RelationTypes.referencesMany, modelFrom: modelFrom, @@ -3152,15 +3152,15 @@ RelationDefinition.referencesMany = function referencesMany(modelFrom, modelToRe }); modelFrom.validate(relationName, function(err) { - var ids = this[fk] || []; + const ids = this[fk] || []; if (idsHaveDuplicates(ids)) { - var msg = 'contains duplicate `' + modelTo.modelName + '` instance'; + const msg = 'contains duplicate `' + modelTo.modelName + '` instance'; this.errors.add(relationName, msg, 'uniqueness'); err(false); } }, {code: 'uniqueness'}); - var scopeMethods = { + const scopeMethods = { findById: scopeMethod(definition, 'findById'), destroy: scopeMethod(definition, 'destroyById'), updateById: scopeMethod(definition, 'updateById'), @@ -3170,19 +3170,19 @@ RelationDefinition.referencesMany = function referencesMany(modelFrom, modelToRe at: scopeMethod(definition, 'at'), }; - var findByIdFunc = scopeMethods.findById; + const findByIdFunc = scopeMethods.findById; modelFrom.prototype['__findById__' + relationName] = findByIdFunc; - var destroyByIdFunc = scopeMethods.destroy; + const destroyByIdFunc = scopeMethods.destroy; modelFrom.prototype['__destroyById__' + relationName] = destroyByIdFunc; - var updateByIdFunc = scopeMethods.updateById; + const updateByIdFunc = scopeMethods.updateById; modelFrom.prototype['__updateById__' + relationName] = updateByIdFunc; - var addFunc = scopeMethods.add; + const addFunc = scopeMethods.add; modelFrom.prototype['__link__' + relationName] = addFunc; - var removeFunc = scopeMethods.remove; + const removeFunc = scopeMethods.remove; modelFrom.prototype['__unlink__' + relationName] = removeFunc; scopeMethods.create = scopeMethod(definition, 'create'); @@ -3190,18 +3190,18 @@ RelationDefinition.referencesMany = function referencesMany(modelFrom, modelToRe scopeMethods.related = scopeMethod(definition, 'related'); - var customMethods = extendScopeMethods(definition, scopeMethods, params.scopeMethods); + const customMethods = extendScopeMethods(definition, scopeMethods, params.scopeMethods); - for (var i = 0; i < customMethods.length; i++) { - var methodName = customMethods[i]; - var method = scopeMethods[methodName]; + for (let i = 0; i < customMethods.length; i++) { + const methodName = customMethods[i]; + const method = scopeMethods[methodName]; if (typeof method === 'function' && method.shared === true) { modelFrom.prototype['__' + methodName + '__' + relationName] = method; } } // Mix the property and scoped methods into the prototype class - var scopeDefinition = defineScope(modelFrom.prototype, modelTo, relationName, function() { + const scopeDefinition = defineScope(modelFrom.prototype, modelTo, relationName, function() { return {}; }, scopeMethods, definition.options); @@ -3211,14 +3211,14 @@ RelationDefinition.referencesMany = function referencesMany(modelFrom, modelToRe }; ReferencesMany.prototype.related = function(receiver, scopeParams, condOrRefresh, options, cb) { - var fk = this.definition.keyFrom; - var modelTo = this.definition.modelTo; - var relationName = this.definition.name; - var modelInstance = this.modelInstance; - var self = receiver; + const fk = this.definition.keyFrom; + const modelTo = this.definition.modelTo; + const relationName = this.definition.name; + const modelInstance = this.modelInstance; + const self = receiver; - var actualCond = {}; - var actualRefresh = false; + let actualCond = {}; + let actualRefresh = false; if (typeof condOrRefresh === 'function' && options === undefined && cb === undefined) { @@ -3238,11 +3238,11 @@ ReferencesMany.prototype.related = function(receiver, scopeParams, condOrRefresh } actualCond = condOrRefresh || {}; - var ids = self[fk] || []; + const ids = self[fk] || []; this.definition.applyScope(modelInstance, actualCond); - var params = mergeQuery(actualCond, scopeParams); + const params = mergeQuery(actualCond, scopeParams); return modelTo.findByIds(ids, params, options, cb); }; @@ -3252,21 +3252,21 @@ ReferencesMany.prototype.findById = function(fkId, options, cb) { cb = options; options = {}; } - var modelTo = this.definition.modelTo; - var modelFrom = this.definition.modelFrom; - var relationName = this.definition.name; - var modelInstance = this.modelInstance; + const modelTo = this.definition.modelTo; + const modelFrom = this.definition.modelFrom; + const relationName = this.definition.name; + const modelInstance = this.modelInstance; - var pk = this.definition.keyTo; - var fk = this.definition.keyFrom; + const pk = this.definition.keyTo; + const fk = this.definition.keyFrom; if (typeof fkId === 'object') { fkId = fkId.toString(); // mongodb } - var ids = modelInstance[fk] || []; + const ids = modelInstance[fk] || []; - var filter = {}; + const filter = {}; this.definition.applyScope(modelInstance, filter); @@ -3277,7 +3277,7 @@ ReferencesMany.prototype.findById = function(fkId, options, cb) { return cb(err); } - var inst = instances[0]; + const inst = instances[0]; if (!inst) { err = new Error(g.f('No instance with {{id}} %s found for %s', fkId, modelTo.modelName)); err.statusCode = 404; @@ -3304,8 +3304,8 @@ ReferencesMany.prototype.exists = function(fkId, options, cb) { cb = options; options = {}; } - var fk = this.definition.keyFrom; - var ids = this.modelInstance[fk] || []; + const fk = this.definition.keyFrom; + const ids = this.modelInstance[fk] || []; cb = cb || utils.createPromiseCallback(); process.nextTick(function() { cb(null, utils.findIndexOf(ids, fkId, idEquals) > -1); }); @@ -3338,7 +3338,7 @@ ReferencesMany.prototype.destroyById = function(fkId, options, cb) { cb = options; options = {}; } - var self = this; + const self = this; cb = cb || utils.createPromiseCallback(); this.findById(fkId, function(err, inst) { if (err) return cb(err); @@ -3355,8 +3355,8 @@ ReferencesMany.prototype.at = function(index, options, cb) { cb = options; options = {}; } - var fk = this.definition.keyFrom; - var ids = this.modelInstance[fk] || []; + const fk = this.definition.keyFrom; + const ids = this.modelInstance[fk] || []; cb = cb || utils.createPromiseCallback(); this.findById(ids[index], options, cb); return cb.promise; @@ -3368,13 +3368,13 @@ ReferencesMany.prototype.create = function(targetModelData, options, cb) { cb = options; options = {}; } - var definition = this.definition; - var modelTo = this.definition.modelTo; - var relationName = this.definition.name; - var modelInstance = this.modelInstance; + const definition = this.definition; + const modelTo = this.definition.modelTo; + const relationName = this.definition.name; + const modelInstance = this.modelInstance; - var pk = this.definition.keyTo; - var fk = this.definition.keyFrom; + const pk = this.definition.keyTo; + const fk = this.definition.keyFrom; if (typeof targetModelData === 'function' && !cb) { cb = targetModelData; @@ -3383,14 +3383,14 @@ ReferencesMany.prototype.create = function(targetModelData, options, cb) { targetModelData = targetModelData || {}; cb = cb || utils.createPromiseCallback(); - var ids = modelInstance[fk] || []; + const ids = modelInstance[fk] || []; - var inst = this.callScopeMethod('build', targetModelData); + const inst = this.callScopeMethod('build', targetModelData); inst.save(options, function(err, inst) { if (err) return cb(err, inst); - var id = inst[pk]; + let id = inst[pk]; if (typeof id === 'object') { id = id.toString(); // mongodb @@ -3411,7 +3411,7 @@ ReferencesMany.prototype.create = function(targetModelData, options, cb) { }; ReferencesMany.prototype.build = function(targetModelData) { - var modelTo = this.definition.modelTo; + const modelTo = this.definition.modelTo; targetModelData = targetModelData || {}; this.definition.applyProperties(this.modelInstance, targetModelData); @@ -3429,22 +3429,22 @@ ReferencesMany.prototype.add = function(acInst, options, cb) { cb = options; options = {}; } - var self = this; - var definition = this.definition; - var modelTo = this.definition.modelTo; - var modelInstance = this.modelInstance; + const self = this; + const definition = this.definition; + const modelTo = this.definition.modelTo; + const modelInstance = this.modelInstance; - var pk = this.definition.keyTo; - var fk = this.definition.keyFrom; + const pk = this.definition.keyTo; + const fk = this.definition.keyFrom; - var insert = function(inst, done) { - var id = inst[pk]; + const insert = function(inst, done) { + let id = inst[pk]; if (typeof id === 'object') { id = id.toString(); // mongodb } - var ids = modelInstance[fk] || []; + const ids = modelInstance[fk] || []; if (definition.options.prepend) { ids.unshift(id); @@ -3462,7 +3462,7 @@ ReferencesMany.prototype.add = function(acInst, options, cb) { if (acInst instanceof modelTo) { insert(acInst, cb); } else { - var filter = {where: {}}; + const filter = {where: {}}; filter.where[pk] = acInst; definition.applyScope(modelInstance, filter); @@ -3485,19 +3485,19 @@ ReferencesMany.prototype.remove = function(acInst, options, cb) { cb = options; options = {}; } - var definition = this.definition; - var modelInstance = this.modelInstance; + const definition = this.definition; + const modelInstance = this.modelInstance; - var pk = this.definition.keyTo; - var fk = this.definition.keyFrom; + const pk = this.definition.keyTo; + const fk = this.definition.keyFrom; - var ids = modelInstance[fk] || []; + const ids = modelInstance[fk] || []; - var id = (acInst instanceof definition.modelTo) ? acInst[pk] : acInst; + const id = (acInst instanceof definition.modelTo) ? acInst[pk] : acInst; cb = cb || utils.createPromiseCallback(); - var index = utils.findIndexOf(ids, id, idEquals); + const index = utils.findIndexOf(ids, id, idEquals); if (index > -1) { ids.splice(index, 1); modelInstance.updateAttribute(fk, ids, options, function(err, inst) { diff --git a/lib/relations.js b/lib/relations.js index e736117c..3fa5af40 100644 --- a/lib/relations.js +++ b/lib/relations.js @@ -7,8 +7,8 @@ /*! * Dependencies */ -var relation = require('./relation-definition'); -var RelationDefinition = relation.RelationDefinition; +const relation = require('./relation-definition'); +const RelationDefinition = relation.RelationDefinition; module.exports = RelationMixin; diff --git a/lib/scope.js b/lib/scope.js index b455330d..17ffd93b 100644 --- a/lib/scope.js +++ b/lib/scope.js @@ -4,17 +4,17 @@ // License text available at https://opensource.org/licenses/MIT 'use strict'; -var _ = require('lodash'); -var i8n = require('inflection'); -var g = require('strong-globalize')(); -var utils = require('./utils'); -var defineCachedRelations = utils.defineCachedRelations; -var setScopeValuesFromWhere = utils.setScopeValuesFromWhere; -var mergeQuery = utils.mergeQuery; -var DefaultModelBaseClass = require('./model.js'); -var collectTargetIds = utils.collectTargetIds; -var idName = utils.idName; -var deprecated = require('depd')('loopback-datasource-juggler'); +const _ = require('lodash'); +const i8n = require('inflection'); +const g = require('strong-globalize')(); +const utils = require('./utils'); +const defineCachedRelations = utils.defineCachedRelations; +const setScopeValuesFromWhere = utils.setScopeValuesFromWhere; +const mergeQuery = utils.mergeQuery; +const DefaultModelBaseClass = require('./model.js'); +const collectTargetIds = utils.collectTargetIds; +const idName = utils.idName; +const deprecated = require('depd')('loopback-datasource-juggler'); /** * Module exports @@ -32,14 +32,14 @@ function ScopeDefinition(definition) { } ScopeDefinition.prototype.targetModel = function(receiver) { - var modelTo; + let modelTo; if (typeof this.options.modelTo === 'function') { modelTo = this.options.modelTo.call(this, receiver) || this.modelTo; } else { modelTo = this.modelTo; } if (!(modelTo.prototype instanceof DefaultModelBaseClass)) { - var msg = 'Invalid target model for scope `'; + let msg = 'Invalid target model for scope `'; msg += (this.isStatic ? this.modelFrom : this.modelFrom.constructor).modelName; msg += this.isStatic ? '.' : '.prototype.'; msg += this.name + '`.'; @@ -58,12 +58,12 @@ ScopeDefinition.prototype.targetModel = function(receiver) { * @returns {*} */ ScopeDefinition.prototype.related = function(receiver, scopeParams, condOrRefresh, options, cb) { - var name = this.name; - var self = receiver; + const name = this.name; + const self = receiver; - var actualCond = {}; - var actualRefresh = false; - var saveOnCache = receiver instanceof DefaultModelBaseClass; + let actualCond = {}; + let actualRefresh = false; + let saveOnCache = receiver instanceof DefaultModelBaseClass; if (typeof condOrRefresh === 'function' && options === undefined && cb === undefined) { // related(receiver, scopeParams, cb) @@ -90,13 +90,13 @@ ScopeDefinition.prototype.related = function(receiver, scopeParams, condOrRefres actualRefresh; if (refreshIsNeeded) { // It either doesn't hit the cache or refresh is required - var params = mergeQuery(actualCond, scopeParams, {nestedInclude: true}); - var targetModel = this.targetModel(receiver); + const params = mergeQuery(actualCond, scopeParams, {nestedInclude: true}); + const targetModel = this.targetModel(receiver); // If there is a through model // run another query to apply filter on relatedModel(targetModel) // see github.com/strongloop/loopback-datasource-juggler/issues/166 - var scopeOnRelatedModel = params.collect && + const scopeOnRelatedModel = params.collect && params.include.scope !== null && typeof params.include.scope === 'object'; if (scopeOnRelatedModel) { @@ -113,18 +113,18 @@ ScopeDefinition.prototype.related = function(receiver, scopeParams, condOrRefres } if (scopeOnRelatedModel === true) { - var relatedModel = targetModel.relations[filter.relation].modelTo; - var IdKey = idName(relatedModel); + const relatedModel = targetModel.relations[filter.relation].modelTo; + const IdKey = idName(relatedModel); // return {inq: [1,2,3]}} - var smartMerge = function(idCollection, qWhere) { + const smartMerge = function(idCollection, qWhere) { if (!qWhere[IdKey]) return idCollection; - var merged = {}; + let merged = {}; - var idsA = idCollection.inq; - var idsB = qWhere[IdKey].inq ? qWhere[IdKey].inq : [qWhere[IdKey]]; + const idsA = idCollection.inq; + const idsB = qWhere[IdKey].inq ? qWhere[IdKey].inq : [qWhere[IdKey]]; - var intersect = _.intersectionWith(idsA, idsB, _.isEqual); + const intersect = _.intersectionWith(idsA, idsB, _.isEqual); if (intersect.length === 1) merged = intersect[0]; if (intersect.length > 1) merged = {inq: intersect}; @@ -133,7 +133,7 @@ ScopeDefinition.prototype.related = function(receiver, scopeParams, condOrRefres if (queryRelated.where !== undefined) { // Merge queryRelated filter and targetId filter - var IdKeyCondition = {}; + const IdKeyCondition = {}; IdKeyCondition[IdKey] = smartMerge(collectTargetIds(data, IdKey), queryRelated.where); @@ -141,7 +141,7 @@ ScopeDefinition.prototype.related = function(receiver, scopeParams, condOrRefres // return empty result if (_.isObject(IdKeyCondition[IdKey]) && _.isEmpty(IdKeyCondition[IdKey])) return cb(null, []); - var mergedWhere = { + const mergedWhere = { and: [ IdKeyCondition, _.omit(queryRelated.where, IdKey), @@ -201,8 +201,8 @@ function defineScope(cls, targetClass, name, params, methods, options) { options = options || {}; // Check if the cls is the class itself or its prototype - var isStatic = (typeof cls === 'function') || options.isStatic || false; - var definition = new ScopeDefinition({ + const isStatic = (typeof cls === 'function') || options.isStatic || false; + const definition = new ScopeDefinition({ isStatic: isStatic, modelFrom: cls, modelTo: targetClass, @@ -236,8 +236,8 @@ function defineScope(cls, targetClass, name, params, methods, options) { * */ get: function() { - var targetModel = definition.targetModel(this); - var self = this; + const targetModel = definition.targetModel(this); + const self = this; var f = function(condOrRefresh, options, cb) { if (arguments.length === 0) { @@ -312,7 +312,7 @@ function defineScope(cls, targetClass, name, params, methods, options) { f.findOne = findOne; f.count = count; - for (var i in definition.methods) { + for (const i in definition.methods) { f[i] = definition.methods[i].bind(self); } @@ -336,52 +336,52 @@ function defineScope(cls, targetClass, name, params, methods, options) { }); // Wrap the property into a function for remoting - var fn = function() { + const fn = function() { // primaryObject.scopeName, such as user.accounts - var f = this[name]; + const f = this[name]; // set receiver to be the scope property whose value is a function f.apply(this[name], arguments); }; cls['__get__' + name] = fn; - var fnCreate = function() { - var f = this[name].create; + const fnCreate = function() { + const f = this[name].create; f.apply(this[name], arguments); }; cls['__create__' + name] = fnCreate; - var fnDelete = function() { - var f = this[name].destroyAll; + const fnDelete = function() { + const f = this[name].destroyAll; f.apply(this[name], arguments); }; cls['__delete__' + name] = fnDelete; - var fnUpdate = function() { - var f = this[name].updateAll; + const fnUpdate = function() { + const f = this[name].updateAll; f.apply(this[name], arguments); }; cls['__update__' + name] = fnUpdate; - var fnFindById = function(cb) { - var f = this[name].findById; + const fnFindById = function(cb) { + const f = this[name].findById; f.apply(this[name], arguments); }; cls['__findById__' + name] = fnFindById; - var fnFindOne = function(cb) { - var f = this[name].findOne; + const fnFindOne = function(cb) { + const f = this[name].findOne; f.apply(this[name], arguments); }; cls['__findOne__' + name] = fnFindOne; - var fnCount = function(cb) { - var f = this[name].count; + const fnCount = function(cb) { + const f = this[name].count; f.apply(this[name], arguments); }; @@ -391,8 +391,8 @@ function defineScope(cls, targetClass, name, params, methods, options) { function build(data) { data = data || {}; // Find all fixed property values for the scope - var targetModel = definition.targetModel(this._receiver); - var where = (this._scope && this._scope.where) || {}; + const targetModel = definition.targetModel(this._receiver); + const where = (this._scope && this._scope.where) || {}; setScopeValuesFromWhere(data, where, targetModel); return new targetModel(data); } @@ -430,9 +430,9 @@ 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 || {}}); + const targetModel = definition.targetModel(this._receiver); + const scoped = (this._scope && this._scope.where) || {}; + const filter = mergeQuery({where: scoped}, {where: where || {}}); return targetModel.destroyAll(filter.where, options, cb); } @@ -450,9 +450,9 @@ function defineScope(cls, targetClass, name, params, methods, options) { options = {}; } options = options || {}; - var targetModel = definition.targetModel(this._receiver); - var scoped = (this._scope && this._scope.where) || {}; - var filter = mergeQuery({where: scoped}, {where: where || {}}); + const targetModel = definition.targetModel(this._receiver); + const scoped = (this._scope && this._scope.where) || {}; + const filter = mergeQuery({where: scoped}, {where: where || {}}); return targetModel.updateAll(filter.where, data, options, cb); } @@ -478,9 +478,9 @@ 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: {}}; + const targetModel = definition.targetModel(this._receiver); + const idName = targetModel.definition.idName(); + let query = {where: {}}; query.where[idName] = id; query = mergeQuery(query, filter); return this.findOne(query, options, cb); @@ -498,8 +498,8 @@ function defineScope(cls, targetClass, name, params, methods, options) { options = {}; } options = options || {}; - var targetModel = definition.targetModel(this._receiver); - var scoped = (this._scope && this._scope.where) || {}; + const targetModel = definition.targetModel(this._receiver); + const scoped = (this._scope && this._scope.where) || {}; filter = mergeQuery({where: scoped}, filter || {}); return targetModel.findOne(filter, options, cb); } @@ -516,9 +516,9 @@ 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 || {}}); + const targetModel = definition.targetModel(this._receiver); + const scoped = (this._scope && this._scope.where) || {}; + const filter = mergeQuery({where: scoped}, {where: where || {}}); return targetModel.count(filter.where, options, cb); } diff --git a/lib/transaction.js b/lib/transaction.js index 986a2e1c..e4336351 100644 --- a/lib/transaction.js +++ b/lib/transaction.js @@ -4,14 +4,14 @@ // License text available at https://opensource.org/licenses/MIT 'use strict'; -var g = require('strong-globalize')(); -var debug = require('debug')('loopback:connector:transaction'); -var uuid = require('uuid'); -var utils = require('./utils'); -var jutil = require('./jutil'); -var ObserverMixin = require('./observer'); +const g = require('strong-globalize')(); +const debug = require('debug')('loopback:connector:transaction'); +const uuid = require('uuid'); +const utils = require('./utils'); +const jutil = require('./jutil'); +const ObserverMixin = require('./observer'); -var Transaction = require('loopback-connector').Transaction; +const Transaction = require('loopback-connector').Transaction; module.exports = TransactionMixin; @@ -73,7 +73,7 @@ function TransactionMixin() { TransactionMixin.beginTransaction = function(options, cb) { cb = cb || utils.createPromiseCallback(); if (Transaction) { - var connector = this.getConnector(); + const connector = this.getConnector(); Transaction.begin(connector, options, function(err, transaction) { if (err) return cb(err); // NOTE(lehni) As part of the process of moving the handling of @@ -87,7 +87,7 @@ TransactionMixin.beginTransaction = function(options, cb) { } if (options.timeout && !transaction.timeout) { transaction.timeout = setTimeout(function() { - var context = { + const context = { transaction: transaction, operation: 'timeout', }; @@ -105,7 +105,7 @@ TransactionMixin.beginTransaction = function(options, cb) { }); } else { process.nextTick(function() { - var err = new Error(g.f('{{Transaction}} is not supported')); + const err = new Error(g.f('{{Transaction}} is not supported')); cb(err); }); } @@ -136,7 +136,7 @@ if (Transaction) { Transaction.prototype.commit = function(cb) { cb = cb || utils.createPromiseCallback(); if (this.ensureActive(cb)) { - var context = { + const context = { transaction: this, operation: 'commit', }; @@ -175,7 +175,7 @@ if (Transaction) { Transaction.prototype.rollback = function(cb) { cb = cb || utils.createPromiseCallback(); if (this.ensureActive(cb)) { - var context = { + const context = { transaction: this, operation: 'rollback', }; diff --git a/lib/types.js b/lib/types.js index 2121969f..419e4d37 100644 --- a/lib/types.js +++ b/lib/types.js @@ -4,7 +4,7 @@ // License text available at https://opensource.org/licenses/MIT 'use strict'; -var Types = {}; +const Types = {}; /** * Schema types */ @@ -40,10 +40,10 @@ Types.Any.prototype.toObject = Types.Any.prototype.toJSON = function() { }; module.exports = function(modelTypes) { - var DateString = require('./date-string'); - var GeoPoint = require('./geo').GeoPoint; + const DateString = require('./date-string'); + const GeoPoint = require('./geo').GeoPoint; - for (var t in Types) { + for (const t in Types) { modelTypes[t] = Types[t]; } @@ -51,7 +51,7 @@ module.exports = function(modelTypes) { modelTypes.registerType = function(type, names) { names = names || []; names = names.concat([type.name]); - for (var n = 0; n < names.length; n++) { + for (let n = 0; n < names.length; n++) { this.schemaTypes[names[n].toLowerCase()] = type; } }; diff --git a/lib/utils.js b/lib/utils.js index a64bb5d1..a2a08f9e 100644 --- a/lib/utils.js +++ b/lib/utils.js @@ -28,10 +28,10 @@ exports.idName = idName; exports.rankArrayElements = rankArrayElements; exports.idsHaveDuplicates = idsHaveDuplicates; -var g = require('strong-globalize')(); -var traverse = require('traverse'); -var assert = require('assert'); -var debug = require('debug')('loopback:juggler:utils'); +const g = require('strong-globalize')(); +const traverse = require('traverse'); +const assert = require('assert'); +const debug = require('debug')('loopback:juggler:utils'); function safeRequire(module) { try { @@ -52,17 +52,17 @@ function safeRequire(module) { * @param {Object} The where clause */ function setScopeValuesFromWhere(data, where, targetModel) { - for (var i in where) { + for (const i in where) { if (i === 'and') { // Find fixed property values from each subclauses - for (var w = 0, n = where[i].length; w < n; w++) { + for (let w = 0, n = where[i].length; w < n; w++) { setScopeValuesFromWhere(data, where[i][w], targetModel); } continue; } - var prop = targetModel.definition.properties[i]; + const prop = targetModel.definition.properties[i]; if (prop) { - var val = where[i]; + const val = where[i]; if (typeof val !== 'object' || val instanceof prop.type || prop.type.name === 'ObjectID' || // MongoDB key prop.type.name === 'uuidFromString') { // C* @@ -82,26 +82,26 @@ function setScopeValuesFromWhere(data, where, targetModel) { * @returns {Object} */ function mergeIncludes(destination, source) { - var destArray = convertToArray(destination); - var sourceArray = convertToArray(source); + const destArray = convertToArray(destination); + const sourceArray = convertToArray(source); if (destArray.length === 0) { return sourceArray; } if (sourceArray.length === 0) { return destArray; } - var relationNames = []; - var resultArray = []; - for (var j in sourceArray) { - var sourceEntry = sourceArray[j]; - var sourceEntryRelationName = (typeof (sourceEntry.rel || sourceEntry.relation) === 'string') ? + const relationNames = []; + const resultArray = []; + for (const j in sourceArray) { + const sourceEntry = sourceArray[j]; + const sourceEntryRelationName = (typeof (sourceEntry.rel || sourceEntry.relation) === 'string') ? sourceEntry.relation : Object.keys(sourceEntry)[0]; relationNames.push(sourceEntryRelationName); resultArray.push(sourceEntry); } - for (var i in destArray) { - var destEntry = destArray[i]; - var destEntryRelationName = (typeof (destEntry.rel || destEntry.relation) === 'string') ? + for (const i in destArray) { + const destEntry = destArray[i]; + const destEntryRelationName = (typeof (destEntry.rel || destEntry.relation) === 'string') ? destEntry.relation : Object.keys(destEntry)[0]; if (relationNames.indexOf(destEntryRelationName) === -1) { resultArray.push(destEntry); @@ -129,17 +129,17 @@ function convertToArray(include) { return [include]; } // Build an array of key/value pairs - var newInclude = []; - for (var key in include) { + const newInclude = []; + for (const key in include) { const obj = {}; obj[key] = include[key]; newInclude.push(obj); } return newInclude; } else if (Array.isArray(include)) { - var normalized = []; - for (var i in include) { - var includeEntry = include[i]; + const normalized = []; + for (const i in include) { + const includeEntry = include[i]; if (typeof includeEntry === 'string') { const obj = {}; obj[includeEntry] = true; @@ -185,7 +185,7 @@ function mergeQuery(base, update, spec) { // specify nestedInclude=true to force nesting of inclusions on scoped // queries. e.g. In physician.patients.find({include: 'address'}), // inclusion should be on patient model, not on physician model. - var saved = base.include; + const saved = base.include; base.include = {}; base.include[update.include] = saved; } else { @@ -217,7 +217,7 @@ function mergeQuery(base, update, spec) { base.limit = update.limit; } - var skip = spec.skip !== false && spec.offset !== false; + const skip = spec.skip !== false && spec.offset !== false; if (skip && update.skip !== undefined) { base.skip = update.skip; @@ -241,8 +241,8 @@ function fieldsToArray(fields, properties, excludeUnknown) { if (!fields) return; // include all properties by default - var result = properties; - var i, n; + let result = properties; + let i, n; if (typeof fields === 'string') { result = [fields]; @@ -251,13 +251,13 @@ function fieldsToArray(fields, properties, excludeUnknown) { result = fields; } else if ('object' === typeof fields) { // { field1: boolean, field2: boolean ... } - var included = []; - var excluded = []; - var keys = Object.keys(fields); + const included = []; + const excluded = []; + const keys = Object.keys(fields); if (!keys.length) return; for (i = 0, n = keys.length; i < n; i++) { - var k = keys[i]; + const k = keys[i]; if (fields[k]) { included.push(k); } else if ((k in fields) && !fields[k]) { @@ -268,13 +268,13 @@ function fieldsToArray(fields, properties, excludeUnknown) { result = included; } else if (excluded.length > 0) { for (i = 0, n = excluded.length; i < n; i++) { - var index = result.indexOf(excluded[i]); + const index = result.indexOf(excluded[i]); if (index !== -1) result.splice(index, 1); // only when existing field excluded } } } - var fieldArray = []; + let fieldArray = []; if (excludeUnknown) { for (i = 0, n = result.length; i < n; i++) { if (properties.indexOf(result[i]) !== -1) { @@ -290,10 +290,10 @@ function fieldsToArray(fields, properties, excludeUnknown) { function selectFields(fields) { // map function return function(obj) { - var result = {}; - var key; + const result = {}; + let key; - for (var i = 0; i < fields.length; i++) { + for (let i = 0; i < fields.length; i++) { key = fields[i]; result[key] = obj[key]; @@ -307,7 +307,7 @@ function isProhibited(key, prohibitedKeys) { if (typeof key !== 'string') { return false; } - for (var k of prohibitedKeys) { + for (const k of prohibitedKeys) { if (k === key) return true; // x.secret, secret.y, or x.secret.y if (key.split('.').indexOf(k) !== -1) return true; @@ -416,8 +416,8 @@ function parseSettings(urlStr) { if (!urlStr) { return {}; } - var uri = url.parse(urlStr, false); - var settings = {}; + const uri = url.parse(urlStr, false); + const settings = {}; settings.connector = uri.protocol && uri.protocol.split(':')[0]; // Remove the trailing : settings.host = settings.hostname = uri.hostname; settings.port = uri.port && Number(uri.port); // port is a string @@ -426,8 +426,8 @@ function parseSettings(urlStr) { settings.database = uri.pathname && uri.pathname.split('/')[1]; // remove the leading / settings.url = urlStr; if (uri.query) { - var params = qs.parse(uri.query); - for (var p in params) { + const params = qs.parse(uri.query); + for (const p in params) { settings[p] = params[p]; } } @@ -451,8 +451,8 @@ function parseSettings(urlStr) { */ function deepMerge(base, extras) { // deepMerge allows undefined extras to allow deep cloning of arrays - var array = Array.isArray(base) && (Array.isArray(extras) || !extras); - var dst = array && [] || {}; + const array = Array.isArray(base) && (Array.isArray(extras) || !extras); + let dst = array && [] || {}; if (array) { // extras or base is an array @@ -480,7 +480,7 @@ function deepMerge(base, extras) { if (extras != null && typeof extras === 'object') { // extras is an object {} Object.keys(extras).forEach(function(key) { - var extra = extras[key]; + const extra = extras[key]; if (extra == null || typeof extra !== 'object') { // extra item value is null, undefined or not an object dst[key] = extra; @@ -511,8 +511,8 @@ function deepMerge(base, extras) { * @returns {Object} The merged property */ function deepMergeProperty(base, extras) { - let mergedObject = deepMerge({key: base}, {key: extras}); - let mergedProperty = mergedObject.key; + const mergedObject = deepMerge({key: base}, {key: extras}); + const mergedProperty = mergedObject.key; return mergedProperty; } @@ -583,26 +583,26 @@ function sortObjectsByIds(idName, ids, objects, strict) { return (typeof id === 'object') ? String(id) : id; }); - var indexOf = function(x) { - var isObj = (typeof x[idName] === 'object'); // ObjectID - var id = isObj ? String(x[idName]) : x[idName]; + const indexOf = function(x) { + const isObj = (typeof x[idName] === 'object'); // ObjectID + const id = isObj ? String(x[idName]) : x[idName]; return ids.indexOf(id); }; - var heading = []; - var tailing = []; + const heading = []; + const tailing = []; objects.forEach(function(x) { if (typeof x === 'object') { - var idx = indexOf(x); + const idx = indexOf(x); if (strict && idx === -1) return; idx === -1 ? tailing.push(x) : heading.push(x); } }); heading.sort(function(x, y) { - var a = indexOf(x); - var b = indexOf(y); + const a = indexOf(x); + const b = indexOf(y); if (a === -1 || b === -1) return 1; // last if (a === b) return 0; if (a > b) return 1; @@ -613,8 +613,8 @@ function sortObjectsByIds(idName, ids, objects, strict) { } function createPromiseCallback() { - var cb; - var promise = new Promise(function(resolve, reject) { + let cb; + const promise = new Promise(function(resolve, reject) { cb = function(err, data) { if (err) return reject(err); return resolve(data); @@ -636,15 +636,15 @@ function isBsonType(value) { * @returns {Array} an array with unique items */ function uniq(a) { - var uniqArray = []; + const uniqArray = []; if (!a) { return uniqArray; } assert(Array.isArray(a), 'array argument is required'); - var comparableA = a.map( + const comparableA = a.map( item => isBsonType(item) ? item.toString() : item ); - for (var i = 0, n = comparableA.length; i < n; i++) { + for (let i = 0, n = comparableA.length; i < n; i++) { if (comparableA.indexOf(comparableA[i]) === i) { uniqArray.push(a[i]); } @@ -658,8 +658,8 @@ function uniq(a) { * @returns {Object} A RegExp object */ function toRegExp(regex) { - var isString = typeof regex === 'string'; - var isRegExp = regex instanceof RegExp; + const isString = typeof regex === 'string'; + const isRegExp = regex instanceof RegExp; if (!(isString || isRegExp)) return new Error(g.f('Invalid argument, must be a string, {{regex}} literal, or ' + @@ -672,20 +672,20 @@ function toRegExp(regex) { return new RegExp(regex); // only accept i, g, or m as valid regex flags - var flags = regex.split('/').pop().split(''); - var validFlags = ['i', 'g', 'm']; - var invalidFlags = []; + const flags = regex.split('/').pop().split(''); + const validFlags = ['i', 'g', 'm']; + const invalidFlags = []; flags.forEach(function(flag) { if (validFlags.indexOf(flag) === -1) invalidFlags.push(flag); }); - var hasInvalidFlags = invalidFlags.length > 0; + const hasInvalidFlags = invalidFlags.length > 0; if (hasInvalidFlags) return new Error(g.f('Invalid {{regex}} flags: %s', invalidFlags)); // strip regex delimiter forward slashes - var expression = regex.substr(1, regex.lastIndexOf('/') - 1); + const expression = regex.substr(1, regex.lastIndexOf('/') - 1); return new RegExp(expression, flags.join('')); } @@ -723,7 +723,7 @@ function findIndexOf(arr, target, isEqual) { return arr.indexOf(target); } - for (var i = 0; i < arr.length; i++) { + for (let i = 0; i < arr.length; i++) { if (isEqual(arr[i], target)) { return i; } } @@ -737,12 +737,12 @@ function findIndexOf(arr, target, isEqual) { * @returns {Object} The object that queries targetIds */ function collectTargetIds(targetData, idPropertyName) { - var targetIds = []; - for (var i = 0; i < targetData.length; i++) { - var targetId = targetData[i][idPropertyName]; + const targetIds = []; + for (let i = 0; i < targetData.length; i++) { + const targetId = targetData[i][idPropertyName]; targetIds.push(targetId); } - var IdQuery = { + const IdQuery = { inq: uniq(targetIds), }; return IdQuery; @@ -765,12 +765,12 @@ function idName(m) { */ function idsHaveDuplicates(ids) { // use Set if available and all ids are of string or number type - var hasDuplicates = undefined; - var i, j; + let hasDuplicates = undefined; + let i, j; if (typeof Set === 'function') { - var uniqueIds = new Set(); + const uniqueIds = new Set(); for (i = 0; i < ids.length; ++i) { - var idType = typeof ids[i]; + const idType = typeof ids[i]; if (idType === 'string' || idType === 'number') { if (uniqueIds.has(ids[i])) { hasDuplicates = true; diff --git a/lib/validations.js b/lib/validations.js index 33ad6fe3..fb978ca7 100644 --- a/lib/validations.js +++ b/lib/validations.js @@ -5,9 +5,9 @@ 'use strict'; -var g = require('strong-globalize')(); -var util = require('util'); -var extend = util._extend; +const g = require('strong-globalize')(); +const util = require('util'); +const extend = util._extend; /*! * Module exports @@ -307,7 +307,7 @@ function validateAbsence(attr, conf, err, options) { function validateLength(attr, conf, err, options) { if (nullCheck.call(this, attr, conf, err)) return; - var len = this[attr].length; + const len = this[attr].length; if (conf.min && len < conf.min) { err('min'); } @@ -362,7 +362,7 @@ function validateFormat(attr, conf, err, options) { if (nullCheck.call(this, attr, conf, err)) return; if (typeof this[attr] === 'string' || typeof this[attr] === 'number') { - let regex = new RegExp(conf['with']); + const regex = new RegExp(conf['with']); if (!regex.test(this[attr])) { err(); } @@ -397,7 +397,7 @@ function escapeStringRegexp(str) { if (typeof str !== 'string') { throw new TypeError('Expected a string'); } - var matchOperatorsRe = /[|\\{}()[\]^$+*?.]/g; + const matchOperatorsRe = /[|\\{}()[\]^$+*?.]/g; return str.replace(matchOperatorsRe, '\\$&'); } @@ -412,7 +412,7 @@ function validateUniqueness(attr, conf, err, options, done) { if (blank(this[attr])) { return process.nextTick(done); } - var cond = {where: {}}; + const cond = {where: {}}; if (conf && conf.ignoreCase) { cond.where[attr] = new RegExp('^' + escapeStringRegexp(this[attr]) + '$', 'i'); @@ -422,14 +422,14 @@ function validateUniqueness(attr, conf, err, options, done) { if (conf && conf.scopedTo) { conf.scopedTo.forEach(function(k) { - var val = this[k]; + const val = this[k]; if (val !== undefined) cond.where[k] = this[k]; }, this); } - var idName = this.constructor.definition.idName(); - var isNewRecord = this.isNewRecord(); + const idName = this.constructor.definition.idName(); + const isNewRecord = this.isNewRecord(); this.constructor.find(cond, options, function(error, found) { if (error) { err(error); @@ -452,11 +452,11 @@ function validateUniqueness(attr, conf, err, options, done) { function validateDate(attr, conf, err) { if (this[attr] === null || this[attr] === undefined) return; - var date = new Date(this[attr]); + const date = new Date(this[attr]); if (isNaN(date.getTime())) return err(); } -var validators = { +const validators = { presence: validatePresence, absence: validateAbsence, length: validateLength, @@ -471,7 +471,7 @@ var validators = { function getConfigurator(name, opts) { return function() { - var args = Array.prototype.slice.call(arguments); + const args = Array.prototype.slice.call(arguments); args[1] = args[1] || {}; configure(this, name, args, opts); }; @@ -513,10 +513,10 @@ function getConfigurator(name, opts) { */ Validatable.prototype.isValid = function(callback, data, options) { options = options || {}; - var valid = true, inst = this, wait = 0, async = false; - var validations = this.constructor.validations; + let valid = true, inst = this, wait = 0, async = false; + const validations = this.constructor.validations; - var reportDiscardedProperties = this.__strict && + const reportDiscardedProperties = this.__strict && this.__unknownProperties && this.__unknownProperties.length; // exit with success when no errors @@ -539,13 +539,13 @@ Validatable.prototype.isValid = function(callback, data, options) { }); this.trigger('validate', function(validationsDone) { - var inst = this, + let inst = this, asyncFail = false; - var attrs = Object.keys(validations || {}); + const attrs = Object.keys(validations || {}); attrs.forEach(function(attr) { - var attrValidations = validations[attr] || []; + const attrValidations = validations[attr] || []; attrValidations.forEach(function(v) { if (v.options && v.options.async) { async = true; @@ -562,10 +562,10 @@ Validatable.prototype.isValid = function(callback, data, options) { }); if (reportDiscardedProperties) { - for (var ix in inst.__unknownProperties) { - var key = inst.__unknownProperties[ix]; - var code = 'unknown-property'; - var msg = defaultMessages[code]; + for (const ix in inst.__unknownProperties) { + const key = inst.__unknownProperties[ix]; + const code = 'unknown-property'; + const msg = defaultMessages[code]; inst.errors.add(key, msg, code); valid = false; } @@ -611,7 +611,7 @@ function cleanErrors(inst) { } function validationFailed(inst, attr, conf, options, cb) { - var opts = conf.options || {}; + const opts = conf.options || {}; if (typeof options === 'function') { cb = options; @@ -628,13 +628,13 @@ function validationFailed(inst, attr, conf, options, cb) { return false; } - var fail = false; - var validator = validators[conf.validation]; - var validatorArguments = []; + let fail = false; + const validator = validators[conf.validation]; + const validatorArguments = []; validatorArguments.push(attr); validatorArguments.push(conf); validatorArguments.push(function onerror(kind) { - var message, code = conf.code || conf.validation; + let message, code = conf.code || conf.validation; if (conf.message) { message = conf.message; } @@ -669,7 +669,7 @@ function validationFailed(inst, attr, conf, options, cb) { } function skipValidation(inst, conf, kind) { - var doValidate = true; + let doValidate = true; if (typeof conf[kind] === 'function') { doValidate = conf[kind].call(inst); if (kind === 'unless') doValidate = !doValidate; @@ -764,7 +764,7 @@ function configure(cls, validation, args, opts) { }); } args = [].slice.call(args); - var conf; + let conf; if (typeof args[args.length - 1] === 'object') { conf = args.pop(); } else { @@ -776,7 +776,7 @@ function configure(cls, validation, args, opts) { conf.validation = validation; args.forEach(function(attr) { if (typeof attr === 'string') { - var validation = extend({}, conf); + const validation = extend({}, conf); validation.options = opts || {}; cls.validations[attr] = cls.validations[attr] || []; cls.validations[attr].push(validation); @@ -803,7 +803,7 @@ Errors.prototype.add = function(field, message, code) { }; function ErrorCodes(messages) { - var c = this; + const c = this; Object.keys(messages).forEach(function(field) { c[field] = messages[field].codes; }); @@ -866,7 +866,7 @@ function ValidationError(obj) { this.name = 'ValidationError'; - var context = obj && obj.constructor && obj.constructor.modelName; + const context = obj && obj.constructor && obj.constructor.modelName; this.message = g.f( 'The %s instance is not valid. Details: %s.', context ? '`' + context + '`' : 'model', @@ -899,15 +899,15 @@ var errorHasStackProperty = !!(new Error).stack; ValidationError.maxPropertyStringLength = 32; function formatErrors(errors, propertyValues) { - var DELIM = '; '; + const DELIM = '; '; errors = errors || {}; return Object.getOwnPropertyNames(errors) .filter(function(propertyName) { return Array.isArray(errors[propertyName]); }) .map(function(propertyName) { - var messages = errors[propertyName]; - var propertyValue = propertyValues[propertyName]; + const messages = errors[propertyName]; + const propertyValue = propertyValues[propertyName]; return messages.map(function(msg) { return formatPropertyError(propertyName, propertyValue, msg); }).join(DELIM); @@ -916,8 +916,8 @@ function formatErrors(errors, propertyValues) { } function formatPropertyError(propertyName, propertyValue, errorMessage) { - var formattedValue; - var valueType = typeof propertyValue; + let formattedValue; + const valueType = typeof propertyValue; if (valueType === 'string') { formattedValue = JSON.stringify(truncatePropertyString(propertyValue)); } else if (propertyValue instanceof Date) { @@ -939,13 +939,13 @@ function formatPropertyError(propertyName, propertyValue, errorMessage) { } function truncatePropertyString(value) { - var len = ValidationError.maxPropertyStringLength; + let len = ValidationError.maxPropertyStringLength; if (value.length <= len) return value; // preserve few last characters like `}` or `]`, but no more than 3 // this way the last `} ]` in the array of objects is included in the message - var tail; - var m = value.match(/([ \t})\]]+)$/); + let tail; + const m = value.match(/([ \t})\]]+)$/); if (m) { tail = m[1].slice(-3); len -= tail.length; diff --git a/support/describe-operation-hooks.js b/support/describe-operation-hooks.js index 2812f114..0ca52e28 100644 --- a/support/describe-operation-hooks.js +++ b/support/describe-operation-hooks.js @@ -12,30 +12,30 @@ * $ open hooks.hml * */ -var Promise = global.Promise = require('bluebird'); -var DataSource = require('../').DataSource; -var Memory = require('../lib/connectors/memory').Memory; +const Promise = global.Promise = require('bluebird'); +const DataSource = require('../').DataSource; +const Memory = require('../lib/connectors/memory').Memory; -var HOOK_NAMES = [ +const HOOK_NAMES = [ 'access', 'before save', 'persist', 'loaded', 'after save', 'before delete', 'after delete', ]; -var dataSources = [ +const dataSources = [ createOptimizedDataSource(), createUnoptimizedDataSource(), ]; -var observedContexts = []; -var lastId = 0; +const observedContexts = []; +let lastId = 0; Promise.onPossiblyUnhandledRejection(function(err) { console.error('POSSIBLY UNHANDLED REJECTION', err.stack); }); /* eslint-disable camelcase */ -var operations = [ +const operations = [ function find(ds) { return ds.TestModel.find({where: {id: '1'}}); }, @@ -112,7 +112,7 @@ var operations = [ ]; /* eslint-enable camelcase */ -var p = setupTestModels(); +let p = setupTestModels(); operations.forEach(function(op) { p = p.then(runner(op)); }); @@ -120,13 +120,13 @@ operations.forEach(function(op) { p.then(report, function(err) { console.error(err.stack); }); function createOptimizedDataSource() { - var ds = new DataSource({connector: Memory}); + const ds = new DataSource({connector: Memory}); ds.name = 'Optimized'; return ds; } function createUnoptimizedDataSource() { - var ds = new DataSource({connector: Memory}); + const ds = new DataSource({connector: Memory}); ds.name = 'Unoptimized'; // disable optimized methods @@ -139,7 +139,7 @@ function createUnoptimizedDataSource() { function setupTestModels() { dataSources.forEach(function setupOnDataSource(ds) { - var TestModel = ds.TestModel = ds.createModel('TestModel', { + const TestModel = ds.TestModel = ds.createModel('TestModel', { id: {type: String, id: true, default: uid}, name: {type: String, required: true}, extra: {type: String, required: false}, @@ -155,7 +155,7 @@ function uid() { function runner(fn) { return function() { - var res = Promise.resolve(); + let res = Promise.resolve(); dataSources.forEach(function(ds) { res = res.then(function() { return resetStorage(ds); @@ -173,7 +173,7 @@ function runner(fn) { } function resetStorage(ds) { - var TestModel = ds.TestModel; + const TestModel = ds.TestModel; HOOK_NAMES.forEach(function(hook) { TestModel.clearObservers(hook); }); @@ -192,7 +192,7 @@ function resetStorage(ds) { .then(function() { HOOK_NAMES.forEach(function(hook) { TestModel.observe(hook, function(ctx, next) { - var row = observedContexts[observedContexts.length - 1]; + const row = observedContexts[observedContexts.length - 1]; row.hooks[hook] = Object.keys(ctx); next(); }); @@ -212,7 +212,7 @@ function report() { // merge rows where Optimized and Unoptimized produce the same context observedContexts.forEach(function(row, ix) { if (!ix) return; - var last = observedContexts[ix - 1]; + const last = observedContexts[ix - 1]; if (row.operation != last.operation) return; if (JSON.stringify(row.hooks) !== JSON.stringify(last.hooks)) return; last.merge = true; @@ -226,11 +226,11 @@ function report() { observedContexts.forEach(function(row) { if (row.skip) return; - var caption = row.operation; + let caption = row.operation; if (!row.merge) caption += ' (' + row.connector + ')'; console.log('' + caption + ''); HOOK_NAMES.forEach(function(h) { - var text = row.hooks[h] ? row.hooks[h].join('
') : ''; + const text = row.hooks[h] ? row.hooks[h].join('
') : ''; console.log(' ' + text + ''); }); console.log(''); diff --git a/test/CustomTypeForeignKey.test.js b/test/CustomTypeForeignKey.test.js index 62d1dcf0..3ff97d7a 100644 --- a/test/CustomTypeForeignKey.test.js +++ b/test/CustomTypeForeignKey.test.js @@ -4,12 +4,12 @@ // License text available at https://opensource.org/licenses/MIT 'use strict'; -var should = require('./init.js'); +const should = require('./init.js'); -var jdb = require('../'); -var DataSource = jdb.DataSource; +const jdb = require('../'); +const DataSource = jdb.DataSource; -var ds, Item, Variant; +let ds, Item, Variant; describe('Datasource-specific field types for foreign keys', function() { before(function() { ds = new DataSource('memory'); @@ -35,7 +35,7 @@ describe('Datasource-specific field types for foreign keys', function() { }); it('should create foreign key with database-specific field type', function(done) { - var VariantDefinition = ds.getModelDefinition('Variant'); + const VariantDefinition = ds.getModelDefinition('Variant'); should.exist(VariantDefinition); should.exist(VariantDefinition.properties.myProp.memory); should.exist(VariantDefinition.properties.myProp.memory.dataType); diff --git a/test/allow-extended-operators.test.js b/test/allow-extended-operators.test.js index 19331dd3..2bef648d 100644 --- a/test/allow-extended-operators.test.js +++ b/test/allow-extended-operators.test.js @@ -60,7 +60,7 @@ describe('allowExtendedOperators', () => { all(model, filter, options, callback) { // return the raw "value" query - let instanceFound = { + const instanceFound = { value: filter.where.value, }; callback(null, [instanceFound]); diff --git a/test/async-observer.test.js b/test/async-observer.test.js index c49a1473..5e9d23a9 100644 --- a/test/async-observer.test.js +++ b/test/async-observer.test.js @@ -4,18 +4,18 @@ // License text available at https://opensource.org/licenses/MIT 'use strict'; -var ModelBuilder = require('../').ModelBuilder; -var should = require('./init'); +const ModelBuilder = require('../').ModelBuilder; +const should = require('./init'); describe('async observer', function() { - var TestModel; + let TestModel; beforeEach(function defineTestModel() { - var modelBuilder = new ModelBuilder(); + const modelBuilder = new ModelBuilder(); TestModel = modelBuilder.define('TestModel', {name: String}); }); it('calls registered async observers', function(done) { - var notifications = []; + const notifications = []; TestModel.observe('before', pushAndNext(notifications, 'before')); TestModel.observe('after', pushAndNext(notifications, 'after')); @@ -32,7 +32,7 @@ describe('async observer', function() { }); it('allows multiple observers for the same operation', function(done) { - var notifications = []; + const notifications = []; TestModel.observe('event', pushAndNext(notifications, 'one')); TestModel.observe('event', pushAndNext(notifications, 'two')); @@ -44,7 +44,7 @@ describe('async observer', function() { }); it('allows multiple operations to be notified in one call', function(done) { - var notifications = []; + const notifications = []; TestModel.observe('event1', pushAndNext(notifications, 'one')); TestModel.observe('event2', pushAndNext(notifications, 'two')); @@ -56,10 +56,10 @@ describe('async observer', function() { }); it('inherits observers from base model', function(done) { - var notifications = []; + const notifications = []; TestModel.observe('event', pushAndNext(notifications, 'base')); - var Child = TestModel.extend('Child'); + const Child = TestModel.extend('Child'); Child.observe('event', pushAndNext(notifications, 'child')); Child.notifyObserversOf('event', {}, function(err) { @@ -70,11 +70,11 @@ describe('async observer', function() { }); it('allow multiple operations to be notified with base models', function(done) { - var notifications = []; + const notifications = []; TestModel.observe('event1', pushAndNext(notifications, 'base1')); TestModel.observe('event2', pushAndNext(notifications, 'base2')); - var Child = TestModel.extend('Child'); + const Child = TestModel.extend('Child'); Child.observe('event1', pushAndNext(notifications, 'child1')); Child.observe('event2', pushAndNext(notifications, 'child2')); @@ -86,10 +86,10 @@ describe('async observer', function() { }); it('does not modify observers in the base model', function(done) { - var notifications = []; + const notifications = []; TestModel.observe('event', pushAndNext(notifications, 'base')); - var Child = TestModel.extend('Child'); + const Child = TestModel.extend('Child'); Child.observe('event', pushAndNext(notifications, 'child')); TestModel.notifyObserversOf('event', {}, function(err) { @@ -100,10 +100,10 @@ describe('async observer', function() { }); it('always calls inherited observers', function(done) { - var notifications = []; + const notifications = []; TestModel.observe('event', pushAndNext(notifications, 'base')); - var Child = TestModel.extend('Child'); + const Child = TestModel.extend('Child'); // Important: there are no observers on the Child model Child.notifyObserversOf('event', {}, function(err) { @@ -114,7 +114,7 @@ describe('async observer', function() { }); it('can remove observers', function(done) { - var notifications = []; + const notifications = []; function call(ctx, next) { notifications.push('call'); @@ -132,7 +132,7 @@ describe('async observer', function() { }); it('can clear all observers', function(done) { - var notifications = []; + const notifications = []; function call(ctx, next) { notifications.push('call'); @@ -159,7 +159,7 @@ describe('async observer', function() { }); it('passes context to final callback', function(done) { - var context = {}; + const context = {}; TestModel.notifyObserversOf('event', context, function(err, ctx) { (ctx || 'null').should.equal(context); done(); @@ -167,7 +167,7 @@ describe('async observer', function() { }); describe('notifyObserversAround', function() { - var notifications; + let notifications; beforeEach(function() { notifications = []; TestModel.observe('before execute', @@ -177,7 +177,7 @@ describe('async observer', function() { }); it('should notify before/after observers', function(done) { - var context = {}; + const context = {}; function work(done) { process.nextTick(function() { @@ -194,7 +194,7 @@ describe('async observer', function() { }); it('should allow work with context', function(done) { - var context = {}; + const context = {}; function work(context, done) { process.nextTick(function() { @@ -212,7 +212,7 @@ describe('async observer', function() { it('should notify before/after observers with multiple results', function(done) { - var context = {}; + const context = {}; function work(done) { process.nextTick(function() { @@ -239,7 +239,7 @@ describe('async observer', function() { TestModel.observe('after invoke', pushAndNext(notifications, 'after invoke')); - var context = {}; + const context = {}; function work(done) { process.nextTick(function() { @@ -264,7 +264,7 @@ describe('async observer', function() { next(); }); - var context = {}; + const context = {}; function work(done) { process.nextTick(function() { @@ -292,7 +292,7 @@ describe('async observer', function() { }); it('handles rejected promise returned by an observer', function(done) { - var testError = new Error('expected test error'); + const testError = new Error('expected test error'); TestModel.observe('event', function(ctx) { return Promise.reject(testError); }); @@ -303,8 +303,8 @@ describe('async observer', function() { }); it('returns a promise when no callback is provided', function() { - var context = {value: 'a-test-context'}; - var p = TestModel.notifyObserversOf('event', context); + const context = {value: 'a-test-context'}; + const p = TestModel.notifyObserversOf('event', context); (p !== undefined).should.be.true; return p.then(function(result) { result.should.eql(context); @@ -312,9 +312,9 @@ describe('async observer', function() { }); it('returns a rejected promise when no callback is provided', function() { - var testError = new Error('expected test error'); + const testError = new Error('expected test error'); TestModel.observe('event', function(ctx, next) { next(testError); }); - var p = TestModel.notifyObserversOf('event', context); + const p = TestModel.notifyObserversOf('event', context); return p.then( function(result) { throw new Error('The promise should have been rejected.'); diff --git a/test/basic-querying.test.js b/test/basic-querying.test.js index 752d04d9..57fd3b4e 100644 --- a/test/basic-querying.test.js +++ b/test/basic-querying.test.js @@ -7,16 +7,16 @@ 'use strict'; /* global getSchema:false, connectorCapabilities:false */ -var async = require('async'); -var bdd = require('./helpers/bdd-if'); -var should = require('./init.js'); -var uid = require('./helpers/uid-generator'); +const async = require('async'); +const bdd = require('./helpers/bdd-if'); +const should = require('./init.js'); +const uid = require('./helpers/uid-generator'); -var db, User; +let db, User; describe('basic-querying', function() { before(function(done) { - var userModelDef = { + const userModelDef = { seq: {type: Number, index: true}, name: {type: String, index: true, sort: true}, email: {type: String, index: true}, @@ -71,7 +71,7 @@ describe('basic-querying', function() { }); it('should query by id: not found', function(done) { - var unknownId = uid.fromConnector(db) || 1; + const unknownId = uid.fromConnector(db) || 1; User.findById(unknownId, function(err, u) { should.not.exist(u); should.not.exist(err); @@ -94,10 +94,10 @@ describe('basic-querying', function() { }); describe('findByIds', function() { - var createdUsers; + let createdUsers; before(function(done) { db = getSchema(); - var people = [ + const people = [ {name: 'a', vip: true}, {name: 'b', vip: null}, {name: 'c'}, @@ -122,7 +122,7 @@ describe('basic-querying', function() { function(err, users) { should.exist(users); should.not.exist(err); - var names = users.map(function(u) { + const names = users.map(function(u) { return u.name; }); names.should.eql( @@ -142,7 +142,7 @@ describe('basic-querying', function() { {where: {vip: true}}, function(err, users) { should.exist(users); should.not.exist(err); - var names = users.map(function(u) { + const names = users.map(function(u) { return u.name; }); names.should.eql(createdUsers.slice(0, 4). @@ -283,7 +283,7 @@ describe('basic-querying', function() { User.find({order: 'order DESC'}, function(err, users) { if (err) return done(err); should.exists(users); - var order = users.map(function(u) { return u.order; }); + const order = users.map(function(u) { return u.order; }); order.should.eql([6, 5, 4, 3, 2, 1]); done(); }); @@ -471,7 +471,7 @@ describe('basic-querying', function() { User.find({where: {name: {'gte': 'Paul McCartney'}}}, function(err, users) { should.not.exist(err); users.should.have.property('length', 4); - for (var ix = 0; ix < users.length; ix++) { + for (let ix = 0; ix < users.length; ix++) { users[ix].name.should.be.greaterThanOrEqual('Paul McCartney'); } done(); @@ -493,7 +493,7 @@ describe('basic-querying', function() { }}, function(err, users) { should.not.exist(err); users.should.have.property('length', 3); - for (var ix = 0; ix < users.length; ix++) { + for (let ix = 0; ix < users.length; ix++) { users[ix].name.should.be.greaterThan('Paul McCartney'); } done(); @@ -506,7 +506,7 @@ describe('basic-querying', function() { }}, function(err, users) { should.not.exist(err); users.should.have.property('length', 2); - for (var ix = 0; ix < users.length; ix++) { + for (let ix = 0; ix < users.length; ix++) { users[ix].name.should.be.lessThan('Paul McCartney'); } done(); @@ -518,7 +518,7 @@ describe('basic-querying', function() { }}, function(err, users) { should.not.exist(err); users.should.have.property('length', 3); - for (var ix = 0; ix < users.length; ix++) { + for (let ix = 0; ix < users.length; ix++) { users[ix].name.should.be.oneOf(['John Lennon', 'Stuart Sutcliffe', 'Paul McCartney']); users[ix].vip.should.be.true(); } @@ -540,7 +540,7 @@ describe('basic-querying', function() { }}, function(err, users) { should.not.exist(err); users.should.have.property('length', 3); - for (var ix = 0; ix < users.length; ix++) { + for (let ix = 0; ix < users.length; ix++) { users[ix].name.should.be.oneOf(['John Lennon', 'Stuart Sutcliffe', 'Paul McCartney']); users[ix].vip.should.be.true(users[ix].name + ' should be VIP'); } @@ -553,7 +553,7 @@ describe('basic-querying', function() { }}, function(err, users) { should.not.exist(err); users.should.have.property('length', 2); - for (var ix = 0; ix < users.length; ix++) { + for (let ix = 0; ix < users.length; ix++) { users[ix].name.should.be.oneOf(['Ringo Starr', 'George Harrison']); users[ix].vip.should.be.false(users[ix].name + ' should not be VIP'); } @@ -578,7 +578,7 @@ describe('basic-querying', function() { }); }); - var itWhenIlikeSupported = connectorCapabilities.ilike; + const itWhenIlikeSupported = connectorCapabilities.ilike; bdd.describeIf(itWhenIlikeSupported, 'ilike', function() { it('should support "like" that is satisfied', function(done) { @@ -618,7 +618,7 @@ describe('basic-querying', function() { }); }); - var itWhenNilikeSupported = connectorCapabilities.nilike !== false; + const itWhenNilikeSupported = connectorCapabilities.nilike !== false; bdd.describeIf(itWhenNilikeSupported, 'nilike', function() { it('should support "nlike" that is satisfied', function(done) { User.find({where: {name: {nlike: 'John'}}}, @@ -783,7 +783,7 @@ describe('basic-querying', function() { }); it('should only include fields as specified', function(done) { - var remaining = 0; + let remaining = 0; function sample(fields) { return { @@ -800,7 +800,7 @@ describe('basic-querying', function() { } users.forEach(function(user) { - var obj = user.toObject(); + const obj = user.toObject(); Object.keys(obj) .forEach(function(key) { @@ -850,13 +850,13 @@ describe('basic-querying', function() { }); }); - var describeWhenNestedSupported = connectorCapabilities.nestedProperty; + const describeWhenNestedSupported = connectorCapabilities.nestedProperty; bdd.describeIf(describeWhenNestedSupported, 'query with nested property', function() { it('should support nested property in query', function(done) { User.find({where: {'address.city': 'San Jose'}}, function(err, users) { if (err) return done(err); users.length.should.be.equal(1); - for (var i = 0; i < users.length; i++) { + for (let i = 0; i < users.length; i++) { users[i].address.city.should.be.eql('San Jose'); } done(); @@ -867,7 +867,7 @@ describe('basic-querying', function() { User.find({where: {'friends.name': {regexp: /^Ringo/}}}, function(err, users) { if (err) return done(err); users.length.should.be.equal(2); - var expectedUsers = ['John Lennon', 'Paul McCartney']; + const expectedUsers = ['John Lennon', 'Paul McCartney']; expectedUsers.indexOf(users[0].name).should.not.equal(-1); expectedUsers.indexOf(users[1].name).should.not.equal(-1); done(); @@ -878,7 +878,7 @@ describe('basic-querying', function() { User.find({where: {'address.city': {gt: 'San'}}}, function(err, users) { if (err) return done(err); users.length.should.be.equal(2); - for (var i = 0; i < users.length; i++) { + for (let i = 0; i < users.length; i++) { users[i].address.state.should.be.eql('CA'); } done(); @@ -1015,7 +1015,7 @@ describe('basic-querying', function() { }); it('should check whether record not exist', function(done) { - var unknownId = uid.fromConnector(db) || 42; + const unknownId = uid.fromConnector(db) || 42; User.destroyAll(function() { User.exists(unknownId, function(err, exists) { should.not.exist(err); @@ -1027,7 +1027,7 @@ describe('basic-querying', function() { }); context('regexp operator', function() { - var invalidDataTypes = [0, true, {}, [], Function, null]; + const invalidDataTypes = [0, true, {}, [], Function, null]; before(seed); @@ -1046,7 +1046,7 @@ describe('basic-querying', function() { // FIXME: This should either be re-enabled or removed. describe.skip('queries', function() { - var Todo; + let Todo; before(function prepDb(done) { db = getSchema(); @@ -1078,7 +1078,7 @@ describe.skip('queries', function() { }); it('should work for updateOrCreate/upsert', function(done) { - var aliases = ['updateOrCreate', 'upsert']; + const aliases = ['updateOrCreate', 'upsert']; async.each(aliases, function(alias, cb) { Todo[alias]({content: 'Buy ham'}, function(err) { should.not.exist(err); @@ -1118,7 +1118,7 @@ describe.skip('queries', function() { it('should work for deleteAll/destroyAll/remove', function(done) { // FIXME: We should add a DAO.delete static method alias for consistency // (DAO.prototype.delete instance method already exists) - var aliases = ['deleteAll', 'destroyAll', 'remove']; + const aliases = ['deleteAll', 'destroyAll', 'remove']; async.each(aliases, function(alias, cb) { Todo[alias](function(err) { should.not.exist(err); @@ -1143,7 +1143,7 @@ describe.skip('queries', function() { }); context('that require an id', function() { - var expectedErrMsg = 'Primary key is missing for the Todo model'; + const expectedErrMsg = 'Primary key is missing for the Todo model'; it('should return an error for findById', function(done) { Todo.findById(1, function(err) { @@ -1163,7 +1163,7 @@ describe.skip('queries', function() { it('should return an error for deleteById/destroyById/removeById', function(done) { - var aliases = ['deleteById', 'destroyById', 'removeById']; + const aliases = ['deleteById', 'destroyById', 'removeById']; async.each(aliases, function(alias, cb) { Todo[alias](1, function(err) { should.exist(err); @@ -1174,7 +1174,7 @@ describe.skip('queries', function() { }); it('should return an error for instance.save', function(done) { - var todo = new Todo(); + const todo = new Todo(); todo.content = 'Buy ham'; todo.save(function(err) { should.exist(err); @@ -1216,7 +1216,7 @@ describe.skip('queries', function() { }); function seed(done) { - var beatles = [ + const beatles = [ { seq: 0, name: 'John Lennon', @@ -1285,6 +1285,6 @@ function seed(done) { } function nextAfterDelay(ctx, next) { - var randomTimeoutTrigger = Math.floor(Math.random() * 100); + const randomTimeoutTrigger = Math.floor(Math.random() * 100); setTimeout(function() { process.nextTick(next); }, randomTimeoutTrigger); } diff --git a/test/common_test.js b/test/common_test.js index 08e8c09c..96771588 100644 --- a/test/common_test.js +++ b/test/common_test.js @@ -5,13 +5,13 @@ 'use strict'; -var Schema = require('../index').Schema; -var Text = Schema.Text; +const Schema = require('../index').Schema; +const Text = Schema.Text; -var nbSchemaRequests = 0; +let nbSchemaRequests = 0; -var batch; -var schemaName; +let batch; +let schemaName; function it(name, cases) { batch[schemaName][name] = cases; @@ -27,7 +27,7 @@ module.exports = function testSchema(exportCasesHere, dataSource) { if (dataSource.name.match(/^\/.*\/test\/\.\.$/)) { schemaName = schemaName.split('/').slice(-3).shift(); } - var start; + let start; batch['should connect to database'] = function(test) { start = Date.now(); @@ -70,12 +70,12 @@ Object.defineProperty(module.exports, 'skip', { }); function clearAndCreate(model, data, callback) { - var createdItems = []; + const createdItems = []; model.destroyAll(function() { nextItem(null, null); }); - var itemIndex = 0; + let itemIndex = 0; function nextItem(err, lastItem) { if (lastItem !== null) { @@ -92,9 +92,9 @@ function clearAndCreate(model, data, callback) { /* eslint-disable mocha/handle-done-callback */ function testOrm(dataSource) { - var requestsAreCounted = dataSource.name !== 'mongodb'; + const requestsAreCounted = dataSource.name !== 'mongodb'; - var Post, User, Passport, Log, Dog; + let Post, User, Passport, Log, Dog; it('should define class', function(test) { User = dataSource.define('User', { @@ -123,7 +123,7 @@ function testOrm(dataSource) { extra: Object, }); - var newuser = new User({settings: {hey: 'you'}}); + const newuser = new User({settings: {hey: 'you'}}); test.ok(newuser.settings); Post = dataSource.define('Post', { @@ -177,7 +177,7 @@ function testOrm(dataSource) { Passport.belongsTo(User, {as: 'owner', foreignKey: 'ownerId'}); User.hasMany(Passport, {as: 'passports', foreignKey: 'ownerId'}); - var user = new User; + const user = new User; test.ok(User instanceof Function); @@ -199,7 +199,7 @@ function testOrm(dataSource) { }); it('should initialize object properly', function(test) { - var hw = 'Hello word', + const hw = 'Hello word', now = Date.now(), post = new Post({title: hw}), anotherPost = Post({title: 'Resig style constructor'}); @@ -218,7 +218,7 @@ function testOrm(dataSource) { }); it('should save object', function(test) { - var title = 'Initial title', title2 = 'Hello world', + const title = 'Initial title', title2 = 'Hello world', date = new Date; Post.create({ @@ -234,7 +234,7 @@ function testOrm(dataSource) { test.equal(obj.title, title2); test.ok(!obj.propertyChanged('title')); - var p = new Post({title: 1}); + const p = new Post({title: 1}); p.title = 2; p.save(function(err, obj) { test.ok(!p.propertyChanged('title')); @@ -252,7 +252,7 @@ function testOrm(dataSource) { }); it('should create object with initial data', function(test) { - var title = 'Initial title', + const title = 'Initial title', date = new Date; Post.create({ @@ -301,8 +301,8 @@ function testOrm(dataSource) { */ it('should not re-instantiate object on saving', function(test) { - var title = 'Initial title'; - var post = new Post({title: title}); + const title = 'Initial title'; + const post = new Post({title: title}); post.save(function(err, savedPost) { test.strictEqual(post, savedPost); test.done(); @@ -329,21 +329,21 @@ function testOrm(dataSource) { }); it('should handle virtual attributes', function(test) { - var salt = 's0m3s3cr3t5a1t'; + const salt = 's0m3s3cr3t5a1t'; User.setter.passwd = function(password) { this._passwd = calcHash(password, salt); }; function calcHash(pass, salt) { - var crypto = require('crypto'); - var hash = crypto.createHash('sha256'); + const crypto = require('crypto'); + const hash = crypto.createHash('sha256'); hash.update(pass); hash.update(salt); return hash.digest('base64'); } - var u = new User; + const u = new User; u.passwd = 's3cr3t'; test.equal(u.passwd, calcHash('s3cr3t', salt)); test.done(); @@ -380,7 +380,7 @@ function testOrm(dataSource) { }); }); - var countOfposts, countOfpostsFiltered; + let countOfposts, countOfpostsFiltered; it('should fetch collection', function(test) { Post.all(function(err, posts) { countOfposts = posts.length; @@ -394,7 +394,7 @@ function testOrm(dataSource) { }); it('should find records filtered with multiple attributes', function(test) { - var d = new Date; + const d = new Date; Post.create({title: 'title', content: 'content', published: true, date: d}, function(err, post) { Post.all({where: {title: 'title', date: d, published: true}}, function(err, res) { test.equals(res.length, 1, 'Filtering Posts returns one post'); @@ -485,8 +485,8 @@ function testOrm(dataSource) { // Finding one post with an existing author associated Post.all(function(err, posts) { // We try to get the first post with a userId != NULL - for (var i = 0; i < posts.length; i++) { - var post = posts[i]; + for (let i = 0; i < posts.length; i++) { + const post = posts[i]; if (post.userId) { // We could get the user with belongs to relationship but it is better if there is no interactions. User.findById(post.userId, function(err, user) { @@ -495,7 +495,7 @@ function testOrm(dataSource) { // There can't be any concurrency because we are counting requests // We are first testing cases when user has posts user.posts(function(err, data) { - var nbInitialRequests = nbSchemaRequests; + const nbInitialRequests = nbSchemaRequests; user.posts(function(err, data2) { test.equal(data.length, 2, 'There should be 2 posts.'); test.equal(data.length, data2.length, 'Posts should be the same, since we are loading on the same object.'); @@ -514,7 +514,7 @@ function testOrm(dataSource) { // We are now testing cases when user doesn't have any post voidUser.posts(function(err, data) { - var nbInitialRequests = nbSchemaRequests; + const nbInitialRequests = nbSchemaRequests; voidUser.posts(function(err, data2) { test.equal(data.length, 0, 'There shouldn\'t be any posts (1/2).'); test.equal(data2.length, 0, 'There shouldn\'t be any posts (2/2).'); @@ -550,13 +550,13 @@ function testOrm(dataSource) { // }); it('should support scopes', function(test) { - var wait = 2; + let wait = 2; test.ok(Post.scope, 'Scope supported'); Post.scope('published', {where: {published: true}}); test.ok(typeof Post.published === 'function'); test.ok(Post.published._scope.where.published === true); - var post = Post.published.build(); + const post = Post.published.build(); test.ok(post.published, 'Can build'); test.ok(post.isNewRecord()); Post.published.create(function(err, psto) { @@ -583,14 +583,14 @@ function testOrm(dataSource) { it('should return type of property', function(test) { test.equal(Post.getPropertyType('title'), 'String'); test.equal(Post.getPropertyType('content'), 'Text'); - var p = new Post; + const p = new Post; test.equal(p.getPropertyType('title'), 'String'); test.equal(p.getPropertyType('content'), 'Text'); test.done(); }); it('should handle ORDER clause', function(test) { - var titles = [ + const titles = [ {title: 'Title A', subject: 'B'}, {title: 'Title Z', subject: 'A'}, {title: 'Title M', subject: 'C'}, @@ -598,8 +598,8 @@ function testOrm(dataSource) { {title: 'Title B', subject: 'A'}, {title: 'Title C', subject: 'D'}, ]; - var isRedis = Post.dataSource.name === 'redis'; - var dates = isRedis ? [5, 9, 0, 17, 10, 9] : [ + const isRedis = Post.dataSource.name === 'redis'; + const dates = isRedis ? [5, 9, 0, 17, 10, 9] : [ new Date(1000 * 5), new Date(1000 * 9), new Date(1000 * 0), @@ -611,7 +611,7 @@ function testOrm(dataSource) { Post.create({title: t.title, subject: t.subject, date: dates[i]}, done); }); - var i = 0, tests = 0; + let i = 0, tests = 0; function done(err, obj) { if (++i === titles.length) { @@ -717,7 +717,7 @@ function testOrm(dataSource) { }); } - var fin = 0; + let fin = 0; function finished() { if (++fin === tests) { @@ -871,8 +871,8 @@ function testOrm(dataSource) { // }); it('should handle order clause with direction', function(test) { - var wait = 0; - var emails = [ + let wait = 0; + const emails = [ 'john@hcompany.com', 'tom@hcompany.com', 'admin@hcompany.com', @@ -887,7 +887,7 @@ function testOrm(dataSource) { User.create({email: email, name: 'Nick'}, done); }); }); - var tests = 2; + let tests = 2; function done() { process.nextTick(function() { @@ -900,7 +900,7 @@ function testOrm(dataSource) { function doSortTest() { User.all({order: 'email ASC', where: {name: 'Nick'}}, function(err, users) { - var _emails = emails.sort(); + const _emails = emails.sort(); users.forEach(function(user, i) { test.equal(_emails[i], user.email, 'ASC sorting'); }); @@ -910,7 +910,7 @@ function testOrm(dataSource) { function doReverseSortTest() { User.all({order: 'email DESC', where: {name: 'Nick'}}, function(err, users) { - var _emails = emails.sort().reverse(); + const _emails = emails.sort().reverse(); users.forEach(function(user, i) { test.equal(_emails[i], user.email, 'DESC sorting'); }); @@ -925,7 +925,7 @@ function testOrm(dataSource) { it('should return id in find result even after updateAttributes', function(test) { Post.create(function(err, post) { - var id = post.id; + const id = post.id; test.ok(post.published === false); post.updateAttributes({title: 'hey', published: true}, function() { Post.find(id, function(err, post) { @@ -938,7 +938,7 @@ function testOrm(dataSource) { }); it('should handle belongsTo correctly', function(test) { - var passport = new Passport({ownerId: 16}); + const passport = new Passport({ownerId: 16}); // sync getter test.equal(passport.owner(), 16); // sync setter @@ -1017,7 +1017,7 @@ function testOrm(dataSource) { if (dataSource.name !== 'mongoose' && dataSource.name !== 'neo4j') it('should update or create record', function(test) { - var newData = { + const newData = { id: 1, title: 'New title (really new)', content: 'Some example content (updated)', @@ -1058,7 +1058,7 @@ function testOrm(dataSource) { User.setter.passwd = function(pass) { this._passwd = pass + 'salt'; }; - var u = new User({passwd: 'qwerty'}); + const u = new User({passwd: 'qwerty'}); test.equal(u.passwd, 'qwertysalt'); u.save(function(err, user) { User.findById(user.id, function(err, user) { @@ -1083,10 +1083,10 @@ function testOrm(dataSource) { }); it('should work with typed and untyped nested collections', function(test) { - var post = new Post; - var like = post.likes.push({foo: 'bar'}); + const post = new Post; + const like = post.likes.push({foo: 'bar'}); test.equal(like.constructor.name, 'ListItem'); - var related = post.related.push({hello: 'world'}); + const related = post.related.push({hello: 'world'}); test.ok(related.someMethod); post.save(function(err, p) { test.equal(p.likes.nextid, 2); @@ -1119,7 +1119,7 @@ function testOrm(dataSource) { }); it('should find or create', function(test) { - var email = 'some email ' + Math.random(); + const email = 'some email ' + Math.random(); User.findOrCreate({where: {email: email}}, function(err, u, created) { test.ok(u); test.ok(!u.age); diff --git a/test/crud-with-options.test.js b/test/crud-with-options.test.js index 49523ffe..4300f46f 100644 --- a/test/crud-with-options.test.js +++ b/test/crud-with-options.test.js @@ -7,9 +7,9 @@ 'use strict'; /* global getSchema:false */ -var should = require('./init.js'); -var async = require('async'); -var db, User, options, filter; +const should = require('./init.js'); +const async = require('async'); +let db, User, options, filter; describe('crud-with-options', function() { before(function(done) { @@ -193,7 +193,7 @@ describe('crud-with-options', function() { describe('findByIds', function() { before(function(done) { - var people = [ + const people = [ {id: 1, name: 'a', vip: true}, {id: 2, name: 'b'}, {id: 3, name: 'c'}, @@ -213,7 +213,7 @@ describe('crud-with-options', function() { User.findByIds([3, 2, 1], function(err, users) { should.exist(users); should.not.exist(err); - var names = users.map(function(u) { return u.name; }); + const names = users.map(function(u) { return u.name; }); names.should.eql(['c', 'b', 'a']); done(); }); @@ -225,7 +225,7 @@ describe('crud-with-options', function() { {where: {vip: true}}, options, function(err, users) { should.exist(users); should.not.exist(err); - var names = users.map(function(u) { + const names = users.map(function(u) { return u.name; }); names.should.eql(['d', 'a']); @@ -407,15 +407,15 @@ describe('crud-with-options', function() { describe('save', function() { it('should allow save(options, cb)', function(done) { - var options = {foo: 'bar'}; - var opts; + const options = {foo: 'bar'}; + let opts; User.observe('after save', function(ctx, next) { opts = ctx.options; next(); }); - var u = new User(); + const u = new User(); u.save(options, function(err) { should.not.exist(err); options.should.equal(opts); @@ -605,7 +605,7 @@ describe('upsertWithWhere', function() { }); function seed(done) { - var beatles = [ + const beatles = [ { id: 0, seq: 0, diff --git a/test/datasource.test.js b/test/datasource.test.js index cfd883ff..920f66c7 100644 --- a/test/datasource.test.js +++ b/test/datasource.test.js @@ -5,12 +5,12 @@ 'use strict'; -var should = require('./init.js'); -var DataSource = require('../lib/datasource.js').DataSource; +const should = require('./init.js'); +const DataSource = require('../lib/datasource.js').DataSource; describe('DataSource', function() { it('reports helpful error when connector init throws', function() { - var throwingConnector = { + const throwingConnector = { name: 'loopback-connector-throwing', initialize: function(ds, cb) { throw new Error('expected test error'); @@ -50,7 +50,7 @@ describe('DataSource', function() { * new DataSource(dsName, settings) without settings.name */ it('should retain the name assigned to it', function() { - var dataSource = new DataSource('myDataSource', { + const dataSource = new DataSource('myDataSource', { connector: 'memory', }); @@ -61,7 +61,7 @@ describe('DataSource', function() { * new DataSource(dsName, settings) */ it('should allow the name assigned to it to take precedence over the settings name', function() { - var dataSource = new DataSource('myDataSource', { + const dataSource = new DataSource('myDataSource', { name: 'defaultDataSource', connector: 'memory', }); @@ -73,7 +73,7 @@ describe('DataSource', function() { * new DataSource(settings) with settings.name */ it('should retain the name from the settings if no name is assigned', function() { - var dataSource = new DataSource({ + const dataSource = new DataSource({ name: 'defaultDataSource', connector: 'memory', }); @@ -85,7 +85,7 @@ describe('DataSource', function() { * new DataSource(undefined, settings) */ it('should retain the name from the settings if name is undefined', function() { - var dataSource = new DataSource(undefined, { + const dataSource = new DataSource(undefined, { name: 'defaultDataSource', connector: 'memory', }); @@ -97,7 +97,7 @@ describe('DataSource', function() { * new DataSource(settings) without settings.name */ it('should use the connector name if no name is provided', function() { - var dataSource = new DataSource({ + const dataSource = new DataSource({ connector: 'memory', }); @@ -115,7 +115,7 @@ describe('DataSource', function() { return cb(null); }, }; - var dataSource = new DataSource(mockConnector); + const dataSource = new DataSource(mockConnector); dataSource.name.should.equal('loopback-connector-mock'); dataSource.connector.should.equal(mockConnector); @@ -132,7 +132,7 @@ describe('DataSource', function() { return cb(null); }, }; - var dataSource = new DataSource('myDataSource', mockConnector); + const dataSource = new DataSource('myDataSource', mockConnector); dataSource.name.should.equal('myDataSource'); dataSource.connector.should.equal(mockConnector); @@ -149,7 +149,7 @@ describe('DataSource', function() { return cb(null); }, }; - var dataSource = new DataSource(mockConnector, {name: 'myDataSource'}); + const dataSource = new DataSource(mockConnector, {name: 'myDataSource'}); dataSource.name.should.equal('myDataSource'); dataSource.connector.should.equal(mockConnector); @@ -169,7 +169,7 @@ describe('DataSource', function() { }); }, }; - var dataSource = new DataSource(mockConnector); + const dataSource = new DataSource(mockConnector); // DataSource is instantiated // connected: false, connecting: false, initialized: false dataSource.connected.should.be.false(); @@ -227,7 +227,7 @@ describe('DataSource', function() { }); }, }; - var dataSource = new DataSource(mockConnector); + const dataSource = new DataSource(mockConnector); // DataSource is instantiated // connected: false, connecting: false, initialized: false dataSource.connected.should.be.false(); @@ -282,7 +282,7 @@ describe('DataSource', function() { }); }, }; - var dataSource = new DataSource(mockConnector, {lazyConnect: true}); + const dataSource = new DataSource(mockConnector, {lazyConnect: true}); // DataSource is instantiated // connected: false, connecting: false, initialized: false dataSource.connected.should.be.false(); diff --git a/test/datatype.test.js b/test/datatype.test.js index 6015e8b1..1dbe12c1 100644 --- a/test/datatype.test.js +++ b/test/datatype.test.js @@ -7,15 +7,15 @@ 'use strict'; /* global getSchema:false */ -var should = require('./init.js'); +const should = require('./init.js'); -var db, Model; +let db, Model; describe('datatypes', function() { before(function(done) { db = getSchema(); - var Nested = db.define('Nested', {}); - var modelTableSchema = { + const Nested = db.define('Nested', {}); + const modelTableSchema = { str: String, date: Date, num: Number, @@ -30,7 +30,7 @@ describe('datatypes', function() { it('should return 400 when property of type array is set to string value', function(done) { - var myModel = db.define('myModel', { + const myModel = db.define('myModel', { list: {type: ['object']}, }); @@ -42,7 +42,7 @@ describe('datatypes', function() { it('should return 400 when property of type array is set to object value', function(done) { - var myModel = db.define('myModel', { + const myModel = db.define('myModel', { list: {type: ['object']}, }); @@ -53,7 +53,7 @@ describe('datatypes', function() { }); it('should keep types when get read data from db', function(done) { - var d = new Date('2015-01-01T12:00:00'), id; + let d = new Date('2015-01-01T12:00:00'), id; Model.create({ str: 'hello', date: d, num: '3', bool: 1, list: ['test'], arr: [1, 'str'], @@ -101,7 +101,7 @@ describe('datatypes', function() { }); it('should respect data types when updating attributes', function(done) { - var d = new Date, id; + const d = new Date, id; Model.create({ str: 'hello', date: d, num: '3', bool: 1}, function(err, m) { @@ -151,7 +151,7 @@ describe('datatypes', function() { }); it('should not coerce nested objects into ModelConstructor types', function() { - var coerced = Model._coerce({nested: {foo: 'bar'}}); + const coerced = Model._coerce({nested: {foo: 'bar'}}); coerced.nested.constructor.name.should.equal('Object'); }); @@ -176,13 +176,13 @@ describe('datatypes', function() { data: {type: 'string'}, }); db.automigrate(['HandleNullModel'], function() { - let a = new Model(null); + const a = new Model(null); done(); }); }); describe('model option persistUndefinedAsNull', function() { - var TestModel, isStrict; + let TestModel, isStrict; before(function(done) { db = getSchema(); TestModel = db.define( @@ -203,7 +203,7 @@ describe('datatypes', function() { }); it('should set missing optional properties to null', function(done) { - var EXPECTED = {desc: null, stars: null}; + const EXPECTED = {desc: null, stars: null}; TestModel.create({name: 'a-test-name'}, function(err, created) { if (err) return done(err); created.should.have.properties(EXPECTED); @@ -217,8 +217,8 @@ describe('datatypes', function() { }); it('should convert property value undefined to null', function(done) { - var EXPECTED = {desc: null, extra: null}; - var data = {desc: undefined, extra: undefined}; + const EXPECTED = {desc: null, extra: null}; + const data = {desc: undefined, extra: undefined}; if (isStrict) { // SQL-based connectors don't support dynamic properties delete EXPECTED.extra; @@ -238,21 +238,21 @@ describe('datatypes', function() { }); it('should convert undefined to null in the setter', function() { - var inst = new TestModel(); + const inst = new TestModel(); inst.desc = undefined; inst.should.have.property('desc', null); inst.toObject().should.have.property('desc', null); }); it('should use null in unsetAttribute()', function() { - var inst = new TestModel(); + const inst = new TestModel(); inst.unsetAttribute('stars'); inst.should.have.property('stars', null); inst.toObject().should.have.property('stars', null); }); it('should convert undefined to null on save', function(done) { - var EXPECTED = {desc: null, stars: null, extra: null, dx: null}; + const EXPECTED = {desc: null, stars: null, extra: null, dx: null}; if (isStrict) { // SQL-based connectors don't support dynamic properties delete EXPECTED.extra; @@ -298,7 +298,7 @@ describe('datatypes', function() { }); it('should convert undefined to null in toObject()', function() { - var inst = new TestModel(); + const inst = new TestModel(); inst.desc = undefined; // Note: this may be a no-op inst.unsetAttribute('stars'); inst.extra = undefined; diff --git a/test/date-string.test.js b/test/date-string.test.js index c1ba8b2e..1dbdb1da 100644 --- a/test/date-string.test.js +++ b/test/date-string.test.js @@ -10,16 +10,16 @@ require('should'); -var DateString = require('../lib/date-string'); -var fmt = require('util').format; -var inspect = require('util').inspect; -var os = require('os'); +const DateString = require('../lib/date-string'); +const fmt = require('util').format; +const inspect = require('util').inspect; +const os = require('os'); describe('DateString', function() { describe('constructor', function() { it('should support a valid date string', function() { - var theDate = '2015-01-01'; - var date = new DateString(theDate); + const theDate = '2015-01-01'; + const date = new DateString(theDate); date.should.not.eql(null); date.when.should.eql(theDate); date.toString().should.eql(theDate); @@ -37,16 +37,16 @@ describe('DateString', function() { testInvalidInput('should throw on null input', null, 'Input must be a string'); it('should update internal date on set', function() { - var date = new DateString('2015-01-01'); + const date = new DateString('2015-01-01'); date.when = '2016-01-01'; date.when.should.eql('2016-01-01'); - var d = new Date('2016-01-01'); + const d = new Date('2016-01-01'); // The internal date representation should also be updated! date._date.toString().should.eql(d.toString()); }); it('should return custom inspect output', function() { - var date = new DateString('2015-01-01'); - var result = inspect(date); + const date = new DateString('2015-01-01'); + const result = inspect(date); result.should.not.eql(null); result.should.eql(fmt('DateString ' + inspect({ when: date.when, @@ -55,24 +55,24 @@ describe('DateString', function() { }); it('should return JSON output', function() { - var date = new DateString('2015-01-01'); - var result = date.toJSON(); + const date = new DateString('2015-01-01'); + const result = date.toJSON(); result.should.eql(JSON.stringify({when: date.when})); }); function testValidInput(msg, val) { it(msg, function() { - var theDate = new DateString(val); + const theDate = new DateString(val); theDate.when.should.eql(val); - var d = new Date(val); + const d = new Date(val); theDate._date.toString().should.eql(d.toString()); }); } function testInvalidInput(msg, val, err) { it(msg, () => { - var fn = () => { - var theDate = new DateString(val); + const fn = () => { + const theDate = new DateString(val); }; fn.should.throw(err); }); diff --git a/test/default-scope.test.js b/test/default-scope.test.js index 3db2f23b..e38f18fa 100644 --- a/test/default-scope.test.js +++ b/test/default-scope.test.js @@ -7,10 +7,10 @@ 'use strict'; /* global getSchema:false */ -var should = require('./init.js'); -var async = require('async'); +const should = require('./init.js'); +const async = require('async'); -var db, Category, Product, Tool, Widget, Thing, Person; +let db, Category, Product, Tool, Widget, Thing, Person; // This test requires a connector that can // handle a custom collection or table name @@ -18,7 +18,7 @@ var db, Category, Product, Tool, Widget, Thing, Person; // TODO [fabien] add table for pgsql/mysql // TODO [fabien] change model definition - see #293 -var setupProducts = function(ids, done) { +const setupProducts = function(ids, done) { async.series([ function(next) { Tool.create({name: 'Tool Z'}, function(err, inst) { @@ -72,7 +72,7 @@ describe('default scope', function() { }); Product.lookupModel = function(data) { - var m = this.dataSource.models[data.kind]; + const m = this.dataSource.models[data.kind]; if (m.base === this) return m; return this; }; @@ -104,11 +104,11 @@ describe('default scope', function() { // inst is only valid for instance methods // like save, updateAttributes - var scopeFn = function(target, inst) { + const scopeFn = function(target, inst) { return {where: {kind: this.modelName}}; }; - var propertiesFn = function(target, inst) { + const propertiesFn = function(target, inst) { return {kind: this.modelName}; }; @@ -138,14 +138,14 @@ describe('default scope', function() { }); describe('manipulation', function() { - var ids = {}; + const ids = {}; before(function(done) { db.automigrate(done); }); it('should return a scoped instance', function() { - var p = new Tool({name: 'Product A', kind: 'ignored'}); + const p = new Tool({name: 'Product A', kind: 'ignored'}); p.name.should.equal('Product A'); p.kind.should.equal('Tool'); p.setAttributes({kind: 'ignored'}); @@ -205,7 +205,7 @@ describe('default scope', function() { }); it('should update a scoped instance - updateOrCreate', function(done) { - var data = {id: ids.productA, description: 'Anything...', kind: 'ingored'}; + const data = {id: ids.productA, description: 'Anything...', kind: 'ingored'}; Tool.updateOrCreate(data, function(err, p) { should.not.exist(err); p.name.should.equal('Product A'); @@ -217,7 +217,7 @@ describe('default scope', function() { }); describe('findById', function() { - var ids = {}; + const ids = {}; before(function(done) { db.automigrate(setupProducts.bind(null, ids, done)); @@ -250,7 +250,7 @@ describe('default scope', function() { }); describe('find', function() { - var ids = {}; + const ids = {}; before(function(done) { db.automigrate(setupProducts.bind(null, ids, done)); @@ -322,7 +322,7 @@ describe('default scope', function() { }); describe('exists', function() { - var ids = {}; + const ids = {}; before(function(done) { db.automigrate(setupProducts.bind(null, ids, done)); @@ -370,7 +370,7 @@ describe('default scope', function() { }); describe('count', function() { - var ids = {}; + const ids = {}; before(function(done) { db.automigrate(setupProducts.bind(null, ids, done)); @@ -418,7 +418,7 @@ describe('default scope', function() { }); describe('removeById', function() { - var ids = {}; + const ids = {}; function isDeleted(id, done) { Product.exists(id, function(err, exists) { @@ -476,7 +476,7 @@ describe('default scope', function() { }); describe('update', function() { - var ids = {}; + const ids = {}; before(function(done) { db.automigrate(setupProducts.bind(null, ids, done)); @@ -521,7 +521,7 @@ describe('default scope', function() { }); describe('remove', function() { - var ids = {}; + const ids = {}; before(function(done) { db.automigrate(setupProducts.bind(null, ids, done)); @@ -593,7 +593,7 @@ describe('default scope', function() { }); describe('scopes', function() { - var ids = {}; + const ids = {}; before(function(done) { db.automigrate(setupProducts.bind(null, ids, done)); @@ -673,7 +673,7 @@ describe('default scope', function() { products.should.have.length(2); products[0].name.should.equal('Product'); products[1].name.should.equal('Product'); - var kinds = products.map(function(p) { return p.kind; }); + const kinds = products.map(function(p) { return p.kind; }); kinds.sort(); kinds.should.eql(['Thing', 'Widget']); done(); @@ -682,7 +682,7 @@ describe('default scope', function() { }); describe('relations', function() { - var ids = {}; + const ids = {}; before(function(done) { db.automigrate(done); @@ -817,7 +817,7 @@ describe('default scope', function() { Person.findById(1, function(err, person) { should.not.exist(err); should.exist(person); - var things = person.things(); + const things = person.things(); should.exist(things); things.should.be.an.instanceOf(Array); things.should.have.length(1); diff --git a/test/defaults.test.js b/test/defaults.test.js index 237c1b4d..c0503c71 100644 --- a/test/defaults.test.js +++ b/test/defaults.test.js @@ -7,12 +7,12 @@ 'use strict'; /* global getSchema:false */ -var should = require('./init.js'); +const should = require('./init.js'); -var db = getSchema(); +const db = getSchema(); describe('defaults', function() { - var Server; + let Server; before(function() { Server = db.define('Server', { @@ -23,7 +23,7 @@ describe('defaults', function() { }); it('should apply defaults on new', function() { - var s = new Server; + const s = new Server; s.port.should.equal(80); }); diff --git a/test/discovery.test.js b/test/discovery.test.js index 5a55833a..cf501762 100644 --- a/test/discovery.test.js +++ b/test/discovery.test.js @@ -5,17 +5,17 @@ 'use strict'; -var jdb = require('../'); -var DataSource = jdb.DataSource; -var should = require('./init.js'); +const jdb = require('../'); +const DataSource = jdb.DataSource; +const should = require('./init.js'); describe('Memory connector with mocked discovery', function() { - var ds; + let ds; before(function() { ds = new DataSource({connector: 'memory'}); - var models = [{type: 'table', name: 'CUSTOMER', owner: 'STRONGLOOP'}, + const models = [{type: 'table', name: 'CUSTOMER', owner: 'STRONGLOOP'}, {type: 'table', name: 'INVENTORY', owner: 'STRONGLOOP'}, {type: 'table', name: 'LOCATION', owner: 'STRONGLOOP'}]; @@ -25,7 +25,7 @@ describe('Memory connector with mocked discovery', function() { }); }; - var modelProperties = [{ + const modelProperties = [{ owner: 'STRONGLOOP', tableName: 'INVENTORY', columnName: 'PRODUCT_ID', @@ -77,7 +77,7 @@ describe('Memory connector with mocked discovery', function() { ds.discoverSchemas('INVENTORY', {}, function(err, schemas) { if (err) return done(err); schemas.should.have.property('STRONGLOOP.INVENTORY'); - var s = schemas['STRONGLOOP.INVENTORY']; + const s = schemas['STRONGLOOP.INVENTORY']; s.name.should.be.eql('Inventory'); Object.keys(s.properties).should.be.eql( ['productId', 'locationId', 'available', 'total'] @@ -95,7 +95,7 @@ describe('Memory connector with mocked discovery', function() { }, function(err, schemas) { if (err) return done(err); schemas.should.have.property('STRONGLOOP.INVENTORY'); - var s = schemas['STRONGLOOP.INVENTORY']; + const s = schemas['STRONGLOOP.INVENTORY']; s.name.should.be.eql('inventory'); Object.keys(s.properties).should.be.eql( ['product_id', 'location_id', 'available', 'total'] @@ -109,7 +109,7 @@ describe('Memory connector with mocked discovery', function() { ds.discoverSchemas('INVENTORY', {nameMapper: null}, function(err, schemas) { if (err) return done(err); schemas.should.have.property('STRONGLOOP.INVENTORY'); - var s = schemas['STRONGLOOP.INVENTORY']; + const s = schemas['STRONGLOOP.INVENTORY']; s.name.should.be.eql('INVENTORY'); Object.keys(s.properties).should.be.eql( ['PRODUCT_ID', 'LOCATION_ID', 'AVAILABLE', 'TOTAL'] @@ -120,7 +120,7 @@ describe('Memory connector with mocked discovery', function() { it('should honor connector\'s discoverSchemas implementation', function(done) { - var models = { + const models = { inventory: { product: {type: 'string'}, location: {type: 'string'}, @@ -140,7 +140,7 @@ describe('Memory connector with mocked discovery', function() { it('should callback function, passed as options parameter', function(done) { - var models = { + const models = { inventory: { product: {type: 'string'}, location: {type: 'string'}, @@ -152,7 +152,7 @@ describe('Memory connector with mocked discovery', function() { }); }; - var options = function(err, schemas) { + const options = function(err, schemas) { if (err) return done(err); schemas.should.be.eql(models); done(); @@ -168,7 +168,7 @@ describe('Memory connector with mocked discovery', function() { .then(function(schemas) { schemas.should.have.property('STRONGLOOP.INVENTORY'); - var s = schemas['STRONGLOOP.INVENTORY']; + const s = schemas['STRONGLOOP.INVENTORY']; s.name.should.be.eql('Inventory'); Object.keys(s.properties).should.be.eql( @@ -182,8 +182,8 @@ describe('Memory connector with mocked discovery', function() { }); describe('discoverSchema', function() { - var models; - var schema; + let models; + let schema; before(function() { schema = { name: 'Inventory', @@ -265,7 +265,7 @@ describe('Memory connector with mocked discovery', function() { }); it('should callback function, passed as options parameter', function(done) { - var options = function(err, schemas) { + const options = function(err, schemas) { if (err) return done(err); schemas.should.be.eql(schema); done(); @@ -288,11 +288,11 @@ describe('Memory connector with mocked discovery', function() { }); describe('discoverModelDefinitions', function() { - var ds; + let ds; before(function() { ds = new DataSource({connector: 'memory'}); - var models = [{type: 'table', name: 'CUSTOMER', owner: 'STRONGLOOP'}, + const models = [{type: 'table', name: 'CUSTOMER', owner: 'STRONGLOOP'}, {type: 'table', name: 'INVENTORY', owner: 'STRONGLOOP'}, {type: 'table', name: 'LOCATION', owner: 'STRONGLOOP'}]; @@ -307,7 +307,7 @@ describe('discoverModelDefinitions', function() { ds.discoverModelDefinitions({}, function(err, schemas) { if (err) return done(err); - var tableNames = schemas.map(function(s) { + const tableNames = schemas.map(function(s) { return s.name; }); @@ -319,10 +319,10 @@ describe('discoverModelDefinitions', function() { }); it('should callback function, passed as options parameter', function(done) { - var options = function(err, schemas) { + const options = function(err, schemas) { if (err) return done(err); - var tableNames = schemas.map(function(s) { + const tableNames = schemas.map(function(s) { return s.name; }); @@ -338,7 +338,7 @@ describe('discoverModelDefinitions', function() { it('should discover model using `discoverModelDefinitions` - promise variant', function(done) { ds.discoverModelDefinitions({}) .then(function(schemas) { - var tableNames = schemas.map(function(s) { + const tableNames = schemas.map(function(s) { return s.name; }); @@ -354,8 +354,8 @@ describe('discoverModelDefinitions', function() { }); describe('discoverModelProperties', function() { - var ds; - var modelProperties; + let ds; + let modelProperties; before(function() { ds = new DataSource({connector: 'memory'}); @@ -408,7 +408,7 @@ describe('discoverModelProperties', function() { }); it('should callback function, passed as options parameter', function(done) { - var options = function(err, schemas) { + const options = function(err, schemas) { if (err) return done(err); schemas.should.be.eql(modelProperties); @@ -440,8 +440,8 @@ describe('discoverModelProperties', function() { }); describe('discoverPrimaryKeys', function() { - var ds; - var modelProperties, primaryKeys; + let ds; + let modelProperties, primaryKeys; before(function() { ds = new DataSource({connector: 'memory'}); @@ -478,7 +478,7 @@ describe('discoverPrimaryKeys', function() { }); it('should callback function, passed as options parameter', function(done) { - var options = function(err, modelPrimaryKeys) { + const options = function(err, modelPrimaryKeys) { if (err) return done(err); modelPrimaryKeys.should.be.eql(primaryKeys); @@ -500,8 +500,8 @@ describe('discoverPrimaryKeys', function() { }); describe('discoverForeignKeys', function() { - var ds; - var modelProperties, foreignKeys; + let ds; + let modelProperties, foreignKeys; before(function() { ds = new DataSource({connector: 'memory'}); @@ -534,7 +534,7 @@ describe('discoverForeignKeys', function() { }); it('should callback function, passed as options parameter', function(done) { - var options = function(err, modelForeignKeys) { + const options = function(err, modelForeignKeys) { if (err) return done(err); modelForeignKeys.should.be.eql(foreignKeys); @@ -557,8 +557,8 @@ describe('discoverForeignKeys', function() { }); describe('discoverExportedForeignKeys', function() { - var ds; - var modelProperties, exportedForeignKeys; + let ds; + let modelProperties, exportedForeignKeys; before(function() { ds = new DataSource({connector: 'memory'}); @@ -591,7 +591,7 @@ describe('discoverExportedForeignKeys', function() { }); it('should callback function, passed as options parameter', function(done) { - var options = function(err, modelForeignKeys) { + const options = function(err, modelForeignKeys) { if (err) return done(err); modelForeignKeys.should.be.eql(exportedForeignKeys); @@ -615,9 +615,9 @@ describe('discoverExportedForeignKeys', function() { }); describe('Mock connector', function() { - var mockConnectors = require('./mock-connectors'); + const mockConnectors = require('./mock-connectors'); describe('customFieldSettings', function() { - var ds = new DataSource(mockConnectors.customFieldSettings); + const ds = new DataSource(mockConnectors.customFieldSettings); it('should be present in discoverSchemas', function(done) { ds.discoverSchemas('person', function(err, schemas) { @@ -632,7 +632,7 @@ describe('Mock connector', function() { }); describe('Default memory connector', function() { - var ds, nonExistantError = 'Table \'NONEXISTENT\' does not exist.'; + let ds, nonExistantError = 'Table \'NONEXISTENT\' does not exist.'; before(function() { ds = new DataSource({connector: 'memory'}); diff --git a/test/exclude-base-props.test.js b/test/exclude-base-props.test.js index 202130a4..6114471c 100644 --- a/test/exclude-base-props.test.js +++ b/test/exclude-base-props.test.js @@ -5,19 +5,19 @@ // This test written in mocha+should.js 'use strict'; -var should = require('./init.js'); -var assert = require('assert'); +const should = require('./init.js'); +const assert = require('assert'); -var jdb = require('../'); -var ModelBuilder = jdb.ModelBuilder; +const jdb = require('../'); +const ModelBuilder = jdb.ModelBuilder; describe('exclude properties ', function() { it('from base model', function(done) { - var ds = new ModelBuilder(); + const ds = new ModelBuilder(); // create a base model User which has name and password properties. id property gets // internally created for the User Model - var User = ds.define('User', {name: String, password: String}); - var properties = User.definition.properties; + const User = ds.define('User', {name: String, password: String}); + let properties = User.definition.properties; // User should have id, name & password properties assert(('id' in properties) && ('password' in properties) && ('name' in properties), 'User should have id, name & password properties'); @@ -26,7 +26,7 @@ describe('exclude properties ', function() { // With excludeBaseProperties, 'password' and 'id' gets excluded from base User model // With idInjection: false - id property of sub Model Customer gets excluded. At the end // User will have these 2 properties: name (inherited from User model) and vip (from customer Model). - var Customer = User.extend('Customer', {vip: {type: String}}, + const Customer = User.extend('Customer', {vip: {type: String}}, {idInjection: false, excludeBaseProperties: ['password', 'id']}); // Customer should have these properties: name(from UserModel) & vip properties = Customer.definition.properties; diff --git a/test/geo.test.js b/test/geo.test.js index a005c372..f206b2b3 100644 --- a/test/geo.test.js +++ b/test/geo.test.js @@ -10,36 +10,36 @@ require('should'); -var GeoPoint = require('../lib/geo').GeoPoint; -var nearFilter = require('../lib/geo').nearFilter; -var geoFilter = require('../lib/geo').filter; -var DELTA = 0.0000001; +const GeoPoint = require('../lib/geo').GeoPoint; +const nearFilter = require('../lib/geo').nearFilter; +const geoFilter = require('../lib/geo').filter; +const DELTA = 0.0000001; describe('GeoPoint', function() { describe('constructor', function() { it('should support a valid array', function() { - var point = new GeoPoint([-34, 150]); + const point = new GeoPoint([-34, 150]); point.lat.should.equal(-34); point.lng.should.equal(150); }); it('should support a valid object', function() { - var point = new GeoPoint({lat: -34, lng: 150}); + const point = new GeoPoint({lat: -34, lng: 150}); point.lat.should.equal(-34); point.lng.should.equal(150); }); it('should support valid string geo coordinates', function() { - var point = new GeoPoint('-34,150'); + const point = new GeoPoint('-34,150'); point.lat.should.equal(-34); point.lng.should.equal(150); }); it('should support coordinates as inline parameters', function() { - var point = new GeoPoint(-34, 150); + const point = new GeoPoint(-34, 150); point.lat.should.equal(-34); point.lng.should.equal(150); @@ -47,7 +47,7 @@ describe('GeoPoint', function() { it('should reject invalid parameters', function() { /* jshint -W024 */ - var fn = function() { + let fn = function() { new GeoPoint('150,-34'); }; fn.should.throw(); @@ -84,17 +84,17 @@ describe('GeoPoint', function() { describe('toString()', function() { it('should return a string in the form "lat,lng"', function() { - var point = new GeoPoint({lat: -34, lng: 150}); + const point = new GeoPoint({lat: -34, lng: 150}); point.toString().should.equal('-34,150'); }); }); describe('distance calculation between two points', function() { - var here = new GeoPoint({lat: 40.77492964101182, lng: -73.90950187151662}); - var there = new GeoPoint({lat: 40.7753227, lng: -73.909217}); + const here = new GeoPoint({lat: 40.77492964101182, lng: -73.90950187151662}); + const there = new GeoPoint({lat: 40.7753227, lng: -73.909217}); it('should return value in miles by default', function() { - var distance = GeoPoint.distanceBetween(here, there); + const distance = GeoPoint.distanceBetween(here, there); distance.should.be.a.Number; distance.should.be.approximately(0.03097916611592679, DELTA); }); @@ -109,7 +109,7 @@ describe('GeoPoint', function() { * - `degrees` */ - var distance = here.distanceTo(there, {type: 'radians'}); + let distance = here.distanceTo(there, {type: 'radians'}); distance.should.be.a.Number; distance.should.be.approximately(0.000007825491914348416, DELTA); @@ -137,7 +137,7 @@ describe('GeoPoint', function() { describe('nearFilter()', function() { it('should return a filter includes minDistance if where contains minDistance option', function() { - var where = { + const where = { location: { near: { lat: 40.77492964101182, @@ -146,7 +146,7 @@ describe('GeoPoint', function() { minDistance: 100, }, }; - var filter = nearFilter(where); + const filter = nearFilter(where); filter[0].key.should.equal('location'); filter[0].should.have.properties({ key: 'location', @@ -161,7 +161,7 @@ describe('GeoPoint', function() { describe('filter()', function() { it('should be able to filter geo points via minDistance', function() { - var points = [{ + const points = [{ location: { lat: 30.283552, lng: 120.126048, @@ -187,7 +187,7 @@ describe('GeoPoint', function() { lng: 121.483687, }, }]; - var filter = [{ + const filter = [{ key: 'location', near: { lat: 30.278562, @@ -196,7 +196,7 @@ describe('GeoPoint', function() { unit: 'meters', minDistance: 10000, }]; - var results = geoFilter(points, filter); + const results = geoFilter(points, filter); results.length.should.be.equal(3); }); }); diff --git a/test/helpers/bdd-if.js b/test/helpers/bdd-if.js index c7d07383..21e5c816 100644 --- a/test/helpers/bdd-if.js +++ b/test/helpers/bdd-if.js @@ -4,7 +4,7 @@ // License text available at https://opensource.org/licenses/MIT 'use strict'; -var fmt = require('util').format; +const fmt = require('util').format; exports.describeIf = function describeIf(cond, name, fn) { if (cond) diff --git a/test/helpers/context-test-helpers.js b/test/helpers/context-test-helpers.js index 54d9562c..6ad91b41 100644 --- a/test/helpers/context-test-helpers.js +++ b/test/helpers/context-test-helpers.js @@ -4,7 +4,7 @@ // License text available at https://opensource.org/licenses/MIT 'use strict'; -var traverse = require('traverse'); +const traverse = require('traverse'); exports.ContextRecorder = ContextRecorder; exports.deepCloneToObject = deepCloneToObject; @@ -18,7 +18,7 @@ function ContextRecorder(initialValue) { } ContextRecorder.prototype.recordAndNext = function(transformFm) { - var self = this; + const self = this; return function(context, next) { if (typeof transformFm === 'function') { transformFm(context); diff --git a/test/helpers/hook-monitor.js b/test/helpers/hook-monitor.js index ed94a46c..36a3a6a6 100644 --- a/test/helpers/hook-monitor.js +++ b/test/helpers/hook-monitor.js @@ -16,12 +16,12 @@ function HookMonitor(opts) { } HookMonitor.prototype.install = function(ObservedModel, hookNames) { - var monitor = this; + const monitor = this; this.names = []; ObservedModel._notify = ObservedModel.notifyObserversOf; ObservedModel.notifyObserversOf = function(operation, context, callback) { if (!Array.isArray(hookNames) || hookNames.indexOf(operation) !== -1) { - var item = monitor.options.includeModelName ? + const item = monitor.options.includeModelName ? ObservedModel.modelName + ':' + operation : operation; monitor.names.push(item); diff --git a/test/helpers/uid-generator.js b/test/helpers/uid-generator.js index 56615f97..6aa3d450 100644 --- a/test/helpers/uid-generator.js +++ b/test/helpers/uid-generator.js @@ -5,7 +5,7 @@ 'use strict'; -var lastId = 0; +let lastId = 0; exports.next = function() { lastId++; diff --git a/test/hooks.test.js b/test/hooks.test.js index 41efb0fd..65ffa9c4 100644 --- a/test/hooks.test.js +++ b/test/hooks.test.js @@ -7,9 +7,9 @@ // This test written in mocha+should.js /* global getSchema:false */ -var should = require('./init.js'); +const should = require('./init.js'); -var j = require('../'), +let j = require('../'), Schema = j.Schema, AbstractClass = j.AbstractClass, Hookable = j.Hookable, @@ -43,7 +43,7 @@ describe('hooks', function() { }); it('should be triggered on create', function(done) { - var user; + let user; User.afterInitialize = function() { if (this.name === 'Nickolay') { this.name += ' Rozental'; @@ -70,7 +70,7 @@ describe('hooks', function() { should.fail('This should not be called'); next(); }; - var u = new User; + const u = new User; }); it('should be triggered on new+save', function(done) { @@ -79,7 +79,7 @@ describe('hooks', function() { }); it('afterCreate should not be triggered on failed create', function(done) { - var old = User.dataSource.connector.create; + const old = User.dataSource.connector.create; User.dataSource.connector.create = function(modelName, id, cb) { cb(new Error('error')); }; @@ -99,7 +99,7 @@ describe('hooks', function() { next(new Error('fail in beforeCreate')); }; - var old = User.dataSource.connector.create; + const old = User.dataSource.connector.create; User.dataSource.connector.create = function(modelName, id, cb) { throw new Error('shouldn\'t be called'); }; @@ -259,7 +259,7 @@ describe('hooks', function() { should.fail('afterUpdate shouldn\'t be called'); }; User.create(function(err, user) { - var save = User.dataSource.connector.save; + const save = User.dataSource.connector.save; User.dataSource.connector.save = function(modelName, id, cb) { User.dataSource.connector.save = save; cb(new Error('Error')); @@ -276,7 +276,7 @@ describe('hooks', function() { afterEach(removeHooks('Destroy')); it('should be triggered on destroy', function(done) { - var hook = 'not called'; + let hook = 'not called'; User.beforeDestroy = function(next) { hook = 'called'; next(); @@ -291,7 +291,7 @@ describe('hooks', function() { }); it('should not trigger after-hook on failed destroy', function(done) { - var destroy = User.dataSource.connector.destroy; + const destroy = User.dataSource.connector.destroy; User.dataSource.connector.destroy = function(modelName, id, cb) { cb(new Error('error')); }; @@ -308,7 +308,7 @@ describe('hooks', function() { }); describe('lifecycle', function() { - var life = [], user; + let life = [], user; before(function(done) { User.beforeSave = function(d) { life.push('beforeSave'); @@ -379,7 +379,7 @@ describe('hooks', function() { }); it('should describe new+save sequence', function(done) { - var u = new User; + const u = new User; u.save(function() { life.should.eql([ 'afterInitialize', @@ -436,7 +436,7 @@ describe('hooks', function() { }); function addHooks(name, done) { - var called = false, random = String(Math.floor(Math.random() * 1000)); + let called = false, random = String(Math.floor(Math.random() * 1000)); User['before' + name] = function(next, data) { called = true; data.email = random; diff --git a/test/include.test.js b/test/include.test.js index e41e6f2c..aac7e472 100644 --- a/test/include.test.js +++ b/test/include.test.js @@ -6,19 +6,19 @@ 'use strict'; /* global getSchema:false, connectorCapabilities:false */ -var assert = require('assert'); -var async = require('async'); -var bdd = require('./helpers/bdd-if'); -var should = require('./init.js'); +const assert = require('assert'); +const async = require('async'); +const bdd = require('./helpers/bdd-if'); +const should = require('./init.js'); -var DataSource = require('../').DataSource; +const DataSource = require('../').DataSource; -var db, User, Profile, AccessToken, Post, Passport, City, Street, Building, Assembly, Part; +let db, User, Profile, AccessToken, Post, Passport, City, Street, Building, Assembly, Part; -var knownUsers = ['User A', 'User B', 'User C', 'User D', 'User E']; -var knownPassports = ['1', '2', '3', '4']; -var knownPosts = ['Post A', 'Post B', 'Post C', 'Post D', 'Post E']; -var knownProfiles = ['Profile A', 'Profile B', 'Profile Z']; +const knownUsers = ['User A', 'User B', 'User C', 'User D', 'User E']; +const knownPassports = ['1', '2', '3', '4']; +const knownPosts = ['Post A', 'Post B', 'Post C', 'Post D', 'Post E']; +const knownProfiles = ['Profile A', 'Profile B', 'Profile Z']; describe('include', function() { before(setup); @@ -34,7 +34,7 @@ describe('include', function() { // The __cachedRelations should be removed from json output p.toJSON().should.not.have.property('__cachedRelations'); - var owner = p.__cachedRelations.owner; + const owner = p.__cachedRelations.owner; if (!p.ownerId) { should.not.exist(owner); } else { @@ -49,7 +49,7 @@ describe('include', function() { it('does not return included item if FK is excluded', function(done) { Passport.find({include: 'owner', fields: 'number'}, function(err, passports) { if (err) return done(err); - var owner = passports[0].toJSON().owner; + const owner = passports[0].toJSON().owner; should.not.exist(owner); done(); }); @@ -117,13 +117,13 @@ describe('include', function() { user.save(function(err) { // save the returned user if (err) return finish(err); // should not store in db the posts - var dsName = User.dataSource.name; + const dsName = User.dataSource.name; if (dsName === 'memory') { JSON.parse(User.dataSource.adapter.cache.User[1]).should.not.have.property('posts'); finish(); } else if (dsName === 'mongodb') { // Check native mongodb connector // get hold of native mongodb collection - var dbCollection = User.dataSource.connector.collection(User.modelName); + const dbCollection = User.dataSource.connector.collection(User.modelName); dbCollection.findOne({_id: user.id}) .then(function(foundUser) { if (!foundUser) { @@ -153,7 +153,7 @@ describe('include', function() { // The __cachedRelations should be removed from json output p.toJSON().should.not.have.property('__cachedRelations'); - var user = p.__cachedRelations.owner; + const user = p.__cachedRelations.owner; if (!p.ownerId) { should.not.exist(user); } else { @@ -183,7 +183,7 @@ describe('include', function() { // The __cachedRelations should be removed from json output passport.toJSON().should.not.have.property('__cachedRelations'); - var user = passport.__cachedRelations.owner; + const user = passport.__cachedRelations.owner; should.exist(user); user.id.should.eql(passport.ownerId); user.__cachedRelations.should.have.property('posts'); @@ -199,7 +199,7 @@ describe('include', function() { should.not.exist(err); should.exist(passports); passports.length.should.be.ok; - var posts; + let posts; if (connectorCapabilities.adhocSort !== false) { posts = passports[0].owner().posts(); posts.should.have.length(3); @@ -222,7 +222,7 @@ describe('include', function() { passports.length.should.be.ok; passports.forEach(function(p) { p.__cachedRelations.should.have.property('owner'); - var user = p.__cachedRelations.owner; + const user = p.__cachedRelations.owner; if (!p.ownerId) { should.not.exist(user); } else { @@ -235,7 +235,7 @@ describe('include', function() { pp.userId.toString().should.eql(user.id.toString()); pp.should.have.property('author'); pp.__cachedRelations.should.have.property('author'); - var author = pp.__cachedRelations.author; + const author = pp.__cachedRelations.author; author.id.should.eql(user.id); }); } @@ -253,7 +253,7 @@ describe('include', function() { }, function(err, passports) { should.not.exist(err); should.exist(passports); - var passport, owner, posts; + let passport, owner, posts; if (connectorCapabilities.adhocSort !== false) { passports.length.should.equal(4); @@ -317,10 +317,10 @@ describe('include', function() { }, function(err, passports) { if (err) return done(err); passports.length.should.equal(2); - var posts1 = passports[0].toJSON().owner.posts; + const posts1 = passports[0].toJSON().owner.posts; posts1.length.should.equal(1); posts1[0].title.should.equal('Post C'); - var posts2 = passports[1].toJSON().owner.posts; + const posts2 = passports[1].toJSON().owner.posts; posts2.length.should.equal(1); posts2[0].title.should.equal('Post D'); @@ -344,9 +344,9 @@ describe('include', function() { }, function(err, passports) { if (err) return done(err); passports.length.should.equal(2); - var owner = passports[0].toJSON().owner; + let owner = passports[0].toJSON().owner; if (owner) { - var posts1 = owner.posts; + const posts1 = owner.posts; posts1.length.should.belowOrEqual(1); if (posts1.length === 1) { posts1[0].title.should.be.oneOf(knownPosts); @@ -354,7 +354,7 @@ describe('include', function() { } owner = passports[1].toJSON().owner; if (owner) { - var posts2 = owner.posts; + const posts2 = owner.posts; posts2.length.should.belowOrEqual(1); if (posts2.length === 1) { posts2[0].title.should.be.oneOf(knownPosts); @@ -394,10 +394,10 @@ describe('include', function() { if (err) return done(err); passports.length.should.equal(4); - var posts1 = passports[0].toJSON().owner.posts; + const posts1 = passports[0].toJSON().owner.posts; posts1.length.should.equal(3); posts1[0].title.should.equal('Post A'); - var posts2 = passports[1].toJSON().owner.posts; + const posts2 = passports[1].toJSON().owner.posts; posts2.length.should.equal(1); posts2[0].title.should.equal('Post D'); @@ -417,7 +417,7 @@ describe('include', function() { }, function(err, user) { if (err) return done(err); - var passport = user.passports()[0]; + const passport = user.passports()[0]; // eql instead of equal because mongo uses object id type passport.id.should.eql(createdPassports[0].id); passport.ownerId.should.eql(createdPassports[0].ownerId); @@ -448,9 +448,9 @@ describe('include', function() { user.name.should.equal('User A'); user.age.should.equal(21); user.id.should.eql(createdUsers[0].id); - var posts = user.posts(); + const posts = user.posts(); posts.length.should.equal(1); - var post = posts[0]; + const post = posts[0]; post.title.should.equal('Post A'); // eql instead of equal because mongo uses object id type post.userId.should.eql(createdPosts[0].userId); @@ -488,7 +488,7 @@ describe('include', function() { }, function(err, user) { if (err) return done(err); - var ids = user.posts().map(function(p) { return p.id; }); + const ids = user.posts().map(function(p) { return p.id; }); ids.should.eql([createdPosts[1].id, createdPosts[2].id]); done(); @@ -506,7 +506,7 @@ describe('include', function() { }, function(err, user) { if (err) return done(err); - var ids = user.posts().map(function(p) { return p.id; }); + const ids = user.posts().map(function(p) { return p.id; }); ids.should.eql([createdPosts[1].id, createdPosts[2].id]); done(); @@ -518,8 +518,8 @@ describe('include', function() { User.findOne({include: {relation: 'posts'}}, function(err, user) { if (err) return done(err); - var posts = user.posts(); - var ids = posts.map(function(p) { return p.id; }); + const posts = user.posts(); + const ids = posts.map(function(p) { return p.id; }); ids.should.eql([ createdPosts[0].id, createdPosts[1].id, @@ -586,7 +586,7 @@ describe('include', function() { user.age.should.equal(21); // eql instead of equal because mongo uses object id type user.id.should.eql(createdUsers[0].id); - var profile = user.profile(); + const profile = user.profile(); profile.profileName.should.equal('Profile A'); // eql instead of equal because mongo uses object id type profile.userId.should.eql(createdProfiles[0].userId); @@ -621,9 +621,9 @@ describe('include', function() { }); it('works when hasManyThrough is called', function(done) { - var Physician = db.define('Physician', {name: String}); - var Patient = db.define('Patient', {name: String}); - var Appointment = db.define('Appointment', { + const Physician = db.define('Physician', {name: String}); + const Patient = db.define('Patient', {name: String}); + const Appointment = db.define('Appointment', { date: { type: Date, default: function() { @@ -631,7 +631,7 @@ describe('include', function() { }, }, }); - var Address = db.define('Address', {name: String}); + const Address = db.define('Address', {name: String}); Physician.hasMany(Patient, {through: Appointment}); Patient.hasMany(Physician, {through: Appointment}); @@ -651,7 +651,7 @@ describe('include', function() { if (err) return done(err); patients.should.have.length(1); - var p = patients[0]; + const p = patients[0]; p.name.should.equal('a'); p.addressId.should.eql(patient.addressId); p.address().id.should.eql(address.id); @@ -673,7 +673,7 @@ describe('include', function() { profile.profileName.should.equal('Profile A'); profile.userId.should.eql(createdProfiles[0].userId); profile.id.should.eql(createdProfiles[0].id); - var user = profile.user(); + const user = profile.user(); user.name.should.equal('User A'); user.age.should.equal(21); user.id.should.eql(createdUsers[0].id); @@ -696,10 +696,10 @@ describe('include', function() { }, function(err, user) { if (err) return done(err); - var passport = user.passports()[0]; + const passport = user.passports()[0]; if (passport) { - var knownPassportIds = []; - var knownOwnerIds = []; + const knownPassportIds = []; + const knownOwnerIds = []; createdPassports.forEach(function(p) { if (p.id) knownPassportIds.push(p.id); if (p.ownerId) knownOwnerIds.push(p.ownerId.toString()); @@ -731,7 +731,7 @@ describe('include', function() { }, function(err, user) { if (err) return done(err); - var posts, post; + let posts, post; if (connectorCapabilities.adhocSort !== false) { user.name.should.equal('User A'); user.age.should.equal(21); @@ -745,7 +745,7 @@ describe('include', function() { post.id.should.eql(createdPosts[0].id); } else { user.name.should.be.oneOf(knownUsers); - var knownUserIds = []; + const knownUserIds = []; createdUsers.forEach(function(u) { knownUserIds.push(u.id.toString()); }); @@ -755,7 +755,7 @@ describe('include', function() { post = posts[0]; post.title.should.be.oneOf(knownPosts); post.userId.toString().should.be.oneOf(knownUserIds); - var knownPostIds = []; + const knownPostIds = []; createdPosts.forEach(function(p) { knownPostIds.push(p.id); }); @@ -794,9 +794,9 @@ describe('include', function() { }, function(err, user) { if (err) return done(err); - var ids = user.posts().map(function(p) { return p.id; }); + const ids = user.posts().map(function(p) { return p.id; }); if (ids.length > 0) { - var knownPosts = []; + const knownPosts = []; createdPosts.forEach(function(p) { if (p.id) knownPosts.push(p.id); }); @@ -820,9 +820,9 @@ describe('include', function() { }, function(err, user) { if (err) return done(err); - var ids = user.posts().map(function(p) { return p.id; }); + const ids = user.posts().map(function(p) { return p.id; }); if (ids.length > 0) { - var knownPosts = []; + const knownPosts = []; createdPosts.forEach(function(p) { if (p.id) knownPosts.push(p.id); }); @@ -840,10 +840,10 @@ describe('include', function() { User.findOne({include: {relation: 'posts'}}, function(err, user) { if (err) return done(err); - var posts = user.posts(); - var ids = posts.map(function(p) { return p.id; }); + const posts = user.posts(); + const ids = posts.map(function(p) { return p.id; }); if (ids.length > 0) { - var knownPosts = []; + const knownPosts = []; createdPosts.forEach(function(p) { if (p.id) knownPosts.push(p.id); }); @@ -910,8 +910,8 @@ describe('include', function() { User.findOne({include: {relation: 'profile'}}, function(err, user) { if (err) return done(err); - var knownUserIds = []; - var knownProfileIds = []; + const knownUserIds = []; + const knownProfileIds = []; createdUsers.forEach(function(u) { // FIXME user.id below might be string, so knownUserIds should match knownUserIds.push(u.id.toString()); @@ -924,7 +924,7 @@ describe('include', function() { user.name.should.be.oneOf(knownUsers); // eql instead of equal because mongo uses object id type user.id.toString().should.be.oneOf(knownUserIds); - var profile = user.profile(); + const profile = user.profile(); if (profile) { profile.profileName.should.be.oneOf(knownProfiles); // eql instead of equal because mongo uses object id type @@ -941,7 +941,7 @@ describe('include', function() { User.findOne({include: {relation: 'posts'}}, function(err, user) { if (err) return done(); - var knownUserIds = []; + const knownUserIds = []; createdUsers.forEach(function(u) { knownUserIds.push(u.id); }); @@ -955,9 +955,9 @@ describe('include', function() { }); it('works when hasManyThrough is called', function(done) { - var Physician = db.define('Physician', {name: String}); - var Patient = db.define('Patient', {name: String}); - var Appointment = db.define('Appointment', { + const Physician = db.define('Physician', {name: String}); + const Patient = db.define('Patient', {name: String}); + const Appointment = db.define('Appointment', { date: { type: Date, default: function() { @@ -965,7 +965,7 @@ describe('include', function() { }, }, }); - var Address = db.define('Address', {name: String}); + const Address = db.define('Address', {name: String}); Physician.hasMany(Patient, {through: Appointment}); Patient.hasMany(Physician, {through: Appointment}); @@ -984,7 +984,7 @@ describe('include', function() { function(err, patients) { if (err) return done(err); patients.should.have.length(1); - var p = patients[0]; + const p = patients[0]; p.name.should.equal('a'); p.addressId.should.eql(patient.addressId); p.address().id.should.eql(address.id); @@ -1004,8 +1004,8 @@ describe('include', function() { if (err) return done(err); if (!profile) return done(); // not every user has progile - var knownUserIds = []; - var knownProfileIds = []; + const knownUserIds = []; + const knownProfileIds = []; createdUsers.forEach(function(u) { knownUserIds.push(u.id.toString()); }); @@ -1016,7 +1016,7 @@ describe('include', function() { profile.profileName.should.be.oneOf(knownProfiles); if (profile.userId) profile.userId.toString().should.be.oneOf(knownUserIds); if (profile.id) profile.id.toString().should.be.oneOf(knownProfileIds); - var user = profile.user(); + const user = profile.user(); if (user) { user.name.should.be.oneOf(knownUsers); user.id.toString().should.be.oneOf(knownUserIds); @@ -1038,7 +1038,7 @@ describe('include', function() { should.exist(posts); posts.length.should.equal(5); - var author = posts[0].author(); + const author = posts[0].author(); author.name.should.equal('User A'); author.should.have.property('id'); author.should.have.property('age', undefined); @@ -1056,7 +1056,7 @@ describe('include', function() { should.exist(posts); posts.length.should.be.belowOrEqual(5); - var author = posts[0].author(); + const author = posts[0].author(); if (author) { author.name.should.be.oneOf('User A', 'User B', 'User C', 'User D', 'User E'); author.should.have.property('id'); @@ -1081,7 +1081,7 @@ describe('include', function() { users[0].name.should.equal('User A'); users[1].name.should.equal('User B'); - var posts = users[0].posts(); + let posts = users[0].posts(); posts.should.be.an.array; posts.should.have.length(3); @@ -1096,7 +1096,7 @@ describe('include', function() { } else { users.forEach(function(u) { u.name.should.be.oneOf(knownUsers); - var posts = u.posts(); + const posts = u.posts(); if (posts) { posts.should.be.an.array; posts.length.should.be.belowOrEqual(3); @@ -1121,7 +1121,7 @@ describe('include', function() { user.should.have.property('posts'); user.should.have.property('passports'); - var userObj = user.toJSON(); + const userObj = user.toJSON(); userObj.should.have.property('posts'); userObj.should.have.property('passports'); userObj.posts.should.be.an.instanceOf(Array); @@ -1161,7 +1161,7 @@ describe('include', function() { user.should.have.property('posts'); user.should.have.property('passports'); - var userObj = user.toJSON(); + const userObj = user.toJSON(); userObj.should.have.property('posts'); userObj.should.have.property('passports'); userObj.posts.should.be.an.instanceOf(Array); @@ -1192,7 +1192,7 @@ describe('include', function() { should.exist(users); users.length.should.be.ok; users.forEach(function(user) { - var userObj = user.toJSON(); + const userObj = user.toJSON(); userObj.should.not.have.property('accesstokens'); }); done(); @@ -1228,12 +1228,12 @@ describe('include', function() { should.not.exist(err); should.exist(users); users.length.should.be.ok; - var usersWithProfile = 0; + let usersWithProfile = 0; users.forEach(function(user) { // The relation should be promoted as the 'owner' property user.should.have.property('profile'); - var userObj = user.toJSON(); - var profile = user.profile(); + const userObj = user.toJSON(); + const profile = user.profile(); if (profile) { profile.should.be.an.instanceOf(Profile); usersWithProfile++; @@ -1261,7 +1261,7 @@ describe('include', function() { where: {partNumber: 'engine'}, }}}, function(err, assemblies) { assemblies.length.should.equal(1); - var parts = assemblies[0].parts(); + const parts = assemblies[0].parts(); parts.should.have.length(1); parts[0].partNumber.should.equal('engine'); done(); @@ -1273,7 +1273,7 @@ describe('include', function() { include: 'posts', }) .then(function(users) { - var posts = users[0].posts(); + const posts = users[0].posts(); if (connectorCapabilities.adhocSort !== false) { posts.should.have.length(3); } else { @@ -1287,7 +1287,7 @@ describe('include', function() { }); }) .then(function(user) { - var posts = user.posts(); + const posts = user.posts(); if (connectorCapabilities.adhocSort !== false) { posts.should.have.length(3); } else { @@ -1299,10 +1299,10 @@ describe('include', function() { }); describe('performance', function() { - var all; + let all; beforeEach(function() { this.called = 0; - var self = this; + const self = this; all = db.connector.all; db.connector.all = function(model, filter, options, cb) { self.called++; @@ -1313,9 +1313,9 @@ describe('include', function() { db.connector.all = all; }); - var nDBCalls = connectorCapabilities.supportTwoOrMoreInq !== false ? 2 : 4; + const nDBCalls = connectorCapabilities.supportTwoOrMoreInq !== false ? 2 : 4; it('including belongsTo should make only ' + nDBCalls + ' db calls', function(done) { - var self = this; + const self = this; Passport.find({include: 'owner'}, function(err, passports) { passports.length.should.be.ok; passports.forEach(function(p) { @@ -1324,7 +1324,7 @@ describe('include', function() { p.should.have.property('owner'); // The __cachedRelations should be removed from json output p.toJSON().should.not.have.property('__cachedRelations'); - var owner = p.__cachedRelations.owner; + const owner = p.__cachedRelations.owner; if (!p.ownerId) { should.not.exist(owner); } else { @@ -1338,7 +1338,7 @@ describe('include', function() { }); it('including hasManyThrough should make only 3 db calls', function(done) { - var self = this; + const self = this; Assembly.create([{name: 'sedan'}, {name: 'hatchback'}, {name: 'SUV'}], function(err, assemblies) { @@ -1359,10 +1359,10 @@ describe('include', function() { }); }, next); }, function(err) { - var autos = connectorCapabilities.supportTwoOrMoreInq !== false ? + const autos = connectorCapabilities.supportTwoOrMoreInq !== false ? ['sedan', 'hatchback', 'SUV'] : ['sedan']; - var resultLength = connectorCapabilities.supportTwoOrMoreInq !== false ? 3 : 1; - var dbCalls = connectorCapabilities.supportTwoOrMoreInq !== false ? 3 : 5; + const resultLength = connectorCapabilities.supportTwoOrMoreInq !== false ? 3 : 1; + const dbCalls = connectorCapabilities.supportTwoOrMoreInq !== false ? 3 : 5; self.called = 0; Assembly.find({ where: { @@ -1376,7 +1376,7 @@ describe('include', function() { should.exists(result); result.length.should.equal(resultLength); // Please note the order of assemblies is random - var assemblies = {}; + const assemblies = {}; result.forEach(function(r) { assemblies[r.name] = r; }); @@ -1391,9 +1391,9 @@ describe('include', function() { }); }); - var dbCalls = connectorCapabilities.supportTwoOrMoreInq !== false ? 3 : 11; + const dbCalls = connectorCapabilities.supportTwoOrMoreInq !== false ? 3 : 11; it('including hasMany should make only ' + dbCalls + ' db calls', function(done) { - var self = this; + const self = this; User.find({include: ['posts', 'passports']}, function(err, users) { should.not.exist(err); should.exist(users); @@ -1403,7 +1403,7 @@ describe('include', function() { user.should.have.property('posts'); user.should.have.property('passports'); - var userObj = user.toJSON(); + const userObj = user.toJSON(); userObj.should.have.property('posts'); userObj.should.have.property('passports'); userObj.posts.should.be.an.instanceOf(Array); @@ -1430,7 +1430,7 @@ describe('include', function() { it('should not make n+1 db calls in relation syntax', function(done) { - var self = this; + const self = this; User.find({include: [{relation: 'posts', scope: { where: {title: 'Post A'}, }}, 'passports']}, function(err, users) { @@ -1442,7 +1442,7 @@ describe('include', function() { user.should.have.property('posts'); user.should.have.property('passports'); - var userObj = user.toJSON(); + const userObj = user.toJSON(); userObj.should.have.property('posts'); userObj.should.have.property('passports'); userObj.posts.should.be.an.instanceOf(Array); @@ -1470,15 +1470,15 @@ describe('include', function() { }); it('should support disableInclude for hasAndBelongsToMany', function() { - var Patient = db.define('Patient', {name: String}); - var Doctor = db.define('Doctor', {name: String}); - var DoctorPatient = db.define('DoctorPatient'); + const Patient = db.define('Patient', {name: String}); + const Doctor = db.define('Doctor', {name: String}); + const DoctorPatient = db.define('DoctorPatient'); Doctor.hasAndBelongsToMany('patients', { model: 'Patient', options: {disableInclude: true}, }); - var doctor; + let doctor; return db.automigrate(['Patient', 'Doctor', 'DoctorPatient']).then(function() { return Doctor.create({name: 'Who'}); }).then(function(inst) { @@ -1624,12 +1624,12 @@ function setup(done) { } function clearAndCreate(model, data, callback) { - var createdItems = []; + const createdItems = []; model.destroyAll(function() { nextItem(null, null); }); - var itemIndex = 0; + let itemIndex = 0; function nextItem(err, lastItem) { if (lastItem !== null) { @@ -1645,7 +1645,7 @@ function clearAndCreate(model, data, callback) { } describe('Model instance with included relation .toJSON()', function() { - var db, ChallengerModel, GameParticipationModel, ResultModel; + let db, ChallengerModel, GameParticipationModel, ResultModel; before(function(done) { db = new DataSource({connector: 'memory'}); @@ -1720,12 +1720,12 @@ describe('Model instance with included relation .toJSON()', function() { } it('should recursively serialize objects', function(done) { - var filter = {include: {gameParticipations: 'results'}}; + const filter = {include: {gameParticipations: 'results'}}; ChallengerModel.find(filter, function(err, challengers) { - var levelOneInclusion = challengers[0].toJSON().gameParticipations[0]; + const levelOneInclusion = challengers[0].toJSON().gameParticipations[0]; assert(levelOneInclusion.__data === undefined, '.__data of a level 1 inclusion is undefined.'); - var levelTwoInclusion = challengers[0].toJSON().gameParticipations[0].results[0]; + const levelTwoInclusion = challengers[0].toJSON().gameParticipations[0].results[0]; assert(levelTwoInclusion.__data === undefined, '__data of a level 2 inclusion is undefined.'); done(); }); diff --git a/test/include_util.test.js b/test/include_util.test.js index 545af718..96aa036b 100644 --- a/test/include_util.test.js +++ b/test/include_util.test.js @@ -4,25 +4,25 @@ // License text available at https://opensource.org/licenses/MIT 'use strict'; -var assert = require('assert'); -var should = require('should'); +const assert = require('assert'); +const should = require('should'); -var includeUtils = require('../lib/include_utils'); +const includeUtils = require('../lib/include_utils'); describe('include_util', function() { describe('#buildOneToOneIdentityMapWithOrigKeys', function() { it('should return an object with keys', function() { - var objs = [ + const objs = [ {id: 11, letter: 'A'}, {id: 22, letter: 'B'}, ]; - var result = includeUtils.buildOneToOneIdentityMapWithOrigKeys(objs, 'id'); + const result = includeUtils.buildOneToOneIdentityMapWithOrigKeys(objs, 'id'); result.get(11).should.be.ok; result.get(22).should.be.ok; }); it('should report errors if id is missing', function() { - var objs = [ + const objs = [ {letter: 'A'}, {id: 22, letter: 'B'}, ]; @@ -33,14 +33,14 @@ describe('include_util', function() { }); it('should overwrite keys in case of collision', function() { - var objs = [ + const objs = [ {id: 11, letter: 'A'}, {id: 22, letter: 'B'}, {id: 33, letter: 'C'}, {id: 11, letter: 'HA!'}, ]; - var result = includeUtils.buildOneToOneIdentityMapWithOrigKeys(objs, 'id'); + const result = includeUtils.buildOneToOneIdentityMapWithOrigKeys(objs, 'id'); result.getKeys().should.containEql(11); result.getKeys().should.containEql(22); result.getKeys().should.containEql(33); @@ -49,28 +49,28 @@ describe('include_util', function() { }); it('should return an object with no additional keys', function() { - var objs = [ + const objs = [ {id: 11, letter: 'A'}, {id: 22, letter: 'B'}, ]; - var result = includeUtils.buildOneToOneIdentityMapWithOrigKeys(objs, 'id'); + const result = includeUtils.buildOneToOneIdentityMapWithOrigKeys(objs, 'id'); result.getKeys().should.eql([11, 22]); // no additional properties }); }); describe('#buildOneToManyIdentityMap', function() { it('should return an object with keys', function() { - var objs = [ + const objs = [ {id: 11, letter: 'A'}, {id: 22, letter: 'B'}, ]; - var result = includeUtils.buildOneToManyIdentityMapWithOrigKeys(objs, 'id'); + const result = includeUtils.buildOneToManyIdentityMapWithOrigKeys(objs, 'id'); result.exist(11).should.be.true; result.exist(22).should.be.true; }); it('should report errors if id is missing', function() { - var objs = [ + const objs = [ {letter: 'A'}, {id: 22, letter: 'B'}, ]; @@ -81,14 +81,14 @@ describe('include_util', function() { }); it('should collect keys in case of collision', function() { - var objs = [ + const objs = [ {'fk_id': 11, letter: 'A'}, {'fk_id': 22, letter: 'B'}, {'fk_id': 33, letter: 'C'}, {'fk_id': 11, letter: 'HA!'}, ]; - var result = includeUtils.buildOneToManyIdentityMapWithOrigKeys(objs, 'fk_id'); + const result = includeUtils.buildOneToManyIdentityMapWithOrigKeys(objs, 'fk_id'); result.get(11)[0]['letter'].should.equal('A'); result.get(11)[1]['letter'].should.equal('HA!'); result.get(33)[0]['letter'].should.equal('C'); @@ -98,7 +98,7 @@ describe('include_util', function() { describe('KVMap', function() { it('should allow to set and get value with key string', function() { - var map = new includeUtils.KVMap(); + const map = new includeUtils.KVMap(); map.set('name', 'Alex'); map.set('gender', true); map.set('age', 25); @@ -107,7 +107,7 @@ describe('KVMap', function() { map.get('age').should.be.equal(25); }); it('should allow to set and get value with arbitrary key type', function() { - var map = new includeUtils.KVMap(); + const map = new includeUtils.KVMap(); map.set('name', 'Alex'); map.set(true, 'male'); map.set(false, false); @@ -118,12 +118,12 @@ describe('KVMap', function() { map.get({isTrue: 'yes'}).should.be.equal(25); }); it('should not allow to get values with [] operator', function() { - var map = new includeUtils.KVMap(); + const map = new includeUtils.KVMap(); map.set('name', 'Alex'); (map['name'] === undefined).should.be.equal(true); }); it('should provide .exist() method for checking if key presented', function() { - var map = new includeUtils.KVMap(); + const map = new includeUtils.KVMap(); map.set('one', 1); map.set(2, 'two'); map.set(true, 'true'); @@ -133,24 +133,24 @@ describe('KVMap', function() { map.exist('two').should.be.false; }); it('should return array of original keys with .getKeys()', function() { - var map = new includeUtils.KVMap(); + const map = new includeUtils.KVMap(); map.set('one', 1); map.set(2, 'two'); map.set(true, 'true'); - var keys = map.getKeys(); + const keys = map.getKeys(); keys.should.containEql('one'); keys.should.containEql(2); keys.should.containEql(true); }); it('should allow to store and fetch arrays', function() { - var map = new includeUtils.KVMap(); + const map = new includeUtils.KVMap(); map.set(1, [1, 2, 3]); map.set(2, [2, 3, 4]); - var valueOne = map.get(1); + const valueOne = map.get(1); valueOne.should.be.eql([1, 2, 3]); valueOne.push(99); map.set(1, valueOne); - var valueOneUpdated = map.get(1); + const valueOneUpdated = map.get(1); valueOneUpdated.should.be.eql([1, 2, 3, 99]); }); }); diff --git a/test/init.js b/test/init.js index fd7f3220..d0fa70b0 100644 --- a/test/init.js +++ b/test/init.js @@ -18,8 +18,8 @@ module.exports = require('should'); } */ -var ModelBuilder = require('../').ModelBuilder; -var Schema = require('../').Schema; +const ModelBuilder = require('../').ModelBuilder; +const Schema = require('../').Schema; if (!('getSchema' in global)) { global.getSchema = function(connector, settings) { diff --git a/test/introspection.test.js b/test/introspection.test.js index d5c596ba..2d672f27 100644 --- a/test/introspection.test.js +++ b/test/introspection.test.js @@ -4,13 +4,13 @@ // License text available at https://opensource.org/licenses/MIT 'use strict'; -var assert = require('assert'); -var ModelBuilder = require('..').ModelBuilder; -var DataSource = require('../').DataSource; -var introspectType = require('../lib/introspection')(ModelBuilder); -var traverse = require('traverse'); +const assert = require('assert'); +const ModelBuilder = require('..').ModelBuilder; +const DataSource = require('../').DataSource; +const introspectType = require('../lib/introspection')(ModelBuilder); +const traverse = require('traverse'); -var json = { +const json = { name: 'Joe', age: 30, birthday: new Date(), @@ -40,7 +40,7 @@ describe('Introspection of model definitions from JSON', function() { }); it('should handle array types', function() { - var type = introspectType(['123']); + let type = introspectType(['123']); assert.deepEqual(type, ['string'], 'type should be ["string"]'); type = introspectType([1]); assert.deepEqual(type, ['number'], 'type should be ["number"]'); @@ -60,16 +60,16 @@ describe('Introspection of model definitions from JSON', function() { }); it('should return a schema for object', function() { - var json = {a: 'str', b: 0, c: true}; - var type = introspectType(json); + const json = {a: 'str', b: 0, c: true}; + const type = introspectType(json); assert.equal(type.a, 'string'); assert.equal(type.b, 'number'); assert.equal(type.c, 'boolean'); }); it('should handle nesting objects', function() { - var json = {a: 'str', b: 0, c: true, d: {x: 10, y: 5}}; - var type = introspectType(json); + const json = {a: 'str', b: 0, c: true, d: {x: 10, y: 5}}; + const type = introspectType(json); assert.equal(type.a, 'string'); assert.equal(type.b, 'number'); assert.equal(type.c, 'boolean'); @@ -78,8 +78,8 @@ describe('Introspection of model definitions from JSON', function() { }); it('should handle nesting arrays', function() { - var json = {a: 'str', b: 0, c: true, d: [1, 2]}; - var type = introspectType(json); + const json = {a: 'str', b: 0, c: true, d: [1, 2]}; + const type = introspectType(json); assert.equal(type.a, 'string'); assert.equal(type.b, 'number'); assert.equal(type.c, 'boolean'); @@ -87,15 +87,15 @@ describe('Introspection of model definitions from JSON', function() { }); it('should build a model from the introspected schema', function(done) { - var copy = traverse(json).clone(); + const copy = traverse(json).clone(); - var schema = introspectType(json); + const schema = introspectType(json); - var builder = new ModelBuilder(); - var Model = builder.define('MyModel', schema, {idInjection: false}); + const builder = new ModelBuilder(); + const Model = builder.define('MyModel', schema, {idInjection: false}); // FIXME: [rfeng] The constructor mutates the arguments - var obj = new Model(json); + let obj = new Model(json); obj = obj.toObject(); @@ -104,27 +104,27 @@ describe('Introspection of model definitions from JSON', function() { }); it('should build a model using buildModelFromInstance', function(done) { - var copy = traverse(json).clone(); + const copy = traverse(json).clone(); - var builder = new ModelBuilder(); - var Model = builder.buildModelFromInstance('MyModel', copy, {idInjection: false}); + const builder = new ModelBuilder(); + const Model = builder.buildModelFromInstance('MyModel', copy, {idInjection: false}); - var obj = new Model(json); + let obj = new Model(json); obj = obj.toObject(); assert.deepEqual(obj, copy); done(); }); it('should build a model using DataSource.buildModelFromInstance', function(done) { - var copy = traverse(json).clone(); + const copy = traverse(json).clone(); - var builder = new DataSource('memory'); - var Model = builder.buildModelFromInstance('MyModel', copy, + const builder = new DataSource('memory'); + const Model = builder.buildModelFromInstance('MyModel', copy, {idInjection: false}); assert.equal(Model.dataSource, builder); - var obj = new Model(json); + let obj = new Model(json); obj = obj.toObject(); assert.deepEqual(obj, copy); done(); diff --git a/test/json.test.js b/test/json.test.js index 6e8558ac..7914b7df 100644 --- a/test/json.test.js +++ b/test/json.test.js @@ -7,24 +7,24 @@ 'use strict'; /* global getSchema:false */ -var should = require('./init.js'); +const should = require('./init.js'); -var Schema = require('../').Schema; -var ModelBuilder = require('../').ModelBuilder; +const Schema = require('../').Schema; +const ModelBuilder = require('../').ModelBuilder; describe('JSON property', function() { - var dataSource, Model; + let dataSource, Model; it('should be defined', function() { dataSource = getSchema(); Model = dataSource.define('Model', {propertyName: ModelBuilder.JSON}); - var m = new Model; + const m = new Model; (new Boolean('propertyName' in m)).should.eql(true); should.not.exist(m.propertyName); }); it('should accept JSON in constructor and return object', function() { - var m = new Model({ + const m = new Model({ propertyName: '{"foo": "bar"}', }); m.propertyName.should.be.an.Object; @@ -32,14 +32,14 @@ describe('JSON property', function() { }); it('should accept object in setter and return object', function() { - var m = new Model; + const m = new Model; m.propertyName = {'foo': 'bar'}; m.propertyName.should.be.an.Object; m.propertyName.foo.should.equal('bar'); }); it('should accept string in setter and return string', function() { - var m = new Model; + const m = new Model; m.propertyName = '{"foo": "bar"}'; m.propertyName.should.be.a.String; m.propertyName.should.equal('{"foo": "bar"}'); diff --git a/test/kv-memory.js b/test/kv-memory.js index 1211ab71..3d72fded 100644 --- a/test/kv-memory.js +++ b/test/kv-memory.js @@ -4,11 +4,11 @@ // License text available at https://opensource.org/licenses/MIT 'use strict'; -var kvMemory = require('../lib/connectors/kv-memory'); -var DataSource = require('..').DataSource; +const kvMemory = require('../lib/connectors/kv-memory'); +const DataSource = require('..').DataSource; describe('Optimized KeyValue-Memory connector', function() { - var dataSourceFactory = function() { + const dataSourceFactory = function() { return new DataSource({connector: kvMemory}); }; @@ -16,8 +16,8 @@ describe('Optimized KeyValue-Memory connector', function() { }); describe('Unoptimized KeyValue-Memory connector', function() { - var dataSourceFactory = function() { - var ds = new DataSource({connector: kvMemory}); + const dataSourceFactory = function() { + const ds = new DataSource({connector: kvMemory}); // disable optimized methods ds.connector.deleteAll = false; diff --git a/test/kvao.suite.js b/test/kvao.suite.js index 62c50750..dc796154 100644 --- a/test/kvao.suite.js +++ b/test/kvao.suite.js @@ -5,10 +5,10 @@ 'use strict'; -var debug = require('debug')('test'); -var extend = require('util')._extend; -var fs = require('fs'); -var path = require('path'); +const debug = require('debug')('test'); +const extend = require('util')._extend; +const fs = require('fs'); +const path = require('path'); module.exports = function(dataSourceFactory, connectorCapabilities) { connectorCapabilities = extend({ @@ -18,16 +18,16 @@ module.exports = function(dataSourceFactory, connectorCapabilities) { }, connectorCapabilities); describe('KeyValue API', function loadAllTestFiles() { - var testRoot = path.resolve(__dirname, 'kvao'); - var testFiles = fs.readdirSync(testRoot); + const testRoot = path.resolve(__dirname, 'kvao'); + let testFiles = fs.readdirSync(testRoot); testFiles = testFiles.filter(function(it) { return !!require.extensions[path.extname(it).toLowerCase()] && /\.suite\.[^.]+$/.test(it); }); - for (var ix in testFiles) { - var name = testFiles[ix]; - var fullPath = path.resolve(testRoot, name); + for (const ix in testFiles) { + const name = testFiles[ix]; + const fullPath = path.resolve(testRoot, name); debug('Loading test suite %s (%s)', name, fullPath); require(fullPath)(dataSourceFactory, connectorCapabilities); } diff --git a/test/kvao/_helpers.js b/test/kvao/_helpers.js index 7d4980dd..4e7fa15f 100644 --- a/test/kvao/_helpers.js +++ b/test/kvao/_helpers.js @@ -23,7 +23,7 @@ function givenModel(dataSourceFactory, modelName, } function givenKeys(Model, keys, cb) { - var p = Promise.all( + let p = Promise.all( keys.map(function(k) { return Model.set(k, 'value-' + k); }) diff --git a/test/kvao/delete-all.suite.js b/test/kvao/delete-all.suite.js index 57b4a0ed..0ac8f9cb 100644 --- a/test/kvao/delete-all.suite.js +++ b/test/kvao/delete-all.suite.js @@ -5,7 +5,7 @@ const helpers = require('./_helpers'); const should = require('should'); module.exports = function(dataSourceFactory, connectorCapabilities) { - var supportsDeleteAll = 'deleteAll' in dataSourceFactory().connector; + const supportsDeleteAll = 'deleteAll' in dataSourceFactory().connector; bdd.describeIf(supportsDeleteAll, 'deleteAll', () => { let CacheItem; diff --git a/test/kvao/expire.suite.js b/test/kvao/expire.suite.js index 95e644e8..2ed0fa24 100644 --- a/test/kvao/expire.suite.js +++ b/test/kvao/expire.suite.js @@ -1,18 +1,18 @@ 'use strict'; -var bdd = require('../helpers/bdd-if'); -var should = require('should'); -var helpers = require('./_helpers'); +const bdd = require('../helpers/bdd-if'); +const should = require('should'); +const helpers = require('./_helpers'); module.exports = function(dataSourceFactory, connectorCapabilities) { // While we support millisecond precision, for the purpose of tests // it's better to use intervals at least 10ms long. - var ttlPrecision = connectorCapabilities.ttlPrecision || 10; + const ttlPrecision = connectorCapabilities.ttlPrecision || 10; - var canExpire = connectorCapabilities.canExpire !== false; + const canExpire = connectorCapabilities.canExpire !== false; bdd.describeIf(canExpire, 'expire', function() { - var CacheItem; + let CacheItem; beforeEach(setupCacheItem); it('sets key ttl - Callback API', function(done) { diff --git a/test/kvao/get-set.suite.js b/test/kvao/get-set.suite.js index 3e15f26e..5b268bd4 100644 --- a/test/kvao/get-set.suite.js +++ b/test/kvao/get-set.suite.js @@ -1,13 +1,13 @@ 'use strict'; -var should = require('should'); -var helpers = require('./_helpers'); +const should = require('should'); +const helpers = require('./_helpers'); module.exports = function(dataSourceFactory, connectorCapabilities) { - var TTL_PRECISION = connectorCapabilities.ttlPrecision; + const TTL_PRECISION = connectorCapabilities.ttlPrecision; describe('get/set', function() { - var CacheItem; + let CacheItem; beforeEach(setupCacheItem); it('works for string values - Callback API', function(done) { diff --git a/test/kvao/iterate-keys.suite.js b/test/kvao/iterate-keys.suite.js index 3dd81afd..84d3c552 100644 --- a/test/kvao/iterate-keys.suite.js +++ b/test/kvao/iterate-keys.suite.js @@ -1,21 +1,21 @@ 'use strict'; -var asyncIterators = require('async-iterators'); -var bdd = require('../helpers/bdd-if'); -var helpers = require('./_helpers'); -var should = require('should'); +const asyncIterators = require('async-iterators'); +const bdd = require('../helpers/bdd-if'); +const helpers = require('./_helpers'); +const should = require('should'); module.exports = function(dataSourceFactory, connectorCapabilities) { - var canIterateKeys = connectorCapabilities.canIterateKeys !== false; + const canIterateKeys = connectorCapabilities.canIterateKeys !== false; bdd.describeIf(canIterateKeys, 'iterateKeys', function() { - var CacheItem; + let CacheItem; beforeEach(setupCacheItem); it('returns AsyncIterator covering all keys', function() { return helpers.givenKeys(CacheItem, ['key1', 'key2']) .then(function() { - var it = CacheItem.iterateKeys(); + const it = CacheItem.iterateKeys(); should(it).have.property('next'); return toArray(it); }) @@ -26,7 +26,7 @@ module.exports = function(dataSourceFactory, connectorCapabilities) { }); it('returns AsyncIterator supporting Promises', function() { - var iterator; + let iterator; return helpers.givenKeys(CacheItem, ['key']) .then(function() { iterator = CacheItem.iterateKeys(); diff --git a/test/kvao/keys.suite.js b/test/kvao/keys.suite.js index 5dbf7541..9c10ecb3 100644 --- a/test/kvao/keys.suite.js +++ b/test/kvao/keys.suite.js @@ -1,11 +1,11 @@ 'use strict'; -var bdd = require('../helpers/bdd-if'); -var helpers = require('./_helpers'); -var should = require('should'); +const bdd = require('../helpers/bdd-if'); +const helpers = require('./_helpers'); +const should = require('should'); module.exports = function(dataSourceFactory, connectorCapabilities) { - var canIterateKeys = connectorCapabilities.canIterateKeys !== false; + const canIterateKeys = connectorCapabilities.canIterateKeys !== false; bdd.describeIf(canIterateKeys, 'keys', function() { let CacheItem; @@ -52,10 +52,10 @@ module.exports = function(dataSourceFactory, connectorCapabilities) { .then(keys => should(keys).eql(['key1', 'key2'])); }); - var largeKeySets = connectorCapabilities.canIterateLargeKeySets !== false; + const largeKeySets = connectorCapabilities.canIterateLargeKeySets !== false; bdd.itIf(largeKeySets, 'handles large key set', function() { - var expectedKeys = []; - for (var ix = 0; ix < 1000; ix++) + const expectedKeys = []; + for (let ix = 0; ix < 1000; ix++) expectedKeys.push('key-' + ix); expectedKeys.sort(); diff --git a/test/kvao/ttl.suite.js b/test/kvao/ttl.suite.js index c924a836..4610994d 100644 --- a/test/kvao/ttl.suite.js +++ b/test/kvao/ttl.suite.js @@ -1,22 +1,22 @@ 'use strict'; -var bdd = require('../helpers/bdd-if'); -var should = require('should'); -var helpers = require('./_helpers'); +const bdd = require('../helpers/bdd-if'); +const should = require('should'); +const helpers = require('./_helpers'); module.exports = function(dataSourceFactory, connectorCapabilities) { - var TTL_PRECISION = connectorCapabilities.ttlPrecision; + const TTL_PRECISION = connectorCapabilities.ttlPrecision; // Use ~1s for stores with precision of 1 ms, // about 3s for stores with precision of 1s. - var INITIAL_TTL = Math.max(TTL_PRECISION + 1000, TTL_PRECISION * 3); + const INITIAL_TTL = Math.max(TTL_PRECISION + 1000, TTL_PRECISION * 3); // A small delay to allow the backend to process the request, run any // TTL/expire checks, etc. Use 1ms for backends supporting sub-10ms // resolution to ensure the delay is not too short.. - var SMALL_DELAY = Math.max(1, Math.floor(TTL_PRECISION / 10)); + const SMALL_DELAY = Math.max(1, Math.floor(TTL_PRECISION / 10)); - var canQueryTtl = connectorCapabilities.canQueryTtl !== false; + const canQueryTtl = connectorCapabilities.canQueryTtl !== false; bdd.describeIf(canQueryTtl, 'ttl', function() { let CacheItem; diff --git a/test/list.test.js b/test/list.test.js index c8e4b5db..cdc608a3 100644 --- a/test/list.test.js +++ b/test/list.test.js @@ -5,8 +5,8 @@ 'use strict'; -var should = require('./init.js'); -var List = require('../lib/list'); +const should = require('./init.js'); +const List = require('../lib/list'); /** * Phone as a class @@ -40,31 +40,31 @@ function PhoneCtor(label, num) { describe('list of items typed by a class', function() { it('allows itemType to be a class', function() { - var phones = givenPhones(); + const phones = givenPhones(); - var list = new List(phones, Phone); + const list = new List(phones, Phone); list.should.be.an.instanceOf(Array); list.toJSON().should.be.eql(phones); }); it('converts items of plain json to the itemType', function() { - var phones = givenPhonesAsJSON(); + const phones = givenPhonesAsJSON(); - var list = new List(phones, Phone); + const list = new List(phones, Phone); list[0].should.be.an.instanceOf(Phone); }); it('converts stringified items to the itemType', function() { - var phones = givenPhonesAsJSON(); + const phones = givenPhonesAsJSON(); - var list = new List(JSON.stringify(phones), Phone); + const list = new List(JSON.stringify(phones), Phone); list[0].should.be.an.instanceOf(Phone); }); it('converts items of plain json to the itemType with push', function() { - var phones = givenPhonesAsJSON(); + const phones = givenPhonesAsJSON(); - var list = new List([], Phone); + const list = new List([], Phone); list.push(phones[0]); list[0].should.be.an.instanceOf(Phone); }); @@ -72,31 +72,31 @@ describe('list of items typed by a class', function() { describe('list of items typed by a ctor', function() { it('allows itemType to be a ctor', function() { - var phones = givenPhonesWithCtor(); + const phones = givenPhonesWithCtor(); - var list = new List(phones, PhoneCtor); + const list = new List(phones, PhoneCtor); list.should.be.an.instanceOf(Array); list.toJSON().should.be.eql(phones); }); it('converts items of plain json to the itemType', function() { - var phones = givenPhonesAsJSON(); + const phones = givenPhonesAsJSON(); - var list = new List(phones, PhoneCtor); + const list = new List(phones, PhoneCtor); list[0].should.be.an.instanceOf(PhoneCtor); }); it('converts stringified items to the itemType', function() { - var phones = givenPhonesAsJSON(); + const phones = givenPhonesAsJSON(); - var list = new List(JSON.stringify(phones), PhoneCtor); + const list = new List(JSON.stringify(phones), PhoneCtor); list[0].should.be.an.instanceOf(PhoneCtor); }); it('converts items of plain json to the itemType with push', function() { - var phones = givenPhonesAsJSON(); + const phones = givenPhonesAsJSON(); - var list = new List([], PhoneCtor); + const list = new List([], PhoneCtor); list.push(phones[0]); list[0].should.be.an.instanceOf(PhoneCtor); }); diff --git a/test/loopback-data.test.js b/test/loopback-data.test.js index 8d175b88..e37a1f39 100644 --- a/test/loopback-data.test.js +++ b/test/loopback-data.test.js @@ -5,9 +5,9 @@ // This test written in mocha+should.js 'use strict'; -var should = require('./init.js'); +const should = require('./init.js'); -var loopbackData = require('../'); +const loopbackData = require('../'); describe('loopback-datasource-juggler', function() { it('should expose version', function() { diff --git a/test/loopback-dl.test.js b/test/loopback-dl.test.js index 00694d55..669a7dce 100644 --- a/test/loopback-dl.test.js +++ b/test/loopback-dl.test.js @@ -5,19 +5,19 @@ // This test written in mocha+should.js 'use strict'; -var should = require('./init.js'); -var assert = require('assert'); -var async = require('async'); +const should = require('./init.js'); +const assert = require('assert'); +const async = require('async'); -var jdb = require('../'); -var ModelBuilder = jdb.ModelBuilder; -var DataSource = jdb.DataSource; +const jdb = require('../'); +const ModelBuilder = jdb.ModelBuilder; +const DataSource = jdb.DataSource; describe('ModelBuilder', function() { it('supports plain models', function(done) { - var modelBuilder = new ModelBuilder(); + const modelBuilder = new ModelBuilder(); - var User = modelBuilder.define('User', { + const User = modelBuilder.define('User', { name: String, bio: ModelBuilder.Text, approved: Boolean, @@ -33,7 +33,7 @@ describe('ModelBuilder', function() { modelBuilder.models.should.be.type('object').and.have.property('User').exactly(User); modelBuilder.definitions.should.be.type('object').and.have.property('User'); - var user = new User({name: 'Joe', age: 20, xyz: false}); + const user = new User({name: 'Joe', age: 20, xyz: false}); User.modelName.should.equal('User'); user.should.be.type('object').and.have.property('name', 'Joe'); @@ -45,11 +45,11 @@ describe('ModelBuilder', function() { }); it('ignores unknown properties in strict mode', function(done) { - var modelBuilder = new ModelBuilder(); + const modelBuilder = new ModelBuilder(); - var User = modelBuilder.define('User', {name: String, bio: String}, {strict: true}); + const User = modelBuilder.define('User', {name: String, bio: String}, {strict: true}); - var user = new User({name: 'Joe', age: 20}); + const user = new User({name: 'Joe', age: 20}); User.modelName.should.equal('User'); user.should.be.type('object'); @@ -62,11 +62,11 @@ describe('ModelBuilder', function() { }); it('ignores non-predefined properties in strict mode', function(done) { - var modelBuilder = new ModelBuilder(); + const modelBuilder = new ModelBuilder(); - var User = modelBuilder.define('User', {name: String, bio: String}, {strict: true}); + const User = modelBuilder.define('User', {name: String, bio: String}, {strict: true}); - var user = new User({name: 'Joe'}); + const user = new User({name: 'Joe'}); user.age = 10; user.bio = 'me'; @@ -86,12 +86,12 @@ describe('ModelBuilder', function() { }); it('throws an error when unknown properties are used if strict=throw', function(done) { - var modelBuilder = new ModelBuilder(); + const modelBuilder = new ModelBuilder(); - var User = modelBuilder.define('User', {name: String, bio: String}, {strict: 'throw'}); + const User = modelBuilder.define('User', {name: String, bio: String}, {strict: 'throw'}); try { - var user = new User({name: 'Joe', age: 20}); + const user = new User({name: 'Joe', age: 20}); assert(false, 'The code should have thrown an error'); } catch (e) { assert(true, 'The code is expected to throw an error'); @@ -100,11 +100,11 @@ describe('ModelBuilder', function() { }); it('supports open models', function(done) { - var modelBuilder = new ModelBuilder(); + const modelBuilder = new ModelBuilder(); - var User = modelBuilder.define('User', {}, {strict: false}); + const User = modelBuilder.define('User', {}, {strict: false}); - var user = new User({name: 'Joe', age: 20}); + const user = new User({name: 'Joe', age: 20}); User.modelName.should.equal('User'); user.should.be.type('object').and.have.property('name', 'Joe'); @@ -115,11 +115,11 @@ describe('ModelBuilder', function() { }); it('accepts non-predefined properties in non-strict mode', function(done) { - var modelBuilder = new ModelBuilder(); + const modelBuilder = new ModelBuilder(); - var User = modelBuilder.define('User', {name: String, bio: String}, {strict: false}); + const User = modelBuilder.define('User', {name: String, bio: String}, {strict: false}); - var user = new User({name: 'Joe'}); + const user = new User({name: 'Joe'}); user.age = 10; user.bio = 'me'; @@ -140,11 +140,11 @@ describe('ModelBuilder', function() { }); it('uses non-strict mode by default', function(done) { - var modelBuilder = new ModelBuilder(); + const modelBuilder = new ModelBuilder(); - var User = modelBuilder.define('User', {}); + const User = modelBuilder.define('User', {}); - var user = new User({name: 'Joe', age: 20}); + const user = new User({name: 'Joe', age: 20}); User.modelName.should.equal('User'); user.should.be.type('object').and.have.property('name', 'Joe'); @@ -155,10 +155,10 @@ describe('ModelBuilder', function() { }); it('supports nested model definitions', function(done) { - var modelBuilder = new ModelBuilder(); + const modelBuilder = new ModelBuilder(); // simplier way to describe model - var User = modelBuilder.define('User', { + const User = modelBuilder.define('User', { name: String, bio: ModelBuilder.Text, approved: Boolean, @@ -188,7 +188,7 @@ describe('ModelBuilder', function() { modelBuilder.models.should.be.type('object').and.have.property('User', User); modelBuilder.definitions.should.be.type('object').and.have.property('User'); - var user = new User({ + let user = new User({ name: 'Joe', age: 20, address: {street: '123 Main St', 'city': 'San Jose', state: 'CA'}, emails: [ @@ -217,11 +217,11 @@ describe('ModelBuilder', function() { }); it('allows models to be referenced by name before they are defined', function(done) { - var modelBuilder = new ModelBuilder(); + const modelBuilder = new ModelBuilder(); - var User = modelBuilder.define('User', {name: String, address: 'Address'}); + const User = modelBuilder.define('User', {name: String, address: 'Address'}); - var user; + let user; try { user = new User({name: 'Joe', address: {street: '123 Main St', 'city': 'San Jose', state: 'CA'}}); assert(false, 'An exception should have been thrown'); @@ -229,7 +229,7 @@ describe('ModelBuilder', function() { // Ignore } - var Address = modelBuilder.define('Address', { + const Address = modelBuilder.define('Address', { street: String, city: String, state: String, @@ -249,28 +249,28 @@ describe('ModelBuilder', function() { }); it('defines an id property for composite ids', function() { - var modelBuilder = new ModelBuilder(); - var Follow = modelBuilder.define('Follow', { + const modelBuilder = new ModelBuilder(); + const Follow = modelBuilder.define('Follow', { followerId: {type: String, id: 1}, followeeId: {type: String, id: 2}, followAt: Date, }); - var follow = new Follow({followerId: 1, followeeId: 2}); + const follow = new Follow({followerId: 1, followeeId: 2}); follow.should.have.property('id'); assert.deepEqual(follow.id, {followerId: 1, followeeId: 2}); }); it('instantiates model from data with no constructor', function(done) { - var modelBuilder = new ModelBuilder(); + const modelBuilder = new ModelBuilder(); - var User = modelBuilder.define('User', {name: String, age: Number}); + const User = modelBuilder.define('User', {name: String, age: Number}); try { - var data = Object.create(null); + const data = Object.create(null); data.name = 'Joe'; data.age = 20; - var user = new User(data); + const user = new User(data); assert(true, 'The code is expected to pass'); } catch (e) { assert(false, 'The code should have not thrown an error'); @@ -279,21 +279,21 @@ describe('ModelBuilder', function() { }); it('instantiates model from data with non function constructor', function(done) { - var modelBuilder = new ModelBuilder(); + const modelBuilder = new ModelBuilder(); - var User = modelBuilder.define('User', {name: String, age: Number}); + const User = modelBuilder.define('User', {name: String, age: Number}); try { - var Person = function(name, age) { + const Person = function(name, age) { this.name = name; this.age = age; }; Person.prototype.constructor = 'constructor'; - var data = new Person('Joe', 20); + const data = new Person('Joe', 20); - var user = new User(data); + const user = new User(data); assert(false, 'The code should have thrown an error'); } catch (e) { e.message.should.equal('Property name "constructor" is not allowed in User data'); @@ -304,7 +304,7 @@ describe('ModelBuilder', function() { }); describe('DataSource ping', function() { - var ds = new DataSource('memory'); + const ds = new DataSource('memory'); ds.settings.connectionTimeout = 50; // ms ds.connector.connect = function(cb) { // Mock up the long delay @@ -324,7 +324,7 @@ describe('DataSource ping', function() { it('cancels invocation after timeout', function(done) { ds.connected = false; // Force connect - var Post = ds.define('Post', { + const Post = ds.define('Post', { title: {type: String, length: 255}, }); Post.create(function(err) { @@ -337,10 +337,10 @@ describe('DataSource ping', function() { describe('DataSource define model', function() { it('supports plain model definitions', function() { - var ds = new DataSource('memory'); + const ds = new DataSource('memory'); // define models - var Post = ds.define('Post', { + const Post = ds.define('Post', { title: {type: String, length: 255}, content: {type: ModelBuilder.Text}, date: {type: Date, default: function() { @@ -351,7 +351,7 @@ describe('DataSource define model', function() { }); // simpler way to describe model - var User = ds.define('User', { + const User = ds.define('User', { name: String, bio: ModelBuilder.Text, approved: Boolean, @@ -359,7 +359,7 @@ describe('DataSource define model', function() { age: Number, }); - var Group = ds.define('Group', {group: String}); + const Group = ds.define('Group', {group: String}); User.mixin(Group); // define any custom method @@ -367,7 +367,7 @@ describe('DataSource define model', function() { return this.name + ', ' + this.age; }; - var user = new User({name: 'Joe', group: 'G1'}); + const user = new User({name: 'Joe', group: 'G1'}); assert.equal(user.name, 'Joe'); assert.equal(user.group, 'G1'); @@ -380,9 +380,9 @@ describe('DataSource define model', function() { User.hasAndBelongsToMany('groups'); - var user2 = new User({name: 'Smith'}); + const user2 = new User({name: 'Smith'}); user2.save(function(err) { - var post = user2.posts.build({title: 'Hello world'}); + const post = user2.posts.build({title: 'Hello world'}); post.save(function(err, data) { // console.log(err ? err : data); }); @@ -396,15 +396,15 @@ describe('DataSource define model', function() { if (err) { return; } - var post = data.posts.build({title: 'My Post'}); + const post = data.posts.build({title: 'My Post'}); }); User.create({name: 'Ray'}, function(err, data) { // console.log(data); }); - var Article = ds.define('Article', {title: String}); - var Tag = ds.define('Tag', {name: String}); + const Article = ds.define('Article', {title: String}); + const Tag = ds.define('Tag', {name: String}); Article.hasAndBelongsToMany('tags'); Article.create(function(e, article) { @@ -418,9 +418,9 @@ describe('DataSource define model', function() { }); // should be able to attach a data source to an existing model - var modelBuilder = new ModelBuilder(); + const modelBuilder = new ModelBuilder(); - var Color = modelBuilder.define('Color', { + const Color = modelBuilder.define('Color', { name: String, }); @@ -440,16 +440,16 @@ describe('DataSource define model', function() { }); it('emits events during attach', function() { - var ds = new DataSource('memory'); - var modelBuilder = new ModelBuilder(); + const ds = new DataSource('memory'); + const modelBuilder = new ModelBuilder(); - var User = modelBuilder.define('User', { + const User = modelBuilder.define('User', { name: String, }); - var seq = 0; - var dataAccessConfigured = -1; - var dataSourceAttached = -1; + let seq = 0; + let dataAccessConfigured = -1; + let dataSourceAttached = -1; User.on('dataAccessConfigured', function(model) { dataAccessConfigured = seq++; @@ -468,9 +468,9 @@ describe('DataSource define model', function() { }); it('ignores unknown properties in strict mode', function(done) { - var ds = new DataSource('memory'); + const ds = new DataSource('memory'); - var User = ds.define('User', {name: String, bio: String}, {strict: true}); + const User = ds.define('User', {name: String, bio: String}, {strict: true}); User.create({name: 'Joe', age: 20}, function(err, user) { User.modelName.should.equal('User'); @@ -485,12 +485,12 @@ describe('DataSource define model', function() { }); it('throws an error when unknown properties are used if strict=throw', function(done) { - var ds = new DataSource('memory'); + const ds = new DataSource('memory'); - var User = ds.define('User', {name: String, bio: String}, {strict: 'throw'}); + const User = ds.define('User', {name: String, bio: String}, {strict: 'throw'}); try { - var user = new User({name: 'Joe', age: 20}); + const user = new User({name: 'Joe', age: 20}); assert(false, 'The code should have thrown an error'); } catch (e) { assert(true, 'The code is expected to throw an error'); @@ -500,19 +500,19 @@ describe('DataSource define model', function() { describe('strict mode "validate"', function() { it('reports validation errors for unknown properties', function() { - var ds = new DataSource('memory'); - var User = ds.define('User', {name: String}, {strict: 'validate'}); - var user = new User({name: 'Joe', age: 20}); + const ds = new DataSource('memory'); + const User = ds.define('User', {name: String}, {strict: 'validate'}); + const user = new User({name: 'Joe', age: 20}); user.isValid().should.be.false; - var codes = user.errors && user.errors.codes || {}; + const codes = user.errors && user.errors.codes || {}; codes.should.have.property('age').eql(['unknown-property']); }); }); it('supports open model definitions', function(done) { - var ds = new DataSource('memory'); + const ds = new DataSource('memory'); - var User = ds.define('User', {}, {strict: false}); + const User = ds.define('User', {}, {strict: false}); User.modelName.should.equal('User'); User.create({name: 'Joe', age: 20}, function(err, user) { @@ -532,9 +532,9 @@ describe('DataSource define model', function() { }); it('uses non-strict mode by default', function(done) { - var ds = new DataSource('memory'); + const ds = new DataSource('memory'); - var User = ds.define('User', {}); + const User = ds.define('User', {}); User.create({name: 'Joe', age: 20}, function(err, user) { User.modelName.should.equal('User'); @@ -547,12 +547,12 @@ describe('DataSource define model', function() { }); it('uses strict mode by default for relational DBs', function(done) { - var ds = new DataSource('memory'); + const ds = new DataSource('memory'); ds.connector.relational = true; // HACK - var User = ds.define('User', {name: String, bio: String}, {strict: true}); + const User = ds.define('User', {name: String, bio: String}, {strict: true}); - var user = new User({name: 'Joe', age: 20}); + const user = new User({name: 'Joe', age: 20}); User.modelName.should.equal('User'); user.should.be.type('object'); @@ -565,13 +565,13 @@ describe('DataSource define model', function() { }); it('throws an error with unknown properties in non-strict mode for relational DBs', function(done) { - var ds = new DataSource('memory'); + const ds = new DataSource('memory'); ds.connector.relational = true; // HACK - var User = ds.define('User', {name: String, bio: String}, {strict: 'throw'}); + const User = ds.define('User', {name: String, bio: String}, {strict: 'throw'}); try { - var user = new User({name: 'Joe', age: 20}); + const user = new User({name: 'Joe', age: 20}); assert(false, 'The code should have thrown an error'); } catch (e) { assert(true, 'The code is expected to throw an error'); @@ -580,8 +580,8 @@ describe('DataSource define model', function() { }); it('changes the property value for save in non-strict mode', function(done) { - var ds = new DataSource('memory');// define models - var Post = ds.define('Post'); + const ds = new DataSource('memory');// define models + const Post = ds.define('Post'); Post.create({price: 900}, function(err, post) { assert.equal(post.price, 900); @@ -594,11 +594,11 @@ describe('DataSource define model', function() { }); it('supports instance level strict mode', function() { - var ds = new DataSource('memory'); + const ds = new DataSource('memory'); - var User = ds.define('User', {name: String, bio: String}, {strict: true}); + const User = ds.define('User', {name: String, bio: String}, {strict: true}); - var user = new User({name: 'Joe', age: 20}, {strict: false}); + const user = new User({name: 'Joe', age: 20}, {strict: false}); user.should.have.property('__strict', false); user.should.be.type('object'); @@ -614,8 +614,8 @@ describe('DataSource define model', function() { }); it('updates instances with unknown properties in non-strict mode', function(done) { - var ds = new DataSource('memory');// define models - var Post; + const ds = new DataSource('memory');// define models + let Post; Post = ds.define('Post', { title: {type: String, length: 255, index: true}, content: {type: String}, @@ -640,9 +640,9 @@ describe('DataSource define model', function() { }); it('injects id by default', function(done) { - var ds = new ModelBuilder(); + const ds = new ModelBuilder(); - var User = ds.define('User', {}); + const User = ds.define('User', {}); assert.deepEqual(User.definition.properties.id, {type: Number, id: 1, generated: true, updateOnly: true}); @@ -650,21 +650,21 @@ describe('DataSource define model', function() { }); it('disables idInjection if the value is false', function(done) { - var ds = new ModelBuilder(); + const ds = new ModelBuilder(); - var User1 = ds.define('User', {}, {idInjection: false}); + const User1 = ds.define('User', {}, {idInjection: false}); assert(!User1.definition.properties.id); done(); }); it('updates generated id type by the connector', function(done) { - var builder = new ModelBuilder(); + const builder = new ModelBuilder(); - var User = builder.define('User', {id: {type: String, generated: true, id: true}}); + const User = builder.define('User', {id: {type: String, generated: true, id: true}}); assert.deepEqual(User.definition.properties.id, {type: String, id: 1, generated: true, updateOnly: true}); - var ds = new DataSource('memory');// define models + const ds = new DataSource('memory');// define models User.attachTo(ds); assert.deepEqual(User.definition.properties.id, @@ -674,18 +674,18 @@ describe('DataSource define model', function() { }); it('allows an explicit remoting path', function() { - var ds = new DataSource('memory'); + const ds = new DataSource('memory'); - var User = ds.define('User', {name: String, bio: String}, { + const User = ds.define('User', {name: String, bio: String}, { http: {path: 'accounts'}, }); User.http.path.should.equal('/accounts'); }); it('allows an explicit remoting path with leading /', function() { - var ds = new DataSource('memory'); + const ds = new DataSource('memory'); - var User = ds.define('User', {name: String, bio: String}, { + const User = ds.define('User', {name: String, bio: String}, { http: {path: '/accounts'}, }); User.http.path.should.equal('/accounts'); @@ -694,16 +694,16 @@ describe('DataSource define model', function() { describe('Model loaded with a base', function() { it('has a base class according to the base option', function() { - var ds = new ModelBuilder(); + const ds = new ModelBuilder(); - var User = ds.define('User', {name: String}); + const User = ds.define('User', {name: String}); User.staticMethod = function staticMethod() { }; User.prototype.instanceMethod = function instanceMethod() { }; - var Customer = ds.define('Customer', {vip: Boolean}, {base: 'User'}); + const Customer = ds.define('Customer', {vip: Boolean}, {base: 'User'}); assert(Customer.prototype instanceof User); assert(Customer.staticMethod === User.staticMethod); @@ -712,30 +712,30 @@ describe('Model loaded with a base', function() { assert.equal(Customer.base, Customer.super_); try { - var Customer1 = ds.define('Customer1', {vip: Boolean}, {base: 'User1'}); + const Customer1 = ds.define('Customer1', {vip: Boolean}, {base: 'User1'}); } catch (e) { assert(e); } }); it('inherits properties from base model', function() { - var ds = new ModelBuilder(); + const ds = new ModelBuilder(); - var User = ds.define('User', {name: String}); + const User = ds.define('User', {name: String}); - var Customer = ds.define('Customer', {vip: Boolean}, {base: 'User'}); + const Customer = ds.define('Customer', {vip: Boolean}, {base: 'User'}); Customer.definition.properties.should.have.property('name'); Customer.definition.properties.name.should.have.property('type', String); }); it('inherits properties by clone from base model', function() { - var ds = new ModelBuilder(); + const ds = new ModelBuilder(); - var User = ds.define('User', {name: String}); + const User = ds.define('User', {name: String}); - var Customer1 = ds.define('Customer1', {vip: Boolean}, {base: 'User'}); - var Customer2 = ds.define('Customer2', {vip: Boolean}, {base: 'User'}); + const Customer1 = ds.define('Customer1', {vip: Boolean}, {base: 'User'}); + const Customer2 = ds.define('Customer2', {vip: Boolean}, {base: 'User'}); Customer1.definition.properties.should.have.property('name'); Customer2.definition.properties.should.have.property('name'); @@ -748,11 +748,11 @@ describe('Model loaded with a base', function() { }); it('can remove properties from base model', function() { - var ds = new ModelBuilder(); + const ds = new ModelBuilder(); - var User = ds.define('User', {username: String, email: String}); + const User = ds.define('User', {username: String, email: String}); - var Customer = ds.define('Customer', + const Customer = ds.define('Customer', {name: String, username: null, email: false}, {base: 'User'}); @@ -760,27 +760,27 @@ describe('Model loaded with a base', function() { // username/email are now shielded Customer.definition.properties.should.not.have.property('username'); Customer.definition.properties.should.not.have.property('email'); - var c = new Customer({name: 'John'}); + const c = new Customer({name: 'John'}); c.should.have.property('username', undefined); c.should.have.property('email', undefined); c.should.have.property('name', 'John'); - var u = new User({username: 'X', email: 'x@y.com'}); + const u = new User({username: 'X', email: 'x@y.com'}); u.should.not.have.property('name'); u.should.have.property('username', 'X'); u.should.have.property('email', 'x@y.com'); }); it('can configure base class via parent argument', function() { - var ds = new ModelBuilder(); + const ds = new ModelBuilder(); - var User = ds.define('User', {name: String}); + const User = ds.define('User', {name: String}); User.staticMethod = function staticMethod() { }; User.prototype.instanceMethod = function instanceMethod() { }; - var Customer = ds.define('Customer', {vip: Boolean}, {}, User); + const Customer = ds.define('Customer', {vip: Boolean}, {}, User); Customer.definition.properties.should.have.property('name'); Customer.definition.properties.name.should.have.property('type', String); @@ -794,9 +794,9 @@ describe('Model loaded with a base', function() { }); describe('Models attached to a dataSource', function() { - var Post; + let Post; before(function() { - var ds = new DataSource('memory');// define models + const ds = new DataSource('memory');// define models Post = ds.define('Post', { title: {type: String, length: 255, index: true}, content: {type: String}, @@ -854,7 +854,7 @@ describe('Models attached to a dataSource', function() { }); it('creates a new instance if it does not exist', function(done) { - var post = {id: 123, title: 'a', content: 'AAA'}; + const post = {id: 123, title: 'a', content: 'AAA'}; Post.updateOrCreate(post, function(err, p) { should.not.exist(err); p.title.should.be.equal(post.title); @@ -915,7 +915,7 @@ describe('Models attached to a dataSource', function() { }); it('creates a new instance if it does not exist', function(done) { - var post = new Post({id: '123', title: 'a', content: 'AAA'}); + const post = new Post({id: '123', title: 'a', content: 'AAA'}); post.save(post, function(err, p) { should.not.exist(err); p.title.should.be.equal(post.title); @@ -937,33 +937,33 @@ describe('Models attached to a dataSource', function() { describe('DataSource connector types', function() { it('returns an array of types using getTypes', function() { - var ds = new DataSource('memory'); - var types = ds.getTypes(); + const ds = new DataSource('memory'); + const types = ds.getTypes(); assert.deepEqual(types, ['db', 'nosql', 'memory']); }); describe('supportTypes', function() { it('tests supported types by string', function() { - var ds = new DataSource('memory'); - var result = ds.supportTypes('db'); + const ds = new DataSource('memory'); + const result = ds.supportTypes('db'); assert(result); }); it('tests supported types by array', function() { - var ds = new DataSource('memory'); - var result = ds.supportTypes(['db', 'memory']); + const ds = new DataSource('memory'); + const result = ds.supportTypes(['db', 'memory']); assert(result); }); it('tests unsupported types by string', function() { - var ds = new DataSource('memory'); - var result = ds.supportTypes('rdbms'); + const ds = new DataSource('memory'); + const result = ds.supportTypes('rdbms'); assert(!result); }); it('tests unsupported types by array', function() { - var ds = new DataSource('memory'); - var result = ds.supportTypes(['rdbms', 'memory']); + const ds = new DataSource('memory'); + let result = ds.supportTypes(['rdbms', 'memory']); assert(!result); result = ds.supportTypes(['rdbms']); @@ -974,7 +974,7 @@ describe('DataSource connector types', function() { describe('DataSource._resolveConnector', function() { // Mocked require - var loader = function(name) { + const loader = function(name) { if (name.indexOf('./connectors/') !== -1) { // ./connectors/ doesn't exist return null; @@ -989,48 +989,48 @@ describe('DataSource._resolveConnector', function() { }; it('resolves connector by path', function() { - var connector = DataSource._resolveConnector(__dirname + '/../lib/connectors/memory'); + const connector = DataSource._resolveConnector(__dirname + '/../lib/connectors/memory'); assert(connector.connector); }); it('resolves connector by internal name', function() { - var connector = DataSource._resolveConnector('memory'); + const connector = DataSource._resolveConnector('memory'); assert(connector.connector); }); it('resolves connector by module name starting with loopback-connector-', function() { - var connector = DataSource._resolveConnector('loopback-connector-xyz', loader); + const connector = DataSource._resolveConnector('loopback-connector-xyz', loader); assert(connector.connector); }); it('resolves connector by short module name with full name first', function() { - var connector = DataSource._resolveConnector('xyz', loader); + const connector = DataSource._resolveConnector('xyz', loader); assert(connector.connector); assert.equal(connector.connector.name, 'loopback-connector-xyz'); }); it('resolves connector by short module name', function() { - var connector = DataSource._resolveConnector('abc', loader); + const connector = DataSource._resolveConnector('abc', loader); assert(connector.connector); assert.equal(connector.connector.name, 'abc'); }); it('resolves connector by short module name for known connectors', function() { - var connector = DataSource._resolveConnector('oracle', loader); + const connector = DataSource._resolveConnector('oracle', loader); assert(connector.connector); assert.equal(connector.connector.name, 'loopback-connector-oracle'); }); it('resolves connector by full module name', function() { - var connector = DataSource._resolveConnector('loopback-xyz', loader); + const connector = DataSource._resolveConnector('loopback-xyz', loader); assert(connector.connector); }); it('fails to resolve connector by module name starting with loopback-connector-', function() { - var connector = DataSource._resolveConnector('loopback-connector-xyz'); + const connector = DataSource._resolveConnector('loopback-connector-xyz'); assert(!connector.connector); assert(connector.error.indexOf('loopback-connector-xyz') !== -1); }); it('fails resolve invalid connector by short module name', function() { - var connector = DataSource._resolveConnector('xyz'); + const connector = DataSource._resolveConnector('xyz'); assert(!connector.connector); assert(connector.error.indexOf('loopback-connector-xyz') !== -1); }); it('fails to resolve invalid connector by full module name', function() { - var connector = DataSource._resolveConnector('loopback-xyz'); + const connector = DataSource._resolveConnector('loopback-xyz'); assert(!connector.connector); assert(connector.error.indexOf('loopback-connector-loopback-xyz') !== -1); }); @@ -1038,10 +1038,10 @@ describe('DataSource._resolveConnector', function() { describe('Model define with relations configuration', function() { it('sets up hasMany relations', function(done) { - var ds = new DataSource('memory'); + const ds = new DataSource('memory'); - var Post = ds.define('Post', {userId: Number, content: String}); - var User = ds.define('User', {name: String}, { + const Post = ds.define('Post', {userId: Number, content: String}); + const User = ds.define('User', {name: String}, { relations: {posts: {type: 'hasMany', model: 'Post'}}, }); @@ -1050,10 +1050,10 @@ describe('Model define with relations configuration', function() { }); it('sets up belongsTo relations', function(done) { - var ds = new DataSource('memory'); + const ds = new DataSource('memory'); - var User = ds.define('User', {name: String}); - var Post = ds.define('Post', {userId: Number, content: String}, { + const User = ds.define('User', {name: String}); + const Post = ds.define('Post', {userId: Number, content: String}, { relations: {user: {type: 'belongsTo', model: 'User'}}, }); @@ -1062,10 +1062,10 @@ describe('Model define with relations configuration', function() { }); it('sets up referencesMany relations', function(done) { - var ds = new DataSource('memory'); + const ds = new DataSource('memory'); - var Post = ds.define('Post', {userId: Number, content: String}); - var User = ds.define('User', {name: String}, { + const Post = ds.define('Post', {userId: Number, content: String}); + const User = ds.define('User', {name: String}, { relations: {posts: {type: 'referencesMany', model: 'Post'}}, }); @@ -1074,10 +1074,10 @@ describe('Model define with relations configuration', function() { }); it('sets up embedsMany relations', function(done) { - var ds = new DataSource('memory'); + const ds = new DataSource('memory'); - var Post = ds.define('Post', {userId: Number, content: String}); - var User = ds.define('User', {name: String}, { + const Post = ds.define('Post', {userId: Number, content: String}); + const User = ds.define('User', {name: String}, { relations: {posts: {type: 'embedsMany', model: 'Post'}}, }); @@ -1086,12 +1086,12 @@ describe('Model define with relations configuration', function() { }); it('sets up belongsTo polymorphic relation with `{polymorphic: true}`', function(done) { - var ds = new DataSource('memory'); + const ds = new DataSource('memory'); - var Product = ds.define('Product', {name: String}, {relations: { + const Product = ds.define('Product', {name: String}, {relations: { pictures: {type: 'hasMany', model: 'Picture', polymorphic: 'imageable'}, }}); - var Picture = ds.define('Picture', {name: String}, {relations: { + const Picture = ds.define('Picture', {name: String}, {relations: { imageable: {type: 'belongsTo', polymorphic: true}, }}); @@ -1114,12 +1114,12 @@ describe('Model define with relations configuration', function() { }); it('sets up hasMany polymorphic relation with `{polymorphic: belongsToRelationName}`', function(done) { - var ds = new DataSource('memory'); + const ds = new DataSource('memory'); - var Picture = ds.define('Picture', {name: String}, {relations: { + const Picture = ds.define('Picture', {name: String}, {relations: { imageable: {type: 'belongsTo', polymorphic: true}, }}); - var Product = ds.define('Product', {name: String}, {relations: { + const Product = ds.define('Product', {name: String}, {relations: { pictures: {type: 'hasMany', model: 'Picture', polymorphic: 'imageable'}, }}); @@ -1142,14 +1142,14 @@ describe('Model define with relations configuration', function() { }); it('creates a foreign key with the correct type', function(done) { - var ds = new DataSource('memory'); + const ds = new DataSource('memory'); - var User = ds.define('User', {name: String, id: {type: String, id: true}}); - var Post = ds.define('Post', {content: String}, {relations: { + const User = ds.define('User', {name: String, id: {type: String, id: true}}); + const Post = ds.define('Post', {content: String}, {relations: { user: {type: 'belongsTo', model: 'User'}}, }); - var fk = Post.definition.properties['userId']; + const fk = Post.definition.properties['userId']; assert(fk, 'The foreign key should be added'); assert(fk.type === String, 'The foreign key should be the same type as primary key'); assert(Post.relations['user'], 'User relation should be set'); @@ -1157,9 +1157,9 @@ describe('Model define with relations configuration', function() { }); it('sets up related hasMany and belongsTo relations', function(done) { - var ds = new DataSource('memory'); + const ds = new DataSource('memory'); - var User = ds.define('User', {name: String}, { + const User = ds.define('User', {name: String}, { relations: { posts: {type: 'hasMany', model: 'Post'}, accounts: {type: 'hasMany', model: 'Account'}, @@ -1169,11 +1169,11 @@ describe('Model define with relations configuration', function() { assert(!User.relations['posts']); assert(!User.relations['accounts']); - var Post = ds.define('Post', {userId: Number, content: String}, { + const Post = ds.define('Post', {userId: Number, content: String}, { relations: {user: {type: 'belongsTo', model: 'User'}}, }); - var Account = ds.define('Account', {userId: Number, type: String}, { + const Account = ds.define('Account', {userId: Number, type: String}, { relations: {user: {type: 'belongsTo', model: 'User'}}, }); @@ -1212,12 +1212,12 @@ describe('Model define with relations configuration', function() { }); it('throws an error if a relation is missing type', function(done) { - var ds = new DataSource('memory'); + const ds = new DataSource('memory'); - var Post = ds.define('Post', {userId: Number, content: String}); + const Post = ds.define('Post', {userId: Number, content: String}); try { - var User = ds.define('User', {name: String}, { + const User = ds.define('User', {name: String}, { relations: {posts: {model: 'Post'}}, }); } catch (e) { @@ -1226,12 +1226,12 @@ describe('Model define with relations configuration', function() { }); it('throws an error if a relation type is invalid', function(done) { - var ds = new DataSource('memory'); + const ds = new DataSource('memory'); - var Post = ds.define('Post', {userId: Number, content: String}); + const Post = ds.define('Post', {userId: Number, content: String}); try { - var User = ds.define('User', {name: String}, { + const User = ds.define('User', {name: String}, { relations: {posts: {type: 'hasXYZ', model: 'Post'}}, }); } catch (e) { @@ -1240,8 +1240,8 @@ describe('Model define with relations configuration', function() { }); it('sets up hasMany through relations', function(done) { - var ds = new DataSource('memory'); - var Physician = ds.createModel('Physician', { + const ds = new DataSource('memory'); + const Physician = ds.createModel('Physician', { name: String, }, { relations: { @@ -1249,7 +1249,7 @@ describe('Model define with relations configuration', function() { }, }); - var Patient = ds.createModel('Patient', { + const Patient = ds.createModel('Patient', { name: String, }, { relations: { @@ -1260,7 +1260,7 @@ describe('Model define with relations configuration', function() { assert(!Physician.relations['patients']); // Appointment hasn't been resolved yet assert(!Patient.relations['physicians']); // Appointment hasn't been resolved yet - var Appointment = ds.createModel('Appointment', { + const Appointment = ds.createModel('Appointment', { physicianId: Number, patientId: Number, appointmentDate: Date, @@ -1277,8 +1277,8 @@ describe('Model define with relations configuration', function() { }); it('sets up hasMany through relations with options', function(done) { - var ds = new DataSource('memory'); - var Physician = ds.createModel('Physician', { + const ds = new DataSource('memory'); + const Physician = ds.createModel('Physician', { name: String, }, { relations: { @@ -1286,7 +1286,7 @@ describe('Model define with relations configuration', function() { }, }); - var Patient = ds.createModel('Patient', { + const Patient = ds.createModel('Patient', { name: String, }, { relations: { @@ -1294,7 +1294,7 @@ describe('Model define with relations configuration', function() { }, }); - var Appointment = ds.createModel('Appointment', { + const Appointment = ds.createModel('Appointment', { physicianId: Number, patientId: Number, appointmentDate: Date, @@ -1311,11 +1311,11 @@ describe('Model define with relations configuration', function() { }); it('sets up relations after attach', function(done) { - var ds = new DataSource('memory'); - var modelBuilder = new ModelBuilder(); + const ds = new DataSource('memory'); + const modelBuilder = new ModelBuilder(); - var Post = modelBuilder.define('Post', {userId: Number, content: String}); - var User = modelBuilder.define('User', {name: String}, { + const Post = modelBuilder.define('Post', {userId: Number, content: String}); + const User = modelBuilder.define('User', {name: String}, { relations: {posts: {type: 'hasMany', model: 'Post'}, }}); @@ -1329,12 +1329,12 @@ describe('Model define with relations configuration', function() { describe('Model define with scopes configuration', function() { it('creates scopes', function(done) { - var ds = new DataSource('memory'); - var User = ds.define('User', {name: String, vip: Boolean, age: Number}, + const ds = new DataSource('memory'); + const User = ds.define('User', {name: String, vip: Boolean, age: Number}, {scopes: {vips: {where: {vip: true}}, top5: {limit: 5, order: 'age'}}}); - var users = []; - for (var i = 0; i < 10; i++) { + const users = []; + for (let i = 0; i < 10; i++) { users.push({name: 'User' + i, vip: i % 3 === 0, age: 20 + i * 2}); } async.each(users, function(user, callback) { @@ -1355,7 +1355,7 @@ describe('Model define with scopes configuration', function() { }); describe('DataAccessObject', function() { - var ds, model, where, error, filter; + let ds, model, where, error, filter; before(function() { ds = new DataSource('memory'); @@ -1418,7 +1418,7 @@ describe('DataAccessObject', function() { }); it('coerces where clause for date types', function() { - var d = new Date(); + const d = new Date(); where = model._coerce({date: d}); assert.deepEqual(where, {date: d}); @@ -1460,7 +1460,7 @@ describe('DataAccessObject', function() { }); it('continues to coerce properties after a logical operator', function() { - var clause = {and: [{age: '10'}], vip: 'true'}; + const clause = {and: [{age: '10'}], vip: 'true'}; // Key order is predictable but not guaranteed. We prefer false negatives (failure) to false positives. assert(Object.keys(clause)[0] === 'and', 'Unexpected key order.'); @@ -1497,7 +1497,7 @@ describe('DataAccessObject', function() { ]; COERCIONS.forEach(coercion => { - var inStr = JSON.stringify(coercion.in); + const inStr = JSON.stringify(coercion.in); it('coerces where clause with array-like objects ' + inStr, () => { assert.deepEqual(model._coerce(coercion.in), coercion.out); }); @@ -1510,7 +1510,7 @@ describe('DataAccessObject', function() { ]; INVALID_CLAUSES.forEach((where) => { - var whereStr = JSON.stringify(where); + const whereStr = JSON.stringify(where); it('throws an error on malformed array-like object ' + whereStr, () => { assert.throws(() => model._coerce(where), /property has invalid clause/); }); @@ -1569,7 +1569,7 @@ describe('DataAccessObject', function() { }); it('throws an error when malformed logical operators follow valid logical clauses', function() { - var invalid = {and: [{x: 1}], or: 'bogus'}; + const invalid = {and: [{x: 1}], or: 'bogus'}; // Key order is predictable but not guaranteed. We prefer false negatives (failure) to false positives. assert(Object.keys(invalid)[0] !== 'or', 'Unexpected key order.'); @@ -1583,7 +1583,7 @@ describe('DataAccessObject', function() { }); it('throws an error if the filter property is not an object', function() { - var filter = null; + let filter = null; try { // The filter clause has to be an object filter = model._normalize('abc'); @@ -1730,7 +1730,7 @@ describe('DataAccessObject', function() { }); describe('ModelBuilder processing json files', function() { - var path = require('path'), + const path = require('path'), fs = require('fs'); /** @@ -1739,7 +1739,7 @@ describe('ModelBuilder processing json files', function() { * @returns A map of schemas keyed by name */ function loadSchemasSync(schemaFile, dataSource) { - var modelBuilder, createModel; + let modelBuilder, createModel; // Set up the data source if (!dataSource) { modelBuilder = new ModelBuilder(); @@ -1749,17 +1749,17 @@ describe('ModelBuilder processing json files', function() { } // Read the dataSource JSON file - var schemas = JSON.parse(fs.readFileSync(schemaFile)); + const schemas = JSON.parse(fs.readFileSync(schemaFile)); return modelBuilder.buildModels(schemas, createModel); } it('defines models', function() { - var models = loadSchemasSync(path.join(__dirname, 'test1-schemas.json')); + let models = loadSchemasSync(path.join(__dirname, 'test1-schemas.json')); models.should.have.property('AnonymousModel_0'); models.AnonymousModel_0.should.have.property('modelName', 'AnonymousModel_0'); - var m1 = new models.AnonymousModel_0({title: 'Test'}); + const m1 = new models.AnonymousModel_0({title: 'Test'}); m1.should.have.property('title', 'Test'); m1.should.have.property('author', 'Raymond'); @@ -1767,16 +1767,16 @@ describe('ModelBuilder processing json files', function() { models.should.have.property('Address'); models.should.have.property('Account'); models.should.have.property('Customer'); - for (var s in models) { - var m = models[s]; + for (const s in models) { + const m = models[s]; assert(new m()); } }); it('attaches models to a specified dataSource', function() { - var ds = new DataSource('memory'); + const ds = new DataSource('memory'); - var models = loadSchemasSync(path.join(__dirname, 'test2-schemas.json'), ds); + const models = loadSchemasSync(path.join(__dirname, 'test2-schemas.json'), ds); models.should.have.property('Address'); models.should.have.property('Account'); models.should.have.property('Customer'); @@ -1784,9 +1784,9 @@ describe('ModelBuilder processing json files', function() { }); it('allows customization of default model base class', function() { - var modelBuilder = new ModelBuilder(); + const modelBuilder = new ModelBuilder(); - var User = modelBuilder.define('User', { + const User = modelBuilder.define('User', { name: String, bio: ModelBuilder.Text, approved: Boolean, @@ -1796,14 +1796,14 @@ describe('ModelBuilder processing json files', function() { modelBuilder.defaultModelBaseClass = User; - var Customer = modelBuilder.define('Customer', {customerId: {type: String, id: true}}); + const Customer = modelBuilder.define('Customer', {customerId: {type: String, id: true}}); assert(Customer.prototype instanceof User); }); it('accepts a model base class', function() { - var modelBuilder = new ModelBuilder(); + const modelBuilder = new ModelBuilder(); - var User = modelBuilder.define('User', { + const User = modelBuilder.define('User', { name: String, bio: ModelBuilder.Text, approved: Boolean, @@ -1811,7 +1811,7 @@ describe('ModelBuilder processing json files', function() { age: Number, }); - var Customer = modelBuilder.define('Customer', + const Customer = modelBuilder.define('Customer', {customerId: {type: String, id: true}}, {}, User); assert(Customer.prototype instanceof User); }); @@ -1819,31 +1819,31 @@ describe('ModelBuilder processing json files', function() { describe('DataSource constructor', function() { it('takes url as the settings', function() { - var ds = new DataSource('memory://localhost/mydb?x=1'); + const ds = new DataSource('memory://localhost/mydb?x=1'); assert.equal(ds.connector.name, 'memory'); }); it('takes connector name', function() { - var ds = new DataSource('memory'); + const ds = new DataSource('memory'); assert.equal(ds.connector.name, 'memory'); }); it('takes settings object', function() { - var ds = new DataSource({connector: 'memory'}); + const ds = new DataSource({connector: 'memory'}); assert.equal(ds.connector.name, 'memory'); }); it('takes settings object and name', function() { - var ds = new DataSource('x', {connector: 'memory'}); + const ds = new DataSource('x', {connector: 'memory'}); assert.equal(ds.connector.name, 'memory'); }); }); describe('ModelBuilder options.models', function() { it('injects model classes from models', function() { - var builder = new ModelBuilder(); - var M1 = builder.define('M1'); - var M2 = builder.define('M2', {}, {models: { + const builder = new ModelBuilder(); + const M1 = builder.define('M1'); + const M2 = builder.define('M2', {}, {models: { 'M1': M1, }}); @@ -1851,9 +1851,9 @@ describe('ModelBuilder options.models', function() { }); it('injects model classes by name in the models', function() { - var builder = new ModelBuilder(); - var M1 = builder.define('M1'); - var M2 = builder.define('M2', {}, {models: { + const builder = new ModelBuilder(); + const M1 = builder.define('M1'); + const M2 = builder.define('M2', {}, {models: { 'M1': 'M1', }}); @@ -1862,25 +1862,25 @@ describe('ModelBuilder options.models', function() { it('injects model classes by name in the models before the class is defined', function() { - var builder = new ModelBuilder(); - var M2 = builder.define('M2', {}, {models: { + const builder = new ModelBuilder(); + const M2 = builder.define('M2', {}, {models: { 'M1': 'M1', }}); assert(M2.M1, 'M1 should be injected to M2'); assert(M2.M1.settings.unresolved, 'M1 is still a proxy'); - var M1 = builder.define('M1'); + const M1 = builder.define('M1'); assert.equal(M2.M1, M1, 'M1 should be injected to M2'); }); it('uses non-strict mode for embedded models by default', function() { - var builder = new ModelBuilder(); - var M1 = builder.define('testEmbedded', { + const builder = new ModelBuilder(); + const M1 = builder.define('testEmbedded', { name: 'string', address: { street: 'string', }, }); - var m1 = new M1({ + const m1 = new M1({ name: 'Jim', address: { street: 'washington st', @@ -1891,15 +1891,15 @@ describe('ModelBuilder options.models', function() { }); it('uses the strictEmbeddedModels setting (true) when applied on modelBuilder', function() { - var builder = new ModelBuilder(); + const builder = new ModelBuilder(); builder.settings.strictEmbeddedModels = true; - var M1 = builder.define('testEmbedded', { + const M1 = builder.define('testEmbedded', { name: 'string', address: { street: 'string', }, }); - var m1 = new M1({ + const m1 = new M1({ name: 'Jim', address: { street: 'washington st', @@ -1908,15 +1908,15 @@ describe('ModelBuilder options.models', function() { }); assert.equal(m1.address.number, undefined, 'm1 should not contain number property in address'); assert.equal(m1.address.isValid(), false, 'm1 address should not validate with extra property'); - var codes = m1.address.errors && m1.address.errors.codes || {}; + const codes = m1.address.errors && m1.address.errors.codes || {}; assert.deepEqual(codes.number, ['unknown-property']); }); }); describe('updateOnly', function() { it('sets forceId to true when model id is generated', function(done) { - var ds = new DataSource('memory'); - var Post = ds.define('Post', { + const ds = new DataSource('memory'); + const Post = ds.define('Post', { title: {type: String, length: 255}, date: {type: Date, default: function() { return new Date(); @@ -1930,8 +1930,8 @@ describe('updateOnly', function() { }); it('flags id as updateOnly when forceId is undefined', function(done) { - var ds = new DataSource('memory'); - var Post = ds.define('Post', { + const ds = new DataSource('memory'); + const Post = ds.define('Post', { title: {type: String, length: 255}, date: {type: Date, default: function() { return new Date(); @@ -1945,8 +1945,8 @@ describe('updateOnly', function() { }); it('does not flag id as updateOnly when forceId is false', function(done) { - var ds = new DataSource('memory'); - var Person = ds.define('Person', { + const ds = new DataSource('memory'); + const Person = ds.define('Person', { name: String, gender: String, }, {forceId: false}); @@ -1958,8 +1958,8 @@ describe('updateOnly', function() { }); it('flags id as updateOnly when forceId is true', function(done) { - var ds = new DataSource('memory'); - var Person = ds.define('Person', { + const ds = new DataSource('memory'); + const Person = ds.define('Person', { name: String, gender: String, }, {forceId: true}); diff --git a/test/manipulation.test.js b/test/manipulation.test.js index 395c3b69..164939c2 100644 --- a/test/manipulation.test.js +++ b/test/manipulation.test.js @@ -7,15 +7,15 @@ 'use strict'; /* global getSchema:false, connectorCapabilities:false */ -var async = require('async'); -var bdd = require('./helpers/bdd-if'); -var should = require('./init.js'); -var uid = require('./helpers/uid-generator'); +const async = require('async'); +const bdd = require('./helpers/bdd-if'); +const should = require('./init.js'); +const uid = require('./helpers/uid-generator'); -var db, Person; -var ValidationError = require('..').ValidationError; +let db, Person; +const ValidationError = require('..').ValidationError; -var UUID_REGEXP = /^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i; +const UUID_REGEXP = /^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i; describe('manipulation', function() { before(function(done) { @@ -36,19 +36,19 @@ describe('manipulation', function() { // A simplified implementation of LoopBack's User model // to reproduce problems related to properties with dynamic setters // For the purpose of the tests, we use a counter instead of a hash fn. - var StubUser; - var stubPasswordCounter; + let StubUser; + let stubPasswordCounter; before(function setupStubUserModel(done) { StubUser = db.createModel('StubUser', {password: String}, {forceId: true}); StubUser.setter.password = function(plain) { if (plain.length === 0) throw new Error('password cannot be empty'); - var hashed = false; + let hashed = false; if (!plain) return; - var pos = plain.indexOf('-'); + const pos = plain.indexOf('-'); if (pos !== -1) { - var head = plain.substr(0, pos); - var tail = plain.substr(pos + 1, plain.length); + const head = plain.substr(0, pos); + const tail = plain.substr(pos + 1, plain.length); hashed = head.toUpperCase() === tail; } if (hashed) return; @@ -67,7 +67,7 @@ describe('manipulation', function() { }); describe('forceId', function() { - var TestForceId; + let TestForceId; before(function(done) { TestForceId = db.define('TestForceId'); db.automigrate('TestForceId', done); @@ -112,7 +112,7 @@ describe('manipulation', function() { }); it('should instantiate an object', function(done) { - var p = new Person({name: 'Anatoliy'}); + const p = new Person({name: 'Anatoliy'}); p.name.should.equal('Anatoliy'); p.isNewRecord().should.be.true; p.save(function(err, inst) { @@ -124,7 +124,7 @@ describe('manipulation', function() { }); it('should instantiate an object (promise variant)', function(done) { - var p = new Person({name: 'Anatoliy'}); + const p = new Person({name: 'Anatoliy'}); p.name.should.equal('Anatoliy'); p.isNewRecord().should.be.true; p.save() @@ -170,7 +170,7 @@ describe('manipulation', function() { }); it('should not allow user-defined value for the id of object - save', function(done) { - var p = new Person({id: 123456}); + const p = new Person({id: 123456}); p.isNewRecord().should.be.true; p.save(function(err, inst) { err.should.be.instanceof(ValidationError); @@ -182,7 +182,7 @@ describe('manipulation', function() { }); it('should not allow user-defined value for the id of object - save (promise variant)', function(done) { - var p = new Person({id: 123456}); + const p = new Person({id: 123456}); p.isNewRecord().should.be.true; p.save() .then(function(inst) { @@ -249,7 +249,7 @@ describe('manipulation', function() { }); it('should create batch of objects', function(done) { - var batch = [ + const batch = [ {name: 'Shaltay'}, {name: 'Boltay'}, {}, @@ -279,7 +279,7 @@ describe('manipulation', function() { }); it('should create batch of objects (promise variant)', function(done) { - var batch = [ + const batch = [ {name: 'ShaltayPromise'}, {name: 'BoltayPromise'}, {}, @@ -314,7 +314,7 @@ describe('manipulation', function() { return next(); } }; - var batch = [ + const batch = [ {name: 'A'}, {name: 'B'}, undefined, @@ -342,7 +342,7 @@ describe('manipulation', function() { Person.findById(created.id, function(err, found) { if (err) return done(err); - var result = found.toObject(); + const result = found.toObject(); result.should.containEql({ id: created.id, name: 'a-name', @@ -359,7 +359,7 @@ describe('manipulation', function() { 'object with duplicate id', function(done) { // NOTE(bajtos) We cannot reuse Person model here, // `settings.forceId` aborts the CREATE request at the validation step. - var Product = db.define('ProductTest', {name: String}, {forceId: false}); + const Product = db.define('ProductTest', {name: String}, {forceId: false}); db.automigrate('ProductTest', function(err) { if (err) return done(err); @@ -379,7 +379,7 @@ describe('manipulation', function() { describe('save', function() { it('should save new object', function(done) { - var p = new Person; + const p = new Person; should.not.exist(p.id); p.save(function(err) { if (err) return done(err); @@ -389,7 +389,7 @@ describe('manipulation', function() { }); it('should save new object (promise variant)', function(done) { - var p = new Person; + const p = new Person; should.not.exist(p.id); p.save() .then(function() { @@ -515,7 +515,7 @@ describe('manipulation', function() { }); describe('updateAttributes', function() { - var person; + let person; before(function(done) { Person.destroyAll(function(err) { @@ -727,7 +727,7 @@ describe('manipulation', function() { it('should allow same stringified id value on updateAttributes', function(done) { - var pid = person.id; + let pid = person.id; if (typeof person.id === 'object' || typeof person.id === 'number') { // For example MongoDB ObjectId pid = person.id.toString(); @@ -785,7 +785,7 @@ describe('manipulation', function() { }); it('should raises on connector error', function(done) { - var fakeConnector = { + const fakeConnector = { updateAttributes: function(model, id, data, options, cb) { cb(new Error('Database Error')); }, @@ -799,7 +799,7 @@ describe('manipulation', function() { }); describe('updateOrCreate', function() { - var Post, Todo; + let Post, Todo; before('prepare "Post" and "Todo" models', function(done) { Post = db.define('Post', { @@ -896,7 +896,7 @@ describe('manipulation', function() { it('should preserve properties with dynamic setters on update', function(done) { StubUser.create({password: 'foo'}, function(err, created) { if (err) return done(err); - var data = {id: created.id, password: 'bar'}; + const data = {id: created.id, password: 'bar'}; StubUser.updateOrCreate(data, function(err, updated) { if (err) return done(err); updated.password.should.equal('bar-BAR'); @@ -914,7 +914,7 @@ describe('manipulation', function() { {name: 'a-name', gender: undefined}, function(err, instance) { if (err) return done(err); - var result = instance.toObject(); + const result = instance.toObject(); result.id.should.eql(instance.id); should.equal(result.name, 'a-name'); should.equal(result.gender, undefined); @@ -923,7 +923,7 @@ describe('manipulation', function() { {id: instance.id, name: 'updated name'}, function(err, updated) { if (err) return done(err); - var result = updated.toObject(); + const result = updated.toObject(); result.id.should.eql(instance.id); should.equal(result.name, 'updated name'); should.equal(result.gender, null); @@ -938,7 +938,7 @@ describe('manipulation', function() { it('updates specific instances when PK is not an auto-generated id', function(done) { // skip the test if the connector is mssql // https://github.com/strongloop/loopback-connector-mssql/pull/92#r72853474 - var dsName = Post.dataSource.name; + const dsName = Post.dataSource.name; if (dsName === 'mssql') return done(); Post.create([ @@ -952,7 +952,7 @@ describe('manipulation', function() { }, function(err, instance) { if (err) return done(err); - var result = instance.toObject(); + const result = instance.toObject(); result.should.have.properties({ title: 'postA', content: 'newContent', @@ -972,7 +972,7 @@ describe('manipulation', function() { }); it('should allow save() of the created instance', function(done) { - var unknownId = uid.fromConnector(db) || 999; + const unknownId = uid.fromConnector(db) || 999; Person.updateOrCreate( {id: unknownId, name: 'a-name'}, function(err, inst) { @@ -985,9 +985,9 @@ describe('manipulation', function() { bdd.describeIf(connectorCapabilities.supportForceId !== false, 'updateOrCreate when forceId is true', function() { - var Post; + let Post; before(function definePostModel(done) { - var ds = getSchema(); + const ds = getSchema(); Post = ds.define('Post', { title: {type: String, length: 255}, content: {type: String}, @@ -996,8 +996,8 @@ describe('manipulation', function() { }); it('fails when id does not exist in db & validate is true', function(done) { - var unknownId = uid.fromConnector(db) || 123; - var post = {id: unknownId, title: 'a', content: 'AAA'}; + const unknownId = uid.fromConnector(db) || 123; + const post = {id: unknownId, title: 'a', content: 'AAA'}; Post.updateOrCreate(post, {validate: true}, (err) => { should(err).have.property('statusCode', 404); done(); @@ -1005,8 +1005,8 @@ describe('manipulation', function() { }); it('fails when id does not exist in db & validate is false', function(done) { - var unknownId = uid.fromConnector(db) || 123; - var post = {id: unknownId, title: 'a', content: 'AAA'}; + const unknownId = uid.fromConnector(db) || 123; + const post = {id: unknownId, title: 'a', content: 'AAA'}; Post.updateOrCreate(post, {validate: false}, (err) => { should(err).have.property('statusCode', 404); done(); @@ -1015,8 +1015,8 @@ describe('manipulation', function() { it('fails when id does not exist in db & validate is false when using updateAttributes', function(done) { - var unknownId = uid.fromConnector(db) || 123; - var post = new Post({id: unknownId}); + const unknownId = uid.fromConnector(db) || 123; + const post = new Post({id: unknownId}); post.updateAttributes({title: 'updated title', content: 'AAA'}, {validate: false}, (err) => { should(err).have.property('statusCode', 404); done(); @@ -1024,7 +1024,7 @@ describe('manipulation', function() { }); it('works on create if the request does not include an id', function(done) { - var post = {title: 'a', content: 'AAA'}; + const post = {title: 'a', content: 'AAA'}; Post.updateOrCreate(post, (err, p) => { if (err) return done(err); p.title.should.equal(post.title); @@ -1049,14 +1049,14 @@ describe('manipulation', function() { }); }); - var hasReplaceById = connectorCapabilities.cloudantCompatible !== false && + const hasReplaceById = connectorCapabilities.cloudantCompatible !== false && !!getSchema().connector.replaceById; if (!hasReplaceById) { describe.skip('replaceById - not implemented', function() {}); } else { describe('replaceOrCreate', function() { - var Post, unknownId; + let Post, unknownId; before(function(done) { db = getSchema(); unknownId = uid.fromConnector(db) || 123; @@ -1069,7 +1069,7 @@ describe('manipulation', function() { }); it('works without options on create (promise variant)', function(done) { - var post = {id: unknownId, title: 'a', content: 'AAA'}; + const post = {id: unknownId, title: 'a', content: 'AAA'}; Post.replaceOrCreate(post) .then(function(p) { should.exist(p); @@ -1091,7 +1091,7 @@ describe('manipulation', function() { }); it('works with options on create (promise variant)', function(done) { - var post = {id: unknownId, title: 'a', content: 'AAA'}; + const post = {id: unknownId, title: 'a', content: 'AAA'}; Post.replaceOrCreate(post, {validate: false}) .then(function(p) { should.exist(p); @@ -1113,7 +1113,7 @@ describe('manipulation', function() { }); it('works without options on update (promise variant)', function(done) { - var post = {title: 'a', content: 'AAA', comments: ['Comment1']}; + const post = {title: 'a', content: 'AAA', comments: ['Comment1']}; Post.create(post) .then(function(created) { created = created.toObject(); @@ -1144,7 +1144,7 @@ describe('manipulation', function() { }); it('works with options on update (promise variant)', function(done) { - var post = {title: 'a', content: 'AAA', comments: ['Comment1']}; + const post = {title: 'a', content: 'AAA', comments: ['Comment1']}; Post.create(post) .then(function(created) { created = created.toObject(); @@ -1234,7 +1234,7 @@ describe('manipulation', function() { }); it('works without options on create (callback variant)', function(done) { - var post = {id: unknownId, title: 'a', content: 'AAA'}; + const post = {id: unknownId, title: 'a', content: 'AAA'}; Post.replaceOrCreate(post, function(err, p) { if (err) return done(err); p.id.should.eql(post.id); @@ -1254,7 +1254,7 @@ describe('manipulation', function() { }); it('works with options on create (callback variant)', function(done) { - var post = {id: unknownId, title: 'a', content: 'AAA'}; + const post = {id: unknownId, title: 'a', content: 'AAA'}; Post.replaceOrCreate(post, {validate: false}, function(err, p) { if (err) return done(err); p.id.should.eql(post.id); @@ -1277,7 +1277,7 @@ describe('manipulation', function() { bdd.describeIf(hasReplaceById && connectorCapabilities.supportForceId !== false, 'replaceOrCreate ' + 'when forceId is true', function() { - var Post, unknownId; + let Post, unknownId; before(function(done) { db = getSchema(); unknownId = uid.fromConnector(db) || 123; @@ -1289,7 +1289,7 @@ describe('manipulation', function() { }); it('fails when id does not exist in db', function(done) { - var post = {id: unknownId, title: 'a', content: 'AAA'}; + const post = {id: unknownId, title: 'a', content: 'AAA'}; Post.replaceOrCreate(post, function(err, p) { err.statusCode.should.equal(404); @@ -1299,7 +1299,7 @@ describe('manipulation', function() { // eslint-disable-next-line mocha/no-identical-title it('works on create if the request does not include an id', function(done) { - var post = {title: 'a', content: 'AAA'}; + const post = {title: 'a', content: 'AAA'}; Post.replaceOrCreate(post, function(err, p) { if (err) return done(err); p.title.should.equal(post.title); @@ -1329,9 +1329,9 @@ describe('manipulation', function() { describe.skip('replaceAttributes/replaceById - not implemented', function() {}); } else { describe('replaceAttributes', function() { - var postInstance; - var Post; - var ds = getSchema(); + let postInstance; + let Post; + const ds = getSchema(); before(function(done) { Post = ds.define('Post', { title: {type: String, length: 255, index: true}, @@ -1486,12 +1486,12 @@ describe('manipulation', function() { }); it('should fail when changing id', function(done) { - var unknownId = uid.fromConnector(db) || 999; + const unknownId = uid.fromConnector(db) || 999; Post.findById(postInstance.id, function(err, p) { if (err) return done(err); p.replaceAttributes({title: 'b', id: unknownId}, function(err, p) { should.exist(err); - var expectedErrMsg = 'id property (id) cannot be updated from ' + + const expectedErrMsg = 'id property (id) cannot be updated from ' + postInstance.id + ' to ' + unknownId; err.message.should.equal(expectedErrMsg); done(); @@ -1533,7 +1533,7 @@ describe('manipulation', function() { } bdd.describeIf(hasReplaceById, 'replaceById', function() { - var Post; + let Post; before(function(done) { db = getSchema(); Post = db.define('Post', { @@ -1545,8 +1545,8 @@ describe('manipulation', function() { bdd.itIf(connectorCapabilities.supportForceId !== false, 'fails when id does not exist in db ' + 'using replaceById', function(done) { - var unknownId = uid.fromConnector(db) || 123; - var post = {id: unknownId, title: 'a', content: 'AAA'}; + const unknownId = uid.fromConnector(db) || 123; + const post = {id: unknownId, title: 'a', content: 'AAA'}; Post.replaceById(post.id, post, function(err, p) { err.statusCode.should.equal(404); done(); @@ -1590,8 +1590,8 @@ describe('manipulation', function() { should.exist(res); res.should.be.instanceOf(Array); res.should.have.lengthOf(2); - var p = res[0]; - var created = res[1]; + const p = res[0]; + const created = res[1]; p.should.be.instanceOf(Person); p.name.should.equal('Jed'); p.gender.should.equal('male'); @@ -1609,8 +1609,8 @@ describe('manipulation', function() { .then(function(res) { res.should.be.instanceOf(Array); res.should.have.lengthOf(2); - var p = res[0]; - var created = res[1]; + const p = res[0]; + const created = res[1]; p.should.be.instanceOf(Person); p.name.should.equal('Jed'); p.gender.should.equal('male'); @@ -1757,7 +1757,7 @@ describe('manipulation', function() { bdd.describeIf(connectorCapabilities.reportDeletedCount === false && connectorCapabilities.deleteWithOtherThanId === false, 'deleteAll/destroyAll case 2', function() { - var idJohn, idJane; + let idJohn, idJane; beforeEach(function clearOldData(done) { Person.deleteAll(done); }); @@ -1807,7 +1807,7 @@ describe('manipulation', function() { // eslint-disable-next-line mocha/no-identical-title it('should report zero deleted instances when no matches are found', function(done) { - var unknownId = uid.fromConnector(db) || 1234567890; + const unknownId = uid.fromConnector(db) || 1234567890; Person.deleteAll({id: unknownId}, function(err, info) { if (err) return done(err); should.not.exist(info.count); @@ -1855,7 +1855,7 @@ describe('manipulation', function() { }); it('should allow deleteById(id) - fail', function(done) { - var unknownId = uid.fromConnector(db) || 9999; + const unknownId = uid.fromConnector(db) || 9999; Person.settings.strictDelete = false; Person.deleteById(unknownId, function(err, info) { if (err) return done(err); @@ -1869,8 +1869,8 @@ describe('manipulation', function() { }); it('should allow deleteById(id) - fail with error', function(done) { - var unknownId = uid.fromConnector(db) || 9999; - var errMsg = 'No instance with id ' + unknownId.toString() + ' found for Person'; + const unknownId = uid.fromConnector(db) || 9999; + const errMsg = 'No instance with id ' + unknownId.toString() + ' found for Person'; Person.settings.strictDelete = true; Person.deleteById(unknownId, function(err) { should.exist(err); @@ -1949,7 +1949,7 @@ describe('manipulation', function() { describe('initialize', function() { it('should initialize object properly', function() { - var hw = 'Hello word', + const hw = 'Hello word', now = Date.now(), person = new Person({name: hw}); @@ -1960,7 +1960,7 @@ describe('manipulation', function() { }); describe('Date $now function (type: Date)', function() { - var CustomModel; + let CustomModel; before(function(done) { CustomModel = db.define('CustomModel1', { @@ -1971,7 +1971,7 @@ describe('manipulation', function() { it('should report current date as default value for date property', function(done) { - var now = Date.now(); + const now = Date.now(); CustomModel.create(function(err, model) { should.not.exists(err); @@ -1984,7 +1984,7 @@ describe('manipulation', function() { }); describe('Date $now function (type: String)', function() { - var CustomModel; + let CustomModel; before(function(done) { CustomModel = db.define('CustomModel2', { @@ -2006,7 +2006,7 @@ describe('manipulation', function() { }); describe('now defaultFn', function() { - var CustomModel; + let CustomModel; before(function(done) { CustomModel = db.define('CustomModel3', { @@ -2017,7 +2017,7 @@ describe('manipulation', function() { it('should generate current time when "defaultFn" is "now"', function(done) { - var now = Date.now(); + const now = Date.now(); CustomModel.create(function(err, model) { if (err) return done(err); model.now.should.be.instanceOf(Date); @@ -2028,7 +2028,7 @@ describe('manipulation', function() { }); describe('guid defaultFn', function() { - var CustomModel; + let CustomModel; before(function(done) { CustomModel = db.define('CustomModel4', { @@ -2047,7 +2047,7 @@ describe('manipulation', function() { }); describe('uuid defaultFn', function() { - var CustomModel; + let CustomModel; before(function(done) { CustomModel = db.define('CustomModel5', { @@ -2066,7 +2066,7 @@ describe('manipulation', function() { }); describe('uuidv4 defaultFn', function() { - var CustomModel; + let CustomModel; before(function(done) { CustomModel = db.define('CustomModel5', { @@ -2085,11 +2085,11 @@ describe('manipulation', function() { }); describe('shortid defaultFn', function() { - var ModelWithShortId; + let ModelWithShortId; before(createModelWithShortId); it('should generate a new id when "defaultFn" is "shortid"', function(done) { - var SHORTID_REGEXP = /^[0-9a-z_\-]{7,14}$/i; + const SHORTID_REGEXP = /^[0-9a-z_\-]{7,14}$/i; ModelWithShortId.create(function(err, modelWithShortId) { if (err) return done(err); modelWithShortId.shortid.should.match(SHORTID_REGEXP); @@ -2114,7 +2114,7 @@ describe('manipulation', function() { describe('property value coercion', function() { it('should coerce boolean types properly', function() { - var p1 = new Person({name: 'John', married: 'false'}); + let p1 = new Person({name: 'John', married: 'false'}); p1.married.should.equal(false); p1 = new Person({name: 'John', married: 'true'}); @@ -2155,7 +2155,7 @@ describe('manipulation', function() { }); it('should coerce date types properly', function() { - var p1 = new Person({name: 'John', dob: '2/1/2015'}); + let p1 = new Person({name: 'John', dob: '2/1/2015'}); p1.dob.should.eql(new Date('2/1/2015')); p1 = new Person({name: 'John', dob: '2/1/2015'}); @@ -2180,8 +2180,8 @@ describe('manipulation', function() { }); describe('update/updateAll', function() { - var idBrett, idCarla, idDonna, idFrank, idGrace, idHarry; - var filterBrett, filterHarry; + let idBrett, idCarla, idDonna, idFrank, idGrace, idHarry; + let filterBrett, filterHarry; beforeEach(function clearOldData(done) { db = getSchema(); @@ -2230,7 +2230,7 @@ describe('manipulation', function() { it('should not update instances that do not satisfy the where condition', function(done) { idHarry = uid.fromConnector(db) || undefined; - var filter = connectorCapabilities.updateWithOtherThanId === false ? + const filter = connectorCapabilities.updateWithOtherThanId === false ? {id: idHarry} : {name: 'Harry Hoe'}; Person.update(filter, {name: 'Marta Moe'}, function(err, info) { @@ -2250,7 +2250,7 @@ describe('manipulation', function() { it('should only update instances that satisfy the where condition', function(done) { - var filter = connectorCapabilities.deleteWithOtherThanId === false ? + const filter = connectorCapabilities.deleteWithOtherThanId === false ? {id: idBrett} : {name: 'Brett Boe'}; Person.update(filter, {name: 'Harry Hoe'}, function(err, info) { @@ -2325,7 +2325,7 @@ describe('manipulation', function() { }); describe('upsertWithWhere', function() { - var ds, Person; + let ds, Person; before('prepare "Person" model', function(done) { ds = getSchema(); Person = ds.define('Person', { @@ -2355,7 +2355,7 @@ describe('manipulation', function() { it('should preserve properties with dynamic setters on update', function(done) { StubUser.create({password: 'foo'}, function(err, created) { if (err) return done(err); - var data = {password: 'bar'}; + const data = {password: 'bar'}; StubUser.upsertWithWhere({id: created.id}, data, function(err, updated) { if (err) return done(err); updated.password.should.equal('bar-BAR'); @@ -2383,7 +2383,7 @@ describe('manipulation', function() { {name: 'updated name'}, function(err, updated) { if (err) return done(err); - var result = updated.toObject(); + const result = updated.toObject(); result.should.have.properties({ id: instance.id, name: 'updated name', @@ -2406,7 +2406,7 @@ describe('manipulation', function() { }); it('works without options on create (promise variant)', function(done) { - var person = {id: 123, name: 'a', city: 'city a'}; + const person = {id: 123, name: 'a', city: 'city a'}; Person.upsertWithWhere({id: 123}, person) .then(function(p) { should.exist(p); @@ -2428,7 +2428,7 @@ describe('manipulation', function() { }); it('works with options on create (promise variant)', function(done) { - var person = {id: 234, name: 'b', city: 'city b'}; + const person = {id: 234, name: 'b', city: 'city b'}; Person.upsertWithWhere({id: 234}, person, {validate: false}) .then(function(p) { should.exist(p); @@ -2450,7 +2450,7 @@ describe('manipulation', function() { }); it('works without options on update (promise variant)', function(done) { - var person = {id: 456, name: 'AAA', city: 'city AAA'}; + const person = {id: 456, name: 'AAA', city: 'city AAA'}; Person.create(person) .then(function(created) { created = created.toObject(); @@ -2477,7 +2477,7 @@ describe('manipulation', function() { }); it('works with options on update (promise variant)', function(done) { - var person = {id: 789, name: 'CCC', city: 'city CCC'}; + const person = {id: 789, name: 'CCC', city: 'city CCC'}; Person.create(person) .then(function(created) { created = created.toObject(); @@ -2504,7 +2504,7 @@ describe('manipulation', function() { }); it('fails the upsertWithWhere operation when data object is empty', function(done) { - var options = {}; + const options = {}; Person.upsertWithWhere({name: 'John Lennon'}, {}, options, function(err) { err.message.should.equal('data object cannot be empty!'); @@ -2567,7 +2567,7 @@ describe('manipulation', function() { }); function givenSomePeople(done) { - var beatles = [ + const beatles = [ {name: 'John Lennon', gender: 'male'}, {name: 'Paul McCartney', gender: 'male'}, {name: 'George Harrison', gender: 'male'}, diff --git a/test/memory.test.js b/test/memory.test.js index 3462ba87..8ff100d8 100644 --- a/test/memory.test.js +++ b/test/memory.test.js @@ -4,21 +4,21 @@ // License text available at https://opensource.org/licenses/MIT 'use strict'; -var jdb = require('../'); -var DataSource = jdb.DataSource; -var path = require('path'); -var fs = require('fs'); -var assert = require('assert'); -var async = require('async'); -var should = require('./init.js'); -var Memory = require('../lib/connectors/memory').Memory; +const jdb = require('../'); +const DataSource = jdb.DataSource; +const path = require('path'); +const fs = require('fs'); +const assert = require('assert'); +const async = require('async'); +const should = require('./init.js'); +const Memory = require('../lib/connectors/memory').Memory; describe('Memory connector', function() { - var file = path.join(__dirname, 'memory.json'); + const file = path.join(__dirname, 'memory.json'); function readModels(done) { fs.readFile(file, function(err, data) { - var json = JSON.parse(data.toString()); + const json = JSON.parse(data.toString()); assert(json.models); assert(json.ids.User); done(err, json); @@ -34,15 +34,15 @@ describe('Memory connector', function() { }); describe('with file', function() { - var ds; + let ds; function createUserModel() { - var ds = new DataSource({ + const ds = new DataSource({ connector: 'memory', file: file, }); - var User = ds.createModel('User', { + const User = ds.createModel('User', { id: { type: Number, id: true, @@ -57,8 +57,8 @@ describe('Memory connector', function() { return User; } - var User; - var ids = []; + let User; + const ids = []; before(function() { User = createUserModel(); @@ -73,7 +73,7 @@ describe('Memory connector', function() { }); it('should persist create', function(done) { - var count = 0; + let count = 0; async.eachSeries(['John1', 'John2', 'John3'], function(item, cb) { User.create({name: item}, function(err, result) { ids.push(result.id); @@ -95,8 +95,8 @@ describe('Memory connector', function() { it('should not have out of sequence read/write', function(done) { // Create the new data source with the same file to simulate // existing records - var User = createUserModel(); - var ds = User.dataSource; + const User = createUserModel(); + const ds = User.dataSource; async.times(10, function(n, next) { if (n === 10) { @@ -107,7 +107,7 @@ describe('Memory connector', function() { next(); }, function(err) { async.eachSeries(['John4', 'John5'], function(item, cb) { - var count = 0; + const count = 0; User.create({name: item}, function(err, result) { ids.push(result.id); cb(err); @@ -152,7 +152,7 @@ describe('Memory connector', function() { return done(err); } assert.equal(Object.keys(json.models.User).length, 4); - var user = JSON.parse(json.models.User[ids[1]]); + const user = JSON.parse(json.models.User[ids[1]]); assert.equal(user.name, 'John'); assert(user.id === ids[1]); done(); @@ -171,7 +171,7 @@ describe('Memory connector', function() { return done(err); } assert.equal(Object.keys(json.models.User).length, 4); - var user = JSON.parse(json.models.User[ids[1]]); + const user = JSON.parse(json.models.User[ids[1]]); assert.equal(user.name, 'John1'); assert(user.id === ids[1]); done(); @@ -190,11 +190,11 @@ describe('Memory connector', function() { }); describe('Query for memory connector', function() { - var ds = new DataSource({ + const ds = new DataSource({ connector: 'memory', }); - var User = ds.define('User', { + const User = ds.define('User', { seq: {type: Number, index: true}, name: {type: String, index: true, sort: true}, email: {type: String, index: true}, @@ -471,7 +471,7 @@ describe('Memory connector', function() { User.find({where: {seq: {neq: 4}}}, function(err, users) { should.not.exist(err); users.length.should.be.equal(5); - for (var i = 0; i < users.length; i++) { + for (let i = 0; i < users.length; i++) { users[i].seq.should.not.be.equal(4); } done(); @@ -482,7 +482,7 @@ describe('Memory connector', function() { User.find({where: {role: {neq: 'lead'}}}, function(err, users) { should.not.exist(err); users.length.should.be.equal(4); - for (var i = 0; i < users.length; i++) { + for (let i = 0; i < users.length; i++) { if (users[i].role) { users[i].role.not.be.equal('lead'); } @@ -495,7 +495,7 @@ describe('Memory connector', function() { User.find({where: {role: {neq: null}}}, function(err, users) { should.not.exist(err); users.length.should.be.equal(2); - for (var i = 0; i < users.length; i++) { + for (let i = 0; i < users.length; i++) { should.exist(users[i].role); } done(); @@ -554,7 +554,7 @@ describe('Memory connector', function() { }); function seed(done) { - var beatles = [ + const beatles = [ { seq: 0, name: 'John Lennon', @@ -616,19 +616,19 @@ describe('Memory connector', function() { }); it('should use collection setting', function(done) { - var ds = new DataSource({ + const ds = new DataSource({ connector: 'memory', }); - var Product = ds.createModel('Product', { + const Product = ds.createModel('Product', { name: String, }); - var Tool = ds.createModel('Tool', { + const Tool = ds.createModel('Tool', { name: String, }, {memory: {collection: 'Product'}}); - var Widget = ds.createModel('Widget', { + const Widget = ds.createModel('Widget', { name: String, }, {memory: {collection: 'Product'}}); @@ -658,8 +658,8 @@ describe('Memory connector', function() { }); it('should refuse to create object with duplicate id', function(done) { - var ds = new DataSource({connector: 'memory'}); - var Product = ds.define('ProductTest', {name: String}, {forceId: false}); + const ds = new DataSource({connector: 'memory'}); + const Product = ds.define('ProductTest', {name: String}, {forceId: false}); ds.automigrate('ProductTest', function(err) { if (err) return done(err); @@ -678,7 +678,7 @@ describe('Memory connector', function() { }); describe('automigrate', function() { - var ds; + let ds; beforeEach(function() { ds = new DataSource({ connector: 'memory', @@ -757,7 +757,7 @@ describe('Memory connector', function() { }); describe('findOrCreate', function() { - var ds, Cars; + let ds, Cars; before(function() { ds = new DataSource({connector: 'memory'}); Cars = ds.define('Cars', { @@ -766,10 +766,10 @@ describe('Memory connector', function() { }); it('should create a specific object once and in the subsequent calls it should find it', function(done) { - var creationNum = 0; + let creationNum = 0; async.times(100, function(n, next) { - var initialData = {color: 'white'}; - var query = {'where': initialData}; + const initialData = {color: 'white'}; + const query = {'where': initialData}; Cars.findOrCreate(query, initialData, function(err, car, created) { if (created) creationNum++; next(err, car); @@ -788,7 +788,7 @@ describe('Memory connector', function() { }); describe('automigrate when NO models are attached', function() { - var ds; + let ds; beforeEach(function() { ds = new DataSource({ connector: 'memory', @@ -811,7 +811,7 @@ describe('Memory connector', function() { }); describe('With mocked autoupdate', function() { - var ds, model; + let ds, model; beforeEach(function() { ds = new DataSource({ connector: 'memory', @@ -902,7 +902,7 @@ describe('Memory connector', function() { }); describe('Optimized connector', function() { - var ds = new DataSource({connector: Memory}); + const ds = new DataSource({connector: Memory}); require('./persistence-hooks.suite')(ds, should, { replaceOrCreateReportsNewInstance: true, @@ -910,7 +910,7 @@ describe('Optimized connector', function() { }); describe('Unoptimized connector', function() { - var ds = new DataSource({connector: Memory}); + const ds = new DataSource({connector: Memory}); // disable optimized methods ds.connector.updateOrCreate = false; @@ -923,7 +923,7 @@ describe('Unoptimized connector', function() { }); describe('Memory connector with options', function() { - var ds, savedOptions = {}, Post; + let ds, savedOptions = {}, Post; before(function() { ds = new DataSource({connector: 'memory'}); @@ -955,7 +955,7 @@ describe('Memory connector with options', function() { }); it('should receive options from the find method', function(done) { - var opts = {transaction: 'tx1'}; + const opts = {transaction: 'tx1'}; Post.find({where: {title: 't1'}}, opts, function(err, p) { savedOptions.find.should.be.eql(opts); done(err); @@ -963,7 +963,7 @@ describe('Memory connector with options', function() { }); it('should treat first object arg as filter for find', function(done) { - var filter = {title: 't1'}; + const filter = {title: 't1'}; Post.find(filter, function(err, p) { savedOptions.find.should.be.eql({}); done(err); @@ -971,7 +971,7 @@ describe('Memory connector with options', function() { }); it('should receive options from the create method', function(done) { - var opts = {transaction: 'tx3'}; + const opts = {transaction: 'tx3'}; Post.create({title: 't1', content: 'c1'}, opts, function(err, p) { savedOptions.create.should.be.eql(opts); done(err); @@ -979,7 +979,7 @@ describe('Memory connector with options', function() { }); it('should receive options from the update method', function(done) { - var opts = {transaction: 'tx4'}; + const opts = {transaction: 'tx4'}; Post.update({title: 't1'}, {content: 'c1 --> c2'}, opts, function(err, p) { savedOptions.update.should.be.eql(opts); @@ -989,7 +989,7 @@ describe('Memory connector with options', function() { }); describe('Memory connector with observers', function() { - var ds = new DataSource({ + const ds = new DataSource({ connector: 'memory', }); @@ -999,10 +999,10 @@ describe('Memory connector with observers', function() { }); it('should notify observers', function(done) { - var events = []; + const events = []; ds.connector.execute = function(command, params, options, cb) { - var self = this; - var context = {command: command, params: params, options: options}; + const self = this; + const context = {command: command, params: params, options: options}; self.notifyObserversOf('before execute', context, function(err) { process.nextTick(function() { if (err) return cb(err); diff --git a/test/mixins.test.js b/test/mixins.test.js index e0a8a0ff..8c20844f 100644 --- a/test/mixins.test.js +++ b/test/mixins.test.js @@ -5,21 +5,21 @@ // This test written in mocha+should.js 'use strict'; -var should = require('./init.js'); +const should = require('./init.js'); -var jdb = require('../'); -var ModelBuilder = jdb.ModelBuilder; -var DataSource = jdb.DataSource; -var Memory = require('../lib/connectors/memory'); +const jdb = require('../'); +const ModelBuilder = jdb.ModelBuilder; +const DataSource = jdb.DataSource; +const Memory = require('../lib/connectors/memory'); -var modelBuilder = new ModelBuilder(); -var mixins = modelBuilder.mixins; +const modelBuilder = new ModelBuilder(); +const mixins = modelBuilder.mixins; function timestamps(Model, options) { Model.defineProperty('createdAt', {type: Date}); Model.defineProperty('updatedAt', {type: Date}); - var originalBeforeSave = Model.beforeSave; + const originalBeforeSave = Model.beforeSave; Model.beforeSave = function(next, data) { Model.applyTimestamps(data, this.isNewRecord()); if (data.createdAt) { @@ -62,24 +62,24 @@ describe('Model class', function() { }); it('should apply a mixin class', function() { - var Address = modelBuilder.define('Address', { + const Address = modelBuilder.define('Address', { street: {type: 'string', required: true}, city: {type: 'string', required: true}, }); - var memory = new DataSource('mem', {connector: Memory}, modelBuilder); - var Item = memory.createModel('Item', {name: 'string'}, { + const memory = new DataSource('mem', {connector: Memory}, modelBuilder); + const Item = memory.createModel('Item', {name: 'string'}, { mixins: {Address: true}, }); - var properties = Item.definition.properties; + const properties = Item.definition.properties; properties.street.should.eql({type: String, required: true}); properties.city.should.eql({type: String, required: true}); }); it('should fail to apply an undefined mixin class', function() { - var memory = new DataSource('mem', {connector: Memory}, modelBuilder); + const memory = new DataSource('mem', {connector: Memory}, modelBuilder); function applyMixin() { memory.createModel('Item', {name: 'string'}, { mixins: {UndefinedMixin: true}, @@ -89,8 +89,8 @@ describe('Model class', function() { }); it('should apply mixins', function(done) { - var memory = new DataSource('mem', {connector: Memory}, modelBuilder); - var Item = memory.createModel('Item', {name: 'string'}, { + const memory = new DataSource('mem', {connector: Memory}, modelBuilder); + const Item = memory.createModel('Item', {name: 'string'}, { mixins: { TimeStamp: true, Demo: {value: true}, @@ -108,7 +108,7 @@ describe('Model class', function() { Item.multiMixin.foo.should.equal('bar'); Item.multiMixin.fox.should.equal('baz'); - var properties = Item.definition.properties; + const properties = Item.definition.properties; properties.createdAt.should.eql({type: Date}); properties.updatedAt.should.eql({type: Date}); @@ -121,8 +121,8 @@ describe('Model class', function() { }); it('should fail to apply undefined mixin', function() { - var memory = new DataSource('mem', {connector: Memory}, modelBuilder); - var Item = memory.createModel('Item', {name: 'string'}); + const memory = new DataSource('mem', {connector: Memory}, modelBuilder); + const Item = memory.createModel('Item', {name: 'string'}); function applyMixin() { Item.mixin('UndefinedMixin', {foo: 'bar'}); @@ -131,14 +131,14 @@ describe('Model class', function() { }); describe('#mixin()', function() { - var Person, Author, Address; + let Person, Author, Address; beforeEach(function() { Address = modelBuilder.define('Address', { street: {type: 'string', required: true}, city: {type: 'string', required: true}, }); - var memory = new DataSource('mem', {connector: Memory}, modelBuilder); + const memory = new DataSource('mem', {connector: Memory}, modelBuilder); Person = memory.createModel('Person', {name: 'string'}); Author = memory.createModel('Author', {name: 'string'}); }); diff --git a/test/model-builder.test.js b/test/model-builder.test.js index 90093195..58c4faab 100644 --- a/test/model-builder.test.js +++ b/test/model-builder.test.js @@ -8,7 +8,7 @@ const should = require('./init.js'); const juggler = require('../'); -var ModelBuilder = juggler.ModelBuilder; +const ModelBuilder = juggler.ModelBuilder; describe('ModelBuilder', () => { describe('define()', () => { diff --git a/test/model-definition.test.js b/test/model-definition.test.js index ac8de705..70f0250f 100644 --- a/test/model-definition.test.js +++ b/test/model-definition.test.js @@ -5,26 +5,26 @@ // This test written in mocha+should.js 'use strict'; -var should = require('./init.js'); -var assert = require('assert'); +const should = require('./init.js'); +const assert = require('assert'); -var jdb = require('../'); -var ModelBuilder = jdb.ModelBuilder; -var DataSource = jdb.DataSource; -var Memory = require('../lib/connectors/memory'); +const jdb = require('../'); +const ModelBuilder = jdb.ModelBuilder; +const DataSource = jdb.DataSource; +const Memory = require('../lib/connectors/memory'); -var ModelDefinition = require('../lib/model-definition'); +const ModelDefinition = require('../lib/model-definition'); describe('ModelDefinition class', function() { - var memory; + let memory; beforeEach(function() { memory = new DataSource({connector: Memory}); }); it('should be able to define plain models', function(done) { - var modelBuilder = new ModelBuilder(); + const modelBuilder = new ModelBuilder(); - var User = new ModelDefinition(modelBuilder, 'User', { + const User = new ModelDefinition(modelBuilder, 'User', { name: 'string', bio: ModelBuilder.Text, approved: Boolean, @@ -39,7 +39,7 @@ describe('ModelDefinition class', function() { assert.equal(User.properties.joinedAt.type, Date); assert.equal(User.properties.age.type, Number); - var json = User.toJSON(); + const json = User.toJSON(); assert.equal(json.name, 'User'); assert.equal(json.properties.name.type, 'String'); assert.equal(json.properties.bio.type, 'Text'); @@ -53,9 +53,9 @@ describe('ModelDefinition class', function() { }); it('should be able to define additional properties', function(done) { - var modelBuilder = new ModelBuilder(); + const modelBuilder = new ModelBuilder(); - var User = new ModelDefinition(modelBuilder, 'User', { + const User = new ModelDefinition(modelBuilder, 'User', { name: 'string', bio: ModelBuilder.Text, approved: Boolean, @@ -65,7 +65,7 @@ describe('ModelDefinition class', function() { User.build(); - var json = User.toJSON(); + let json = User.toJSON(); User.defineProperty('id', {type: 'number', id: true}); assert.equal(User.properties.name.type, String); @@ -83,9 +83,9 @@ describe('ModelDefinition class', function() { }); it('should be able to define nesting models', function(done) { - var modelBuilder = new ModelBuilder(); + const modelBuilder = new ModelBuilder(); - var User = new ModelDefinition(modelBuilder, 'User', { + const User = new ModelDefinition(modelBuilder, 'User', { name: String, bio: ModelBuilder.Text, approved: Boolean, @@ -107,7 +107,7 @@ describe('ModelDefinition class', function() { assert.equal(User.properties.age.type, Number); assert.equal(typeof User.properties.address.type, 'function'); - var json = User.toJSON(); + const json = User.toJSON(); assert.equal(json.name, 'User'); assert.equal(json.properties.name.type, 'String'); assert.equal(json.properties.bio.type, 'Text'); @@ -124,15 +124,15 @@ describe('ModelDefinition class', function() { }); it('should be able to define referencing models', function(done) { - var modelBuilder = new ModelBuilder(); + const modelBuilder = new ModelBuilder(); - var Address = modelBuilder.define('Address', { + const Address = modelBuilder.define('Address', { street: String, city: String, zipCode: String, state: String, }); - var User = new ModelDefinition(modelBuilder, 'User', { + const User = new ModelDefinition(modelBuilder, 'User', { name: String, bio: ModelBuilder.Text, approved: Boolean, @@ -150,7 +150,7 @@ describe('ModelDefinition class', function() { assert.equal(User.properties.age.type, Number); assert.equal(User.properties.address.type, Address); - var json = User.toJSON(); + const json = User.toJSON(); assert.equal(json.name, 'User'); assert.equal(json.properties.name.type, 'String'); assert.equal(json.properties.bio.type, 'Text'); @@ -164,15 +164,15 @@ describe('ModelDefinition class', function() { }); it('should be able to define referencing models by name', function(done) { - var modelBuilder = new ModelBuilder(); + const modelBuilder = new ModelBuilder(); - var Address = modelBuilder.define('Address', { + const Address = modelBuilder.define('Address', { street: String, city: String, zipCode: String, state: String, }); - var User = new ModelDefinition(modelBuilder, 'User', { + const User = new ModelDefinition(modelBuilder, 'User', { name: String, bio: ModelBuilder.Text, approved: Boolean, @@ -190,7 +190,7 @@ describe('ModelDefinition class', function() { assert.equal(User.properties.age.type, Number); assert.equal(User.properties.address.type, Address); - var json = User.toJSON(); + const json = User.toJSON(); assert.equal(json.name, 'User'); assert.equal(json.properties.name.type, 'String'); assert.equal(json.properties.bio.type, 'Text'); @@ -204,9 +204,9 @@ describe('ModelDefinition class', function() { }); it('should report correct id names', function(done) { - var modelBuilder = new ModelBuilder(); + const modelBuilder = new ModelBuilder(); - var User = new ModelDefinition(modelBuilder, 'User', { + const User = new ModelDefinition(modelBuilder, 'User', { userId: {type: String, id: true}, name: 'string', bio: ModelBuilder.Text, @@ -221,9 +221,9 @@ describe('ModelDefinition class', function() { }); it('should sort id properties by its index', function() { - var modelBuilder = new ModelBuilder(); + const modelBuilder = new ModelBuilder(); - var User = new ModelDefinition(modelBuilder, 'User', { + const User = new ModelDefinition(modelBuilder, 'User', { userId: {type: String, id: 2}, userType: {type: String, id: 1}, name: 'string', @@ -233,7 +233,7 @@ describe('ModelDefinition class', function() { age: 'number', }); - var ids = User.ids(); + const ids = User.ids(); assert.ok(Array.isArray(ids)); assert.equal(ids.length, 2); assert.equal(ids[0].id, 1); @@ -243,9 +243,9 @@ describe('ModelDefinition class', function() { }); it('should report correct table/column names', function(done) { - var modelBuilder = new ModelBuilder(); + const modelBuilder = new ModelBuilder(); - var User = new ModelDefinition(modelBuilder, 'User', { + const User = new ModelDefinition(modelBuilder, 'User', { userId: {type: String, id: true, oracle: {column: 'ID'}}, name: 'string', }, {oracle: {table: 'USER'}}); @@ -259,11 +259,11 @@ describe('ModelDefinition class', function() { describe('maxDepthOfQuery', function() { it('should report errors for deep query than maxDepthOfQuery', function(done) { - var MyModel = memory.createModel('my-model', {}, { + const MyModel = memory.createModel('my-model', {}, { maxDepthOfQuery: 5, }); - var filter = givenComplexFilter(); + const filter = givenComplexFilter(); MyModel.find(filter, function(err) { should.exist(err); @@ -273,11 +273,11 @@ describe('ModelDefinition class', function() { }); it('should honor maxDepthOfQuery setting', function(done) { - var MyModel = memory.createModel('my-model', {}, { + const MyModel = memory.createModel('my-model', {}, { maxDepthOfQuery: 20, }); - var filter = givenComplexFilter(); + const filter = givenComplexFilter(); MyModel.find(filter, function(err) { should.not.exist(err); @@ -286,11 +286,11 @@ describe('ModelDefinition class', function() { }); it('should honor maxDepthOfQuery in options', function(done) { - var MyModel = memory.createModel('my-model', {}, { + const MyModel = memory.createModel('my-model', {}, { maxDepthOfQuery: 5, }); - var filter = givenComplexFilter(); + const filter = givenComplexFilter(); MyModel.find(filter, {maxDepthOfQuery: 20}, function(err) { should.not.exist(err); @@ -299,28 +299,28 @@ describe('ModelDefinition class', function() { }); function givenComplexFilter() { - var filter = {where: {and: [{and: [{and: [{and: [{and: [{and: + const filter = {where: {and: [{and: [{and: [{and: [{and: [{and: [{and: [{and: [{and: [{x: 1}]}]}]}]}]}]}]}]}]}}; return filter; } }); it('should serialize protected properties into JSON', function() { - var ProtectedModel = memory.createModel('protected', {}, { + const ProtectedModel = memory.createModel('protected', {}, { protected: ['protectedProperty'], }); - var pm = new ProtectedModel({ + const pm = new ProtectedModel({ id: 1, foo: 'bar', protectedProperty: 'protected', }); - var serialized = pm.toJSON(); + const serialized = pm.toJSON(); assert.deepEqual(serialized, { id: 1, foo: 'bar', protectedProperty: 'protected', }); }); it('should not serialize protected properties of nested models into JSON', function(done) { - var Parent = memory.createModel('parent'); - var Child = memory.createModel('child', {}, {protected: ['protectedProperty']}); + const Parent = memory.createModel('parent'); + const Child = memory.createModel('child', {}, {protected: ['protectedProperty']}); Parent.hasMany(Child); Parent.create({ name: 'parent', @@ -333,8 +333,8 @@ describe('ModelDefinition class', function() { if (err) return done(err); Parent.find({include: 'children'}, function(err, parents) { if (err) return done(err); - var serialized = parents[0].toJSON(); - var child = serialized.children[0]; + const serialized = parents[0].toJSON(); + const child = serialized.children[0]; assert.equal(child.name, 'child'); assert.notEqual(child.protectedProperty, 'protectedValue'); done(); @@ -344,15 +344,15 @@ describe('ModelDefinition class', function() { }); it('should not serialize hidden properties into JSON', function() { - var HiddenModel = memory.createModel('hidden', {}, { + const HiddenModel = memory.createModel('hidden', {}, { hidden: ['secret'], }); - var hm = new HiddenModel({ + const hm = new HiddenModel({ id: 1, foo: 'bar', secret: 'secret', }); - var serialized = hm.toJSON(); + const serialized = hm.toJSON(); assert.deepEqual(serialized, { id: 1, foo: 'bar', @@ -360,8 +360,8 @@ describe('ModelDefinition class', function() { }); it('should not serialize hidden properties of nested models into JSON', function(done) { - var Parent = memory.createModel('parent'); - var Child = memory.createModel('child', {}, {hidden: ['secret']}); + const Parent = memory.createModel('parent'); + const Child = memory.createModel('child', {}, {hidden: ['secret']}); Parent.hasMany(Child); Parent.create({ name: 'parent', @@ -374,8 +374,8 @@ describe('ModelDefinition class', function() { if (err) return done(err); Parent.find({include: 'children'}, function(err, parents) { if (err) return done(err); - var serialized = parents[0].toJSON(); - var child = serialized.children[0]; + const serialized = parents[0].toJSON(); + const child = serialized.children[0]; assert.equal(child.name, 'child'); assert.notEqual(child.secret, 'secret'); done(); @@ -385,7 +385,7 @@ describe('ModelDefinition class', function() { }); describe('hidden properties', function() { - var Child; + let Child; describe('with hidden array', function() { beforeEach(function() { givenChildren(); }); @@ -493,7 +493,7 @@ describe('ModelDefinition class', function() { }; describe('hidden nested properties', function() { - var Child; + let Child; beforeEach(givenChildren); it('should be removed if used in where as a composite key - x.secret', function() { @@ -515,7 +515,7 @@ describe('ModelDefinition class', function() { }); function givenChildren() { - var hiddenProps = {hidden: ['secret']}; + const hiddenProps = {hidden: ['secret']}; Child = memory.createModel('child', { name: String, x: { @@ -555,8 +555,8 @@ describe('ModelDefinition class', function() { } describe('protected properties', function() { - var Parent; - var Child; + let Parent; + let Child; beforeEach(givenParentAndChild); it('should be removed if used in include scope', function() { @@ -614,8 +614,8 @@ describe('ModelDefinition class', function() { }); describe('hidden properties in include', function() { - var Parent; - var Child; + let Parent; + let Child; beforeEach(givenParentAndChildWithHiddenProperty); it('should be rejected if used in scope', function() { @@ -653,7 +653,7 @@ describe('ModelDefinition class', function() { }); it('should report deprecation warning for property named constructor', function() { - var message = 'deprecation not reported'; + let message = 'deprecation not reported'; process.once('deprecation', function(err) { message = err.message; }); memory.createModel('Ctor', {'constructor': String}); @@ -663,7 +663,7 @@ describe('ModelDefinition class', function() { it('should throw error for dynamic property names containing dot', function(done) { - var Model = memory.createModel('DynamicDotted'); + const Model = memory.createModel('DynamicDotted'); Model.create({'dot.name': 'dot.value'}, function(err) { err.should.be.instanceOf(Error); err.message.should.match(/dot\(s\).*DynamicDotted.*dot\.name/); @@ -672,7 +672,7 @@ describe('ModelDefinition class', function() { }); it('should throw error for dynamic property named constructor', function(done) { - var Model = memory.createModel('DynamicCtor'); + const Model = memory.createModel('DynamicCtor'); Model.create({'constructor': 'myCtor'}, function(err) { assert.equal(err.message, 'Property name "constructor" is not allowed in DynamicCtor data'); done(); @@ -680,18 +680,18 @@ describe('ModelDefinition class', function() { }); it('should support "array" type shortcut', function() { - var Model = memory.createModel('TwoArrays', { + const Model = memory.createModel('TwoArrays', { regular: Array, sugar: 'array', }); - var props = Model.definition.properties; + const props = Model.definition.properties; props.regular.type.should.equal(props.sugar.type); }); context('hasPK', function() { context('with primary key defined', function() { - var Todo; + let Todo; before(function prepModel() { Todo = new ModelDefinition(new ModelBuilder(), 'Todo', { content: 'string', @@ -709,7 +709,7 @@ describe('ModelDefinition class', function() { }); context('without primary key defined', function() { - var Todo; + let Todo; before(function prepModel() { Todo = new ModelDefinition(new ModelBuilder(), 'Todo', { content: 'string', diff --git a/test/model-inheritance.test.js b/test/model-inheritance.test.js index bb580170..1a2d5e71 100644 --- a/test/model-inheritance.test.js +++ b/test/model-inheritance.test.js @@ -74,7 +74,7 @@ describe('Model class inheritance', function() { }; // saving original getMergePolicy method - let originalGetMergePolicy = base.getMergePolicy; + const originalGetMergePolicy = base.getMergePolicy; // the injected getMergePolicy method captures the provided configureModelMerge option base.getMergePolicy = function(options) { @@ -154,9 +154,9 @@ describe('Model class inheritance', function() { }); it('allows model extension', function(done) { - var modelBuilder = new ModelBuilder(); + const modelBuilder = new ModelBuilder(); - var User = modelBuilder.define('User', { + const User = modelBuilder.define('User', { name: String, bio: ModelBuilder.Text, approved: Boolean, @@ -164,9 +164,9 @@ describe('Model class inheritance', function() { age: Number, }); - var Customer = User.extend('Customer', {customerId: {type: String, id: true}}); + const Customer = User.extend('Customer', {customerId: {type: String, id: true}}); - var customer = new Customer({name: 'Joe', age: 20, customerId: 'c01'}); + const customer = new Customer({name: 'Joe', age: 20, customerId: 'c01'}); customer.should.be.type('object').and.have.property('name', 'Joe'); customer.should.have.property('name', 'Joe'); @@ -179,8 +179,8 @@ describe('Model class inheritance', function() { // Remove internal properties return k.indexOf('__') === -1; }).length, 0); - var count = 0; - for (var p in customer.toObject()) { + let count = 0; + for (const p in customer.toObject()) { if (p.indexOf('__') === 0) { continue; } @@ -198,9 +198,9 @@ describe('Model class inheritance', function() { }); it('allows model extension with merged settings', function(done) { - var modelBuilder = new ModelBuilder(); + const modelBuilder = new ModelBuilder(); - var User = modelBuilder.define('User', { + const User = modelBuilder.define('User', { name: String, }, { defaultPermission: 'ALLOW', @@ -219,7 +219,7 @@ describe('Model class inheritance', function() { }, }); - var Customer = User.extend('Customer', + const Customer = User.extend('Customer', {customerId: {type: String, id: true}}, { defaultPermission: 'DENY', acls: [ diff --git a/test/normalize-undefined.test.js b/test/normalize-undefined.test.js index 4c594326..ae9d696f 100644 --- a/test/normalize-undefined.test.js +++ b/test/normalize-undefined.test.js @@ -4,23 +4,23 @@ // License text available at https://opensource.org/licenses/MIT 'use strict'; -var jdb = require('../'); -var DataSource = jdb.DataSource; -var path = require('path'); -var fs = require('fs'); -var assert = require('assert'); -var async = require('async'); -var should = require('./init.js'); -var Memory = require('../lib/connectors/memory').Memory; +const jdb = require('../'); +const DataSource = jdb.DataSource; +const path = require('path'); +const fs = require('fs'); +const assert = require('assert'); +const async = require('async'); +const should = require('./init.js'); +const Memory = require('../lib/connectors/memory').Memory; describe('normalizeUndefinedInQuery', function() { describe('with setting "throw"', function() { - var ds = new DataSource({ + const ds = new DataSource({ connector: 'memory', normalizeUndefinedInQuery: 'throw', }); - var User = ds.define('User', { + const User = ds.define('User', { seq: {type: Number, index: true}, name: {type: String, index: true, sort: true}, email: {type: String, index: true}, @@ -87,11 +87,11 @@ describe('normalizeUndefinedInQuery', function() { }); describe('with setting "nullify"', function() { - var ds = new DataSource({ + const ds = new DataSource({ connector: 'memory', }); - var User = ds.define('User', { + const User = ds.define('User', { seq: {type: Number, index: true}, name: {type: String, index: true, sort: true}, email: {type: String, index: true}, @@ -165,11 +165,11 @@ describe('normalizeUndefinedInQuery', function() { }); describe('with setting "ignore"', function() { - var ds = new DataSource({ + const ds = new DataSource({ connector: 'memory', }); - var User = ds.define('User', { + const User = ds.define('User', { seq: {type: Number, index: true}, name: {type: String, index: true, sort: true}, email: {type: String, index: true}, @@ -244,7 +244,7 @@ describe('normalizeUndefinedInQuery', function() { }); function seed(User, done) { - var beatles = [ + const beatles = [ { seq: 0, name: 'John Lennon', diff --git a/test/operation-hooks.suite/embeds-many-create.suite.js b/test/operation-hooks.suite/embeds-many-create.suite.js index f5f9b96d..91d846ea 100644 --- a/test/operation-hooks.suite/embeds-many-create.suite.js +++ b/test/operation-hooks.suite/embeds-many-create.suite.js @@ -5,18 +5,18 @@ 'use strict'; -var ValidationError = require('../..').ValidationError; +const ValidationError = require('../..').ValidationError; -var contextTestHelpers = require('../helpers/context-test-helpers'); -var ContextRecorder = contextTestHelpers.ContextRecorder; -var aCtxForModel = contextTestHelpers.aCtxForModel; +const contextTestHelpers = require('../helpers/context-test-helpers'); +const ContextRecorder = contextTestHelpers.ContextRecorder; +const aCtxForModel = contextTestHelpers.aCtxForModel; -var uid = require('../helpers/uid-generator'); -var HookMonitor = require('../helpers/hook-monitor'); +const uid = require('../helpers/uid-generator'); +const HookMonitor = require('../helpers/hook-monitor'); module.exports = function(dataSource, should, connectorCapabilities) { describe('EmbedsMany - create', function() { - var ctxRecorder, hookMonitor, expectedError; + let ctxRecorder, hookMonitor, expectedError; beforeEach(function setupHelpers() { ctxRecorder = new ContextRecorder('hook not called'); @@ -24,8 +24,8 @@ module.exports = function(dataSource, should, connectorCapabilities) { expectedError = new Error('test error'); }); - var Owner, Embedded, ownerInstance; - var migrated = false; + let Owner, Embedded, ownerInstance; + let migrated = false; beforeEach(function setupDatabase() { Embedded = dataSource.createModel('Embedded', { @@ -57,7 +57,7 @@ module.exports = function(dataSource, should, connectorCapabilities) { }); function callCreate() { - var item = new Embedded({name: 'created'}); + const item = new Embedded({name: 'created'}); return ownerInstance.embeddedList.create(item); } diff --git a/test/operation-hooks.suite/embeds-many-destroy.suite.js b/test/operation-hooks.suite/embeds-many-destroy.suite.js index c93a2494..30fef8fa 100644 --- a/test/operation-hooks.suite/embeds-many-destroy.suite.js +++ b/test/operation-hooks.suite/embeds-many-destroy.suite.js @@ -5,26 +5,26 @@ 'use strict'; -var ValidationError = require('../..').ValidationError; +const ValidationError = require('../..').ValidationError; -var contextTestHelpers = require('../helpers/context-test-helpers'); -var ContextRecorder = contextTestHelpers.ContextRecorder; -var aCtxForModel = contextTestHelpers.aCtxForModel; +const contextTestHelpers = require('../helpers/context-test-helpers'); +const ContextRecorder = contextTestHelpers.ContextRecorder; +const aCtxForModel = contextTestHelpers.aCtxForModel; -var uid = require('../helpers/uid-generator'); -var HookMonitor = require('../helpers/hook-monitor'); +const uid = require('../helpers/uid-generator'); +const HookMonitor = require('../helpers/hook-monitor'); module.exports = function(dataSource, should, connectorCapabilities) { describe('EmbedsMany - destroy', function() { - var ctxRecorder, hookMonitor, expectedError; + let ctxRecorder, hookMonitor, expectedError; beforeEach(function sharedSetup() { ctxRecorder = new ContextRecorder('hook not called'); hookMonitor = new HookMonitor({includeModelName: true}); expectedError = new Error('test error'); }); - var Owner, Embedded; - var migrated = false; + let Owner, Embedded; + let migrated = false; beforeEach(function setupDatabase() { Embedded = dataSource.createModel('Embedded', { // Set id.generated to false to honor client side values @@ -47,14 +47,14 @@ module.exports = function(dataSource, should, connectorCapabilities) { } }); - var ownerInstance, existingInstance, existingItem; + let ownerInstance, existingInstance, existingItem; beforeEach(function setupData() { return Owner.create({}) .then(function(inst) { ownerInstance = inst; }) .then(function() { - var item = new Embedded({name: 'created'}); + const item = new Embedded({name: 'created'}); return ownerInstance.embeddedList.create(item).then(function(it) { existingItem = it; }); diff --git a/test/operation-hooks.suite/embeds-many-update-by-id.suite.js b/test/operation-hooks.suite/embeds-many-update-by-id.suite.js index b696278b..605ed575 100644 --- a/test/operation-hooks.suite/embeds-many-update-by-id.suite.js +++ b/test/operation-hooks.suite/embeds-many-update-by-id.suite.js @@ -5,26 +5,26 @@ 'use strict'; -var ValidationError = require('../..').ValidationError; +const ValidationError = require('../..').ValidationError; -var contextTestHelpers = require('../helpers/context-test-helpers'); -var ContextRecorder = contextTestHelpers.ContextRecorder; -var aCtxForModel = contextTestHelpers.aCtxForModel; +const contextTestHelpers = require('../helpers/context-test-helpers'); +const ContextRecorder = contextTestHelpers.ContextRecorder; +const aCtxForModel = contextTestHelpers.aCtxForModel; -var uid = require('../helpers/uid-generator'); -var HookMonitor = require('../helpers/hook-monitor'); +const uid = require('../helpers/uid-generator'); +const HookMonitor = require('../helpers/hook-monitor'); module.exports = function(dataSource, should, connectorCapabilities) { describe('EmbedsMany - update', function() { - var ctxRecorder, hookMonitor, expectedError; + let ctxRecorder, hookMonitor, expectedError; beforeEach(function setupHelpers() { ctxRecorder = new ContextRecorder('hook not called'); hookMonitor = new HookMonitor({includeModelName: true}); expectedError = new Error('test error'); }); - var Owner, Embedded; - var migrated = false; + let Owner, Embedded; + let migrated = false; beforeEach(function setupDatabase() { Embedded = dataSource.createModel('Embedded', { // Set id.generated to false to honor client side values @@ -47,14 +47,14 @@ module.exports = function(dataSource, should, connectorCapabilities) { } }); - var ownerInstance, existingItem; + let ownerInstance, existingItem; beforeEach(function setupData() { return Owner.create({}) .then(function(inst) { ownerInstance = inst; }) .then(function() { - var item = new Embedded({name: 'created'}); + const item = new Embedded({name: 'created'}); return ownerInstance.embeddedList.create(item).then(function(it) { existingItem = it; }); diff --git a/test/operation-hooks.suite/embeds-one-create.suite.js b/test/operation-hooks.suite/embeds-one-create.suite.js index dc8ef457..eb41dd04 100644 --- a/test/operation-hooks.suite/embeds-one-create.suite.js +++ b/test/operation-hooks.suite/embeds-one-create.suite.js @@ -5,18 +5,18 @@ 'use strict'; -var ValidationError = require('../..').ValidationError; +const ValidationError = require('../..').ValidationError; -var contextTestHelpers = require('../helpers/context-test-helpers'); -var ContextRecorder = contextTestHelpers.ContextRecorder; -var aCtxForModel = contextTestHelpers.aCtxForModel; +const contextTestHelpers = require('../helpers/context-test-helpers'); +const ContextRecorder = contextTestHelpers.ContextRecorder; +const aCtxForModel = contextTestHelpers.aCtxForModel; -var uid = require('../helpers/uid-generator'); -var HookMonitor = require('../helpers/hook-monitor'); +const uid = require('../helpers/uid-generator'); +const HookMonitor = require('../helpers/hook-monitor'); module.exports = function(dataSource, should, connectorCapabilities) { describe('EmbedsOne - create', function() { - var ctxRecorder, hookMonitor, expectedError; + let ctxRecorder, hookMonitor, expectedError; beforeEach(function setupHelpers() { ctxRecorder = new ContextRecorder('hook not called'); @@ -24,8 +24,8 @@ module.exports = function(dataSource, should, connectorCapabilities) { expectedError = new Error('test error'); }); - var Owner, Embedded, ownerInstance; - var migrated = false; + let Owner, Embedded, ownerInstance; + let migrated = false; beforeEach(function setupDatabase() { Embedded = dataSource.createModel('Embedded', { @@ -57,7 +57,7 @@ module.exports = function(dataSource, should, connectorCapabilities) { }); function callCreate() { - var item = new Embedded({name: 'created'}); + const item = new Embedded({name: 'created'}); return ownerInstance.embeddedItem.create(item); } diff --git a/test/operation-hooks.suite/embeds-one-destroy.suite.js b/test/operation-hooks.suite/embeds-one-destroy.suite.js index a25ddc02..7d4cf110 100644 --- a/test/operation-hooks.suite/embeds-one-destroy.suite.js +++ b/test/operation-hooks.suite/embeds-one-destroy.suite.js @@ -5,26 +5,26 @@ 'use strict'; -var ValidationError = require('../..').ValidationError; +const ValidationError = require('../..').ValidationError; -var contextTestHelpers = require('../helpers/context-test-helpers'); -var ContextRecorder = contextTestHelpers.ContextRecorder; -var aCtxForModel = contextTestHelpers.aCtxForModel; +const contextTestHelpers = require('../helpers/context-test-helpers'); +const ContextRecorder = contextTestHelpers.ContextRecorder; +const aCtxForModel = contextTestHelpers.aCtxForModel; -var uid = require('../helpers/uid-generator'); -var HookMonitor = require('../helpers/hook-monitor'); +const uid = require('../helpers/uid-generator'); +const HookMonitor = require('../helpers/hook-monitor'); module.exports = function(dataSource, should, connectorCapabilities) { describe('EmbedsOne - destroy', function() { - var ctxRecorder, hookMonitor, expectedError; + let ctxRecorder, hookMonitor, expectedError; beforeEach(function sharedSetup() { ctxRecorder = new ContextRecorder('hook not called'); hookMonitor = new HookMonitor({includeModelName: true}); expectedError = new Error('test error'); }); - var Owner, Embedded; - var migrated = false; + let Owner, Embedded; + let migrated = false; beforeEach(function setupDatabase() { Embedded = dataSource.createModel('Embedded', { // Set id.generated to false to honor client side values @@ -47,14 +47,14 @@ module.exports = function(dataSource, should, connectorCapabilities) { } }); - var ownerInstance, existingInstance, existingItem; + let ownerInstance, existingInstance, existingItem; beforeEach(function setupData() { return Owner.create({}) .then(function(inst) { ownerInstance = inst; }) .then(function() { - var item = new Embedded({name: 'created'}); + const item = new Embedded({name: 'created'}); return ownerInstance.embeddedItem.create(item).then(function(it) { existingItem = it; }); diff --git a/test/operation-hooks.suite/embeds-one-update.suite.js b/test/operation-hooks.suite/embeds-one-update.suite.js index dbf3342c..3a1b4c4b 100644 --- a/test/operation-hooks.suite/embeds-one-update.suite.js +++ b/test/operation-hooks.suite/embeds-one-update.suite.js @@ -5,26 +5,26 @@ 'use strict'; -var ValidationError = require('../..').ValidationError; +const ValidationError = require('../..').ValidationError; -var contextTestHelpers = require('../helpers/context-test-helpers'); -var ContextRecorder = contextTestHelpers.ContextRecorder; -var aCtxForModel = contextTestHelpers.aCtxForModel; +const contextTestHelpers = require('../helpers/context-test-helpers'); +const ContextRecorder = contextTestHelpers.ContextRecorder; +const aCtxForModel = contextTestHelpers.aCtxForModel; -var uid = require('../helpers/uid-generator'); -var HookMonitor = require('../helpers/hook-monitor'); +const uid = require('../helpers/uid-generator'); +const HookMonitor = require('../helpers/hook-monitor'); module.exports = function(dataSource, should, connectorCapabilities) { describe('EmbedsOne - update', function() { - var ctxRecorder, hookMonitor, expectedError; + let ctxRecorder, hookMonitor, expectedError; beforeEach(function setupHelpers() { ctxRecorder = new ContextRecorder('hook not called'); hookMonitor = new HookMonitor({includeModelName: true}); expectedError = new Error('test error'); }); - var Owner, Embedded; - var migrated = false; + let Owner, Embedded; + let migrated = false; beforeEach(function setupDatabase() { Embedded = dataSource.createModel('Embedded', { // Set id.generated to false to honor client side values @@ -47,14 +47,14 @@ module.exports = function(dataSource, should, connectorCapabilities) { } }); - var ownerInstance, existingItem; + let ownerInstance, existingItem; beforeEach(function setupData() { return Owner.create({}) .then(function(inst) { ownerInstance = inst; }) .then(function() { - var item = new Embedded({name: 'created'}); + const item = new Embedded({name: 'created'}); return ownerInstance.embeddedItem.create(item).then(function(it) { existingItem = it; }); diff --git a/test/operation-hooks.suite/index.js b/test/operation-hooks.suite/index.js index 3f43346d..5fd174ff 100644 --- a/test/operation-hooks.suite/index.js +++ b/test/operation-hooks.suite/index.js @@ -1,18 +1,18 @@ 'use strict'; -var debug = require('debug')('test'); -var fs = require('fs'); -var path = require('path'); +const debug = require('debug')('test'); +const fs = require('fs'); +const path = require('path'); module.exports = function(dataSource, should, connectorCapabilities) { - var operations = fs.readdirSync(__dirname); + let operations = fs.readdirSync(__dirname); operations = operations.filter(function(it) { return it !== path.basename(__filename) && !!require.extensions[path.extname(it).toLowerCase()]; }); - for (var ix in operations) { - var name = operations[ix]; - var fullPath = require.resolve('./' + name); + for (const ix in operations) { + const name = operations[ix]; + const fullPath = require.resolve('./' + name); debug('Loading test suite %s (%s)', name, fullPath); require(fullPath).apply(this, arguments); } diff --git a/test/optional-validation.test.js b/test/optional-validation.test.js index 74614280..1f09a419 100644 --- a/test/optional-validation.test.js +++ b/test/optional-validation.test.js @@ -7,16 +7,16 @@ 'use strict'; /* global getSchema:false */ -var async = require('async'); -var should = require('./init.js'); -var db, User, options, ModelWithForceId, whereCount = 0; -var j = require('../'); -var ValidationError = j.ValidationError; +const async = require('async'); +const should = require('./init.js'); +let db, User, options, ModelWithForceId, whereCount = 0; +const j = require('../'); +const ValidationError = j.ValidationError; -var INITIAL_NAME = 'Bert'; -var NEW_NAME = 'Ernie'; -var INVALID_DATA = {name: null}; -var VALID_DATA = {name: INITIAL_NAME}; +const INITIAL_NAME = 'Bert'; +const NEW_NAME = 'Ernie'; +const INVALID_DATA = {name: null}; +const VALID_DATA = {name: INITIAL_NAME}; describe('optional-validation', function() { before(function(done) { @@ -103,7 +103,7 @@ describe('optional-validation', function() { function callUpdateOrCreateWithExistingUserId(name, options, cb) { User.create({'name': 'Groover'}, function(err, user) { if (err) return cb(err); - var data = {name: name}; + const data = {name: name}; data.id = user.id; User.updateOrCreate(data, options, cb); }); diff --git a/test/persistence-hooks.suite.js b/test/persistence-hooks.suite.js index babc6914..398e2a95 100644 --- a/test/persistence-hooks.suite.js +++ b/test/persistence-hooks.suite.js @@ -4,35 +4,35 @@ // License text available at https://opensource.org/licenses/MIT 'use strict'; -var ValidationError = require('../').ValidationError; +const ValidationError = require('../').ValidationError; -var async = require('async'); -var contextTestHelpers = require('./helpers/context-test-helpers'); -var ContextRecorder = contextTestHelpers.ContextRecorder; -var deepCloneToObject = contextTestHelpers.deepCloneToObject; -var aCtxForModel = contextTestHelpers.aCtxForModel; -var GeoPoint = require('../lib/geo.js').GeoPoint; +const async = require('async'); +const contextTestHelpers = require('./helpers/context-test-helpers'); +const ContextRecorder = contextTestHelpers.ContextRecorder; +const deepCloneToObject = contextTestHelpers.deepCloneToObject; +const aCtxForModel = contextTestHelpers.aCtxForModel; +const GeoPoint = require('../lib/geo.js').GeoPoint; -var uid = require('./helpers/uid-generator'); -var getLastGeneratedUid = uid.last; +const uid = require('./helpers/uid-generator'); +const getLastGeneratedUid = uid.last; -var HookMonitor = require('./helpers/hook-monitor'); -var isNewInstanceFlag; +const HookMonitor = require('./helpers/hook-monitor'); +let isNewInstanceFlag; module.exports = function(dataSource, should, connectorCapabilities) { isNewInstanceFlag = connectorCapabilities.replaceOrCreateReportsNewInstance; if (!connectorCapabilities) connectorCapabilities = {}; if (isNewInstanceFlag === undefined) { - var warn = 'The connector does not support a recently added feature:' + + const warn = 'The connector does not support a recently added feature:' + ' replaceOrCreateReportsNewInstance'; console.warn(warn); } describe('Persistence hooks', function() { - var ctxRecorder, hookMonitor, expectedError; - var TestModel, existingInstance, GeoModel; - var migrated = false; + let ctxRecorder, hookMonitor, expectedError; + let TestModel, existingInstance, GeoModel; + let migrated = false; - var undefinedValue = undefined; + let undefinedValue = undefined; beforeEach(function setupDatabase(done) { ctxRecorder = new ContextRecorder('hook not called'); @@ -82,8 +82,8 @@ module.exports = function(dataSource, should, connectorCapabilities) { TestModel.create({name: 'second'}, function(err) { if (err) return done(err); - var location1 = new GeoPoint({lat: 10.2, lng: 6.7}); - var location2 = new GeoPoint({lat: 10.3, lng: 6.8}); + const location1 = new GeoPoint({lat: 10.2, lng: 6.7}); + const location2 = new GeoPoint({lat: 10.3, lng: 6.8}); GeoModel.create([ {name: 'Rome', location: location1}, {name: 'Tokyo', location: location2}, @@ -143,7 +143,7 @@ module.exports = function(dataSource, should, connectorCapabilities) { it('triggers the loaded hook multiple times when multiple instances exist when near filter is used', function(done) { - var hookMonitorGeoModel; + let hookMonitorGeoModel; hookMonitorGeoModel = new HookMonitor({includeModelName: false}); function monitorHookExecutionGeoModel(hookNames) { @@ -152,7 +152,7 @@ module.exports = function(dataSource, should, connectorCapabilities) { monitorHookExecutionGeoModel(); - var query = { + const query = { where: {location: {near: '10,5'}}, }; GeoModel.find(query, function(err, list) { @@ -170,7 +170,7 @@ module.exports = function(dataSource, should, connectorCapabilities) { next(); }); - var query = { + const query = { where: {location: {near: '10,5'}}, }; @@ -191,7 +191,7 @@ module.exports = function(dataSource, should, connectorCapabilities) { next(); }); - var query = { + const query = { where: {location: {near: '10,5'}}, }; @@ -1325,7 +1325,7 @@ module.exports = function(dataSource, should, connectorCapabilities) { // The rationale behind passing { persisted: true } is to bypass the check // made by DAO to determine whether the instance should be saved via // PersistedModel.create and force it to call connector.save() - var instance = new TestModel( + const instance = new TestModel( {id: 'new-id', name: 'created'}, {persisted: true} ); @@ -1391,7 +1391,7 @@ module.exports = function(dataSource, should, connectorCapabilities) { it('triggers `before save` hook', function(done) { TestModel.observe('before save', ctxRecorder.recordAndNext()); - var currentInstance = deepCloneToObject(existingInstance); + const currentInstance = deepCloneToObject(existingInstance); existingInstance.updateAttributes({name: 'changed'}, function(err) { if (err) return done(err); @@ -1494,13 +1494,13 @@ module.exports = function(dataSource, should, connectorCapabilities) { }); it('applies updates from `persist` hook - for nested model instance', function(done) { - var Address = dataSource.createModel('NestedAddress', { + const Address = dataSource.createModel('NestedAddress', { id: {type: String, id: true, default: 1}, city: {type: String, required: true}, country: {type: String, required: true}, }); - var User = dataSource.createModel('UserWithAddress', { + const User = dataSource.createModel('UserWithAddress', { id: {type: String, id: true, default: uid.next}, name: {type: String, required: true}, address: {type: Address, required: false}, @@ -1512,7 +1512,7 @@ module.exports = function(dataSource, should, connectorCapabilities) { User.create({name: 'Joe'}, function(err, instance) { if (err) return done(err); - var existingUser = instance; + const existingUser = instance; User.observe('persist', ctxRecorder.recordAndNext(function(ctx) { should.exist(ctx.data.address); @@ -1762,13 +1762,13 @@ module.exports = function(dataSource, should, connectorCapabilities) { }); it('applies updates from `persist` hook - for nested model instance', function(done) { - var Address = dataSource.createModel('NestedAddress', { + const Address = dataSource.createModel('NestedAddress', { id: {type: String, id: true, default: 1}, city: {type: String, required: true}, country: {type: String, required: true}, }); - var User = dataSource.createModel('UserWithAddress', { + const User = dataSource.createModel('UserWithAddress', { id: {type: String, id: true, default: uid.next}, name: {type: String, required: true}, address: {type: Address, required: false}, @@ -1780,7 +1780,7 @@ module.exports = function(dataSource, should, connectorCapabilities) { User.create({name: 'Joe'}, function(err, instance) { if (err) return done(err); - var existingUser = instance; + const existingUser = instance; User.observe('persist', ctxRecorder.recordAndNext(function(ctx) { should.exist(ctx.data.address); @@ -2215,7 +2215,7 @@ module.exports = function(dataSource, should, connectorCapabilities) { function(err, instance) { if (err) return done(err); - var expectedContext = aCtxForModel(TestModel, { + const expectedContext = aCtxForModel(TestModel, { where: {id: existingInstance.id}, data: { id: existingInstance.id, @@ -2504,7 +2504,7 @@ module.exports = function(dataSource, should, connectorCapabilities) { if (err) return done(err); - var expectedContext = aCtxForModel(TestModel, { + const expectedContext = aCtxForModel(TestModel, { instance: instance, }); @@ -2522,7 +2522,7 @@ module.exports = function(dataSource, should, connectorCapabilities) { function(err, instance) { if (err) return done(err); - var expectedContext = aCtxForModel(TestModel, { + const expectedContext = aCtxForModel(TestModel, { instance: { id: existingInstance.id, name: 'replaced name', @@ -2548,7 +2548,7 @@ module.exports = function(dataSource, should, connectorCapabilities) { function(err, instance) { if (err) return done(err); - var expectedContext = aCtxForModel(TestModel, { + const expectedContext = aCtxForModel(TestModel, { instance: { id: 'new-id', name: 'a name', @@ -2603,7 +2603,7 @@ module.exports = function(dataSource, should, connectorCapabilities) { function(err, instance) { if (err) return done(err); - var expectedContext = aCtxForModel(TestModel, { + const expectedContext = aCtxForModel(TestModel, { currentInstance: { id: 'new-id', name: 'a name', @@ -2637,7 +2637,7 @@ module.exports = function(dataSource, should, connectorCapabilities) { function(err, instance) { if (err) return done(err); - var expected = { + const expected = { where: {id: existingInstance.id}, data: { id: existingInstance.id, @@ -2650,7 +2650,7 @@ module.exports = function(dataSource, should, connectorCapabilities) { }, }; - var expectedContext = aCtxForModel(TestModel, expected); + const expectedContext = aCtxForModel(TestModel, expected); if (!dataSource.connector.replaceOrCreate) { expectedContext.isNewInstance = false; @@ -2718,7 +2718,7 @@ module.exports = function(dataSource, should, connectorCapabilities) { function(err, instance) { if (err) return done(err); - var expected = { + const expected = { data: { id: 'new-id', name: 'a name', @@ -2743,7 +2743,7 @@ module.exports = function(dataSource, should, connectorCapabilities) { function(err, instance) { if (err) return done(err); - var expected = { + const expected = { data: { id: existingInstance.id, name: 'replaced name', @@ -2779,7 +2779,7 @@ module.exports = function(dataSource, should, connectorCapabilities) { function(err, instance) { if (err) return done(err); - var expected = { + const expected = { instance: { id: existingInstance.id, name: 'replaced name', @@ -2805,7 +2805,7 @@ module.exports = function(dataSource, should, connectorCapabilities) { function(err, instance) { if (err) return done(err); - var expected = { + const expected = { instance: { id: instance.id, name: 'a name', @@ -3498,7 +3498,7 @@ module.exports = function(dataSource, should, connectorCapabilities) { {id: existingInstance.id, name: 'updated name'}, function(err, instance) { if (err) return done(err); - var expectedContext = aCtxForModel(TestModel, { + const expectedContext = aCtxForModel(TestModel, { where: {id: existingInstance.id}, data: { id: existingInstance.id, @@ -3525,7 +3525,7 @@ module.exports = function(dataSource, should, connectorCapabilities) { {id: 'new-id', name: 'a name'}, function(err, instance) { if (err) return done(err); - var expectedContext = aCtxForModel(TestModel, {}); + const expectedContext = aCtxForModel(TestModel, {}); if (dataSource.connector.upsertWithWhere) { expectedContext.data = {id: 'new-id', name: 'a name'}; @@ -3607,7 +3607,7 @@ module.exports = function(dataSource, should, connectorCapabilities) { function(err, instance) { if (err) return done(err); - var expectedContext = aCtxForModel(TestModel, { + const expectedContext = aCtxForModel(TestModel, { data: {id: 'new-id', name: 'a name'}, currentInstance: { id: 'new-id', @@ -3633,7 +3633,7 @@ module.exports = function(dataSource, should, connectorCapabilities) { {id: existingInstance.id, name: 'updated name'}, function(err, instance) { if (err) return done(err); - var expectedContext = aCtxForModel(TestModel, { + const expectedContext = aCtxForModel(TestModel, { where: {id: existingInstance.id}, data: { id: existingInstance.id, @@ -3675,7 +3675,7 @@ module.exports = function(dataSource, should, connectorCapabilities) { {id: existingInstance.id, name: 'updated name'}, function(err, instance) { if (err) return done(err); - var expectedContext = aCtxForModel(TestModel, { + const expectedContext = aCtxForModel(TestModel, { data: { id: existingInstance.id, name: 'updated name', diff --git a/test/relations.test.js b/test/relations.test.js index 7839bb3d..5bd3b5f2 100644 --- a/test/relations.test.js +++ b/test/relations.test.js @@ -7,25 +7,25 @@ 'use strict'; /* global getSchema:false, connectorCapabilities:false */ -var assert = require('assert'); -var bdd = require('./helpers/bdd-if'); -var should = require('./init.js'); -var uid = require('./helpers/uid-generator'); -var jdb = require('../'); -var DataSource = jdb.DataSource; -var createPromiseCallback = require('../lib/utils.js').createPromiseCallback; +const assert = require('assert'); +const bdd = require('./helpers/bdd-if'); +const should = require('./init.js'); +const uid = require('./helpers/uid-generator'); +const jdb = require('../'); +const DataSource = jdb.DataSource; +const createPromiseCallback = require('../lib/utils.js').createPromiseCallback; -var db, tmp, Book, Chapter, Author, Reader, Article, Employee; -var Category, Job; -var Picture, PictureLink; -var Person, Address; -var Link; +let db, tmp, Book, Chapter, Author, Reader, Article, Employee; +let Category, Job; +let Picture, PictureLink; +let Person, Address; +let Link; -var getTransientDataSource = function(settings) { +const getTransientDataSource = function(settings) { return new DataSource('transient', settings, db.modelBuilder); }; -var getMemoryDataSource = function(settings) { +const getMemoryDataSource = function(settings) { return new DataSource('memory', settings, db.modelBuilder); }; @@ -49,7 +49,7 @@ describe('relations', function() { Book.hasMany(Chapter); Book.hasMany(Reader, {as: 'users'}); Book.hasMany(Author, {foreignKey: 'projectId'}); - var b = new Book; + const b = new Book; b.chapters.should.be.an.instanceOf(Function); b.users.should.be.an.instanceOf(Function); b.authors.should.be.an.instanceOf(Function); @@ -77,8 +77,8 @@ describe('relations', function() { it('should build record on scope', function(done) { Book.create(function(err, book) { - var chaps = book.chapters; - var c = chaps.build(); + const chaps = book.chapters; + const c = chaps.build(); c.bookId.should.eql(book.id); c.save(done); }); @@ -124,7 +124,7 @@ describe('relations', function() { }); it('should create a batch of records on scope', function(done) { - var chapters = [ + const chapters = [ {name: 'a'}, {name: 'z'}, {name: 'c'}, @@ -143,7 +143,7 @@ describe('relations', function() { }); it('should create a batch of records on scope with promises', function(done) { - var chapters = [ + const chapters = [ {name: 'a'}, {name: 'z'}, {name: 'c'}, @@ -177,14 +177,14 @@ describe('relations', function() { should.exist(ch); ch.should.have.lengthOf(3); - var chapters = book.chapters(); + const chapters = book.chapters(); chapters.should.eql(ch); book.chapters(function(e, c) { should.not.exist(e); should.exist(c); ch.should.have.lengthOf(3); - var acz = ['a', 'c', 'z']; + const acz = ['a', 'c', 'z']; acz.should.containEql(c[0].name); acz.should.containEql(c[1].name); acz.should.containEql(c[2].name); @@ -214,13 +214,13 @@ describe('relations', function() { .then(function(ch) { should.exist(ch); ch.should.have.lengthOf(3); - var chapters = book.chapters(); + const chapters = book.chapters(); chapters.should.eql(ch); return book.chapters.find() .then(function(c) { should.exist(c); ch.should.have.lengthOf(3); - var acz = ['a', 'c', 'z']; + const acz = ['a', 'c', 'z']; acz.should.containEql(c[0].name); acz.should.containEql(c[1].name); acz.should.containEql(c[2].name); @@ -246,13 +246,13 @@ describe('relations', function() { should.exist(ch); ch.should.have.lengthOf(3); - var chapters = book.chapters(); + const chapters = book.chapters(); chapters.should.eql(ch); book.chapters.find(function(e, c) { should.not.exist(e); should.exist(c); ch.should.have.lengthOf(3); - var acz = ['a', 'c', 'z']; + const acz = ['a', 'c', 'z']; acz.should.containEql(c[0].name); acz.should.containEql(c[1].name); acz.should.containEql(c[2].name); @@ -278,7 +278,7 @@ describe('relations', function() { should.exist(ch); ch.should.have.lengthOf(3); - var chapters = book.chapters(); + const chapters = book.chapters(); chapters.should.eql(ch); book.chapters.find(function(e, c) { @@ -286,7 +286,7 @@ describe('relations', function() { should.exist(c); should.exist(c.length); c.should.have.lengthOf(3); - var acz = ['a', 'c', 'z']; + const acz = ['a', 'c', 'z']; acz.should.containEql(c[0].name); acz.should.containEql(c[1].name); acz.should.containEql(c[2].name); @@ -297,7 +297,7 @@ describe('relations', function() { }); it('should find scoped record', function(done) { - var id; + let id; Book.create(function(err, book) { book.chapters.create({name: 'a'}, function(err, ch) { id = ch.id; @@ -320,7 +320,7 @@ describe('relations', function() { }); it('should find scoped record with promises', function(done) { - var id; + let id; Book.create() .then(function(book) { return book.chapters.create({name: 'a'}) @@ -403,7 +403,7 @@ describe('relations', function() { }); it('should update scoped record', function(done) { - var id; + let id; Book.create(function(err, book) { book.chapters.create({name: 'a'}, function(err, ch) { id = ch.id; @@ -425,7 +425,7 @@ describe('relations', function() { }); it('should update scoped record with promises', function(done) { - var id; + let id; Book.create() .then(function(book) { return book.chapters.create({name: 'a'}) @@ -451,7 +451,7 @@ describe('relations', function() { }); it('should destroy scoped record', function(done) { - var id; + let id; Book.create(function(err, book) { book.chapters.create({name: 'a'}, function(err, ch) { id = ch.id; @@ -470,7 +470,7 @@ describe('relations', function() { }); it('should destroy scoped record with promises', function(done) { - var id; + let id; Book.create() .then(function(book) { return book.chapters.create({name: 'a'}) @@ -494,7 +494,7 @@ describe('relations', function() { }); it('should check existence of a scoped record', function(done) { - var id; + let id; Book.create(function(err, book) { book.chapters.create({name: 'a'}, function(err, ch) { id = ch.id; @@ -516,7 +516,7 @@ describe('relations', function() { }); it('should check existence of a scoped record with promises', function(done) { - var id; + let id; Book.create() .then(function(book) { return book.chapters.create({name: 'a'}) @@ -545,7 +545,7 @@ describe('relations', function() { Book.create({chapters: []}, function(err, book) { if (err) return done(err); book.chapters.should.be.a.function; - var obj = book.toObject(); + const obj = book.toObject(); should.not.exist(obj.chapters); done(); }); @@ -555,7 +555,7 @@ describe('relations', function() { Book.create({chapters: []}) .then(function(book) { book.chapters.should.be.a.function; - var obj = book.toObject(); + const obj = book.toObject(); should.not.exist(obj.chapters); done(); }).catch(done); @@ -565,7 +565,7 @@ describe('relations', function() { Book.create({chapters: {}}, function(err, book) { if (err) return done(err); book.chapters.should.be.a.function; - var obj = book.toObject(); + const obj = book.toObject(); should.not.exist(obj.chapters); done(); }); @@ -575,7 +575,7 @@ describe('relations', function() { Book.create({chapters: {}}) .then(function(book) { book.chapters.should.be.a.function; - var obj = book.toObject(); + const obj = book.toObject(); should.not.exist(obj.chapters); done(); }).catch(done); @@ -584,7 +584,7 @@ describe('relations', function() { }); describe('hasMany through', function() { - var Physician, Patient, Appointment, Address; + let Physician, Patient, Appointment, Address; before(function(done) { Physician = db.define('Physician', {name: String}); @@ -607,7 +607,7 @@ describe('relations', function() { it('should build record on scope', function(done) { Physician.create(function(err, physician) { - var patient = physician.patients.build(); + const patient = physician.patients.build(); patient.physicianId.should.eql(physician.id); patient.save(done); }); @@ -644,7 +644,7 @@ describe('relations', function() { }); it('should create multiple records on scope', function(done) { - var async = require('async'); + const async = require('async'); Physician.create(function(err, physician) { physician.patients.create([{}, {}], function(err, patients) { if (err) return done(err); @@ -667,7 +667,7 @@ describe('relations', function() { }); it('should create multiple records on scope with promises', function(done) { - var async = require('async'); + const async = require('async'); Physician.create() .then(function(physician) { return physician.patients.create([{}, {}]) @@ -701,7 +701,7 @@ describe('relations', function() { }); function verify(physician) { physician.patients(function(err, ch) { - var patients = physician.patients(); + const patients = physician.patients(); patients.should.eql(ch); if (err) return done(err); @@ -729,7 +729,7 @@ describe('relations', function() { function verify(physician) { return physician.patients.find() .then(function(ch) { - var patients = physician.patients(); + const patients = physician.patients(); should.equal(patients, ch); should.exist(ch); @@ -740,8 +740,8 @@ describe('relations', function() { }); describe('fetch scoped instances with paging filters', function() { - var samplePatientId; - var physician; + let samplePatientId; + let physician; beforeEach(createSampleData); @@ -760,7 +760,7 @@ describe('relations', function() { }); context('with filter order', function() { it('orders the result by patient name', function(done) { - var filter = connectorCapabilities.adhocSort !== false ? {order: 'name DESC'} : {}; + const filter = connectorCapabilities.adhocSort !== false ? {order: 'name DESC'} : {}; physician.patients(filter, function(err, ch) { if (err) return done(err); should.exist(ch); @@ -770,7 +770,7 @@ describe('relations', function() { ch[1].name.should.eql('c'); ch[2].name.should.eql('a'); } else { - var acz = ['a', 'c', 'z']; + const acz = ['a', 'c', 'z']; ch[0].name.should.be.oneOf(acz); ch[1].name.should.be.oneOf(acz); ch[2].name.should.be.oneOf(acz); @@ -796,7 +796,7 @@ describe('relations', function() { }); context('with filter fields', function() { it('includes field \'name\' but not \'age\'', function(done) { - var fieldsFilter = { + const fieldsFilter = { fields: {name: true, age: false}, order: 'sequence', }; @@ -816,7 +816,7 @@ describe('relations', function() { }); context('with filter include', function() { it('returns physicians included in patient', function(done) { - var includeFilter = {include: 'physicians'}; + const includeFilter = {include: 'physicians'}; physician.patients(includeFilter, function(err, ch) { if (err) return done(err); ch.should.have.lengthOf(3); @@ -827,7 +827,7 @@ describe('relations', function() { }); context('with filter where', function() { it('returns patient where id equal to samplePatientId', function(done) { - var whereFilter = {where: {id: samplePatientId}}; + const whereFilter = {where: {id: samplePatientId}}; physician.patients(whereFilter, function(err, ch) { if (err) return done(err); should.exist(ch); @@ -837,7 +837,7 @@ describe('relations', function() { }); }); it('returns patient where name equal to samplePatient name', function(done) { - var whereFilter = {where: {name: 'a'}}; + const whereFilter = {where: {name: 'a'}}; physician.patients(whereFilter, function(err, ch) { if (err) return done(err); should.exist(ch); @@ -847,8 +847,8 @@ describe('relations', function() { }); }); it('returns patients where id in an array', function(done) { - var idArr = []; - var whereFilter; + const idArr = []; + let whereFilter; physician.patients.create({name: 'b'}, function(err, p) { idArr.push(samplePatientId, p.id); whereFilter = {where: {id: {inq: idArr}}}; @@ -875,7 +875,7 @@ describe('relations', function() { if (err) return done(err); should.exist(p); - var wrongWhereFilter = {where: {id: p.id}}; + const wrongWhereFilter = {where: {id: p.id}}; physician.patients(wrongWhereFilter, function(err, ch) { if (err) return done(err); should.exist(ch); @@ -888,7 +888,7 @@ describe('relations', function() { context('findById with filter include', function() { it('returns patient where id equal to \'samplePatientId\'' + 'with included physicians', function(done) { - var includeFilter = {include: 'physicians'}; + const includeFilter = {include: 'physicians'}; physician.patients.findById(samplePatientId, includeFilter, function(err, ch) { if (err) return done(err); @@ -902,7 +902,7 @@ describe('relations', function() { context('findById with filter fields', function() { it('returns patient where id equal to \'samplePatientId\'' + 'with field \'name\' but not \'age\'', function(done) { - var fieldsFilter = {fields: {name: true, age: false}}; + const fieldsFilter = {fields: {name: true, age: false}}; physician.patients.findById(samplePatientId, fieldsFilter, function(err, ch) { if (err) return done(err); @@ -916,8 +916,8 @@ describe('relations', function() { }); context('findById with include filter that contains string fields', function() { it('should accept string and convert it to array', function(done) { - var includeFilter = {include: {relation: 'patients', scope: {fields: 'name'}}}; - var physicianId = physician.id; + const includeFilter = {include: {relation: 'patients', scope: {fields: 'name'}}}; + const physicianId = physician.id; Physician.findById(physicianId, includeFilter, function(err, result) { if (err) return done(err); should.exist(result); @@ -964,7 +964,7 @@ describe('relations', function() { } }); it('should find be filtered from option', function(done) { - var id; + let id; Physician.create(function(err, physician) { if (err) return done(err); physician.patients.create({name: 'a', realm: 'test'}, function(err, ch) { @@ -995,7 +995,7 @@ describe('relations', function() { }); it('should find scoped record', function(done) { - var id; + let id; Physician.create(function(err, physician) { physician.patients.create({name: 'a'}, function(err, ch) { id = ch.id; @@ -1018,7 +1018,7 @@ describe('relations', function() { }); it('should find scoped record with promises', function(done) { - var id; + let id; Physician.create() .then(function(physician) { return physician.patients.create({name: 'a'}) @@ -1062,7 +1062,7 @@ describe('relations', function() { should.exist(ch); ch.should.have.lengthOf(1); ch[0].addressId.should.eql(addressId); - var address = ch[0].address(); + const address = ch[0].address(); should.exist(address); address.should.be.an.instanceof(Address); address.name.should.equal('z'); @@ -1093,7 +1093,7 @@ describe('relations', function() { should.exist(ch); ch.should.have.lengthOf(1); ch[0].addressId.toString().should.eql(addressId.toString()); - var address = ch[0].address(); + const address = ch[0].address(); should.exist(address); address.should.be.an.instanceof(Address); address.name.should.equal('z'); @@ -1107,7 +1107,7 @@ describe('relations', function() { }); it('should update scoped record', function(done) { - var id; + let id; Physician.create(function(err, physician) { physician.patients.create({name: 'a'}, function(err, ch) { id = ch.id; @@ -1129,7 +1129,7 @@ describe('relations', function() { }); it('should update scoped record with promises', function(done) { - var id; + let id; Physician.create() .then(function(physician) { return physician.patients.create({name: 'a'}) @@ -1155,7 +1155,7 @@ describe('relations', function() { bdd.itIf(connectorCapabilities.deleteWithOtherThanId !== false, 'should destroy scoped record', function(done) { - var id; + let id; Physician.create(function(err, physician) { physician.patients.create({name: 'a'}, function(err, ch) { id = ch.id; @@ -1175,7 +1175,7 @@ describe('relations', function() { bdd.itIf(connectorCapabilities.deleteWithOtherThanId !== false, 'should destroy scoped record with promises', function(done) { - var id; + let id; Physician.create() .then(function(physician) { return physician.patients.create({name: 'a'}) @@ -1202,7 +1202,7 @@ describe('relations', function() { }); it('should check existence of a scoped record', function(done) { - var id; + let id; Physician.create(function(err, physician) { physician.patients.create({name: 'a'}, function(err, ch) { if (err) return done(err); @@ -1225,7 +1225,7 @@ describe('relations', function() { }); it('should check existence of a scoped record with promises', function(done) { - var id; + let id; Physician.create() .then(function(physician) { return physician.patients.create({name: 'a'}) @@ -1285,7 +1285,7 @@ describe('relations', function() { it('should allow to add connection with through data', function(done) { Physician.create({name: 'ph1'}, function(e, physician) { Patient.create({name: 'pa1'}, function(e, patient) { - var now = Date.now(); + const now = Date.now(); physician.patients.add(patient, {date: new Date(now)}, function(e, app) { should.not.exist(e); should.exist(app); @@ -1305,7 +1305,7 @@ describe('relations', function() { .then(function(physician) { return Patient.create({name: 'pa1'}) .then(function(patient) { - var now = Date.now(); + const now = Date.now(); return physician.patients.add(patient, {date: new Date(now)}) .then(function(app) { should.exist(app); @@ -1322,7 +1322,7 @@ describe('relations', function() { bdd.itIf(connectorCapabilities.deleteWithOtherThanId !== false, 'should allow to remove connection with instance', function(done) { - var id; + let id; Physician.create(function(err, physician) { physician.patients.create({name: 'a'}, function(err, patient) { id = patient.id; @@ -1343,7 +1343,7 @@ describe('relations', function() { bdd.itIf(connectorCapabilities.deleteWithOtherThanId !== false, 'should allow to remove connection with instance with promises', function(done) { - var id; + let id; Physician.create() .then(function(physician) { return physician.patients.create({name: 'a'}) @@ -1375,8 +1375,8 @@ describe('relations', function() { }); describe('hasMany through - collect', function() { - var Physician, Patient, Appointment, Address; - var idPatient, idPhysician; + let Physician, Patient, Appointment, Address; + let idPatient, idPhysician; beforeEach(function(done) { idPatient = uid.fromConnector(db) || 1234; @@ -1399,12 +1399,12 @@ describe('relations', function() { Patient.belongsTo(Address); Appointment.belongsTo(Physician); Appointment.belongsTo(Patient); - var physician = new Physician({id: idPhysician}); - var scope1 = physician.patients._scope; + const physician = new Physician({id: idPhysician}); + const scope1 = physician.patients._scope; scope1.should.have.property('collect', 'patient'); scope1.should.have.property('include', 'patient'); - var patient = new Patient({id: idPatient}); - var scope2 = patient.yyy._scope; + const patient = new Patient({id: idPatient}); + const scope2 = patient.yyy._scope; scope2.should.have.property('collect', 'physician'); scope2.should.have.property('include', 'physician'); }); @@ -1423,12 +1423,12 @@ describe('relations', function() { Patient.belongsTo(Address); // jam. Appointment.belongsTo(Patient, {as: 'car'}); // jam. Should we complain in this case??? - var physician = new Physician({id: idPhysician}); - var scope1 = physician.patients._scope; + const physician = new Physician({id: idPhysician}); + const scope1 = physician.patients._scope; scope1.should.have.property('collect', 'bar'); scope1.should.have.property('include', 'bar'); - var patient = new Patient({id: idPatient}); - var scope2 = patient.yyy._scope; + const patient = new Patient({id: idPatient}); + const scope2 = patient.yyy._scope; scope2.should.have.property('collect', 'foo'); scope2.should.have.property('include', 'foo'); }); @@ -1440,12 +1440,12 @@ describe('relations', function() { Appointment.belongsTo(Patient, {as: 'bar', foreignKey: 'patientId'}); Patient.belongsTo(Address); // jam. - var physician = new Physician({id: idPhysician}); - var scope1 = physician.patients._scope; + const physician = new Physician({id: idPhysician}); + const scope1 = physician.patients._scope; scope1.should.have.property('collect', 'bar'); scope1.should.have.property('include', 'bar'); - var patient = new Patient({id: idPatient}); - var scope2 = patient.yyy._scope; + const patient = new Patient({id: idPatient}); + const scope2 = patient.yyy._scope; scope2.should.have.property('collect', 'foo'); scope2.should.have.property('include', 'foo'); }); @@ -1459,12 +1459,12 @@ describe('relations', function() { Appointment.belongsTo(Physician, {as: 'goo', foreignKey: 'physicianId'}); // jam. Should we complain in this case??? Appointment.belongsTo(Patient, {as: 'car', foreignKey: 'patientId'}); // jam. Should we complain in this case??? - var physician = new Physician({id: idPhysician}); - var scope1 = physician.patients._scope; + const physician = new Physician({id: idPhysician}); + const scope1 = physician.patients._scope; scope1.should.have.property('collect', 'bar'); scope1.should.have.property('include', 'bar'); - var patient = new Patient({id: idPatient}); - var scope2 = patient.yyy._scope; + const patient = new Patient({id: idPatient}); + const scope2 = patient.yyy._scope; scope2.should.have.property('collect', 'foo'); // first matched relation scope2.should.have.property('include', 'foo'); // first matched relation }); @@ -1481,15 +1481,15 @@ describe('relations', function() { }); it('can determine the collect via model name', function() { - var physician = new Physician({id: idPhysician}); - var scope1 = physician.xxx._scope; + const physician = new Physician({id: idPhysician}); + const scope1 = physician.xxx._scope; scope1.should.have.property('collect', 'patient'); scope1.should.have.property('include', 'patient'); }); it('can determine the collect via keyThrough', function() { - var patient = new Patient({id: idPatient}); - var scope2 = patient.yyy._scope; + const patient = new Patient({id: idPatient}); + const scope2 = patient.yyy._scope; scope2.should.have.property('collect', 'foo'); scope2.should.have.property('include', 'foo'); }); @@ -1497,7 +1497,7 @@ describe('relations', function() { }); describe('hasMany through - customized relation name and foreign key', function() { - var Physician, Patient, Appointment; + let Physician, Patient, Appointment; beforeEach(function(done) { Physician = db.define('Physician', {name: String}); @@ -1512,16 +1512,16 @@ describe('relations', function() { Patient.hasMany(Physician, {through: Appointment, as: 'yyy', foreignKey: 'bbbId', keyThrough: 'aaaId'}); Appointment.belongsTo(Physician, {as: 'aaa', foreignKey: 'aaaId'}); Appointment.belongsTo(Patient, {as: 'bbb', foreignKey: 'bbbId'}); - var physician = new Physician({id: 1}); + const physician = new Physician({id: 1}); physician.xxx.should.have.property('_targetClass', 'Patient'); - var patient = new Patient({id: 1}); + const patient = new Patient({id: 1}); patient.yyy.should.have.property('_targetClass', 'Physician'); }); }); describe('hasMany through bi-directional relations on the same model', function() { - var User, Follow, Address; - var idFollower, idFollowee; + let User, Follow, Address; + let idFollower, idFollowee; before(function(done) { idFollower = uid.fromConnector(db) || 3456; @@ -1547,8 +1547,8 @@ describe('relations', function() { it('should set foreignKeys of through model correctly in first relation', function(done) { - var follower = new User({id: idFollower}); - var followee = new User({id: idFollowee}); + const follower = new User({id: idFollower}); + const followee = new User({id: idFollowee}); followee.followers.add(follower, function(err, throughInst) { if (err) return done(err); should.exist(throughInst); @@ -1560,8 +1560,8 @@ describe('relations', function() { it('should set foreignKeys of through model correctly in second relation', function(done) { - var follower = new User({id: idFollower}); - var followee = new User({id: idFollowee}); + const follower = new User({id: idFollower}); + const followee = new User({id: idFollowee}); follower.following.add(followee, function(err, throughInst) { if (err) return done(err); should.exist(throughInst); @@ -1573,8 +1573,8 @@ describe('relations', function() { }); describe('hasMany through - between same models', function() { - var User, Follow, Address; - var idFollower, idFollowee; + let User, Follow, Address; + let idFollower, idFollowee; before(function(done) { idFollower = uid.fromConnector(db) || 3456; @@ -1599,8 +1599,8 @@ describe('relations', function() { }); it('should set the keyThrough and the foreignKey', function(done) { - var user = new User({id: idFollower}); - var user2 = new User({id: idFollowee}); + const user = new User({id: idFollower}); + const user2 = new User({id: idFollowee}); user.following.add(user2, function(err, f) { if (err) return done(err); should.exist(f); @@ -1611,11 +1611,11 @@ describe('relations', function() { }); it('can determine the collect via keyThrough for each side', function() { - var user = new User({id: idFollower}); - var scope1 = user.followers._scope; + const user = new User({id: idFollower}); + const scope1 = user.followers._scope; scope1.should.have.property('collect', 'follower'); scope1.should.have.property('include', 'follower'); - var scope2 = user.following._scope; + const scope2 = user.following._scope; scope2.should.have.property('collect', 'followee'); scope2.should.have.property('include', 'followee'); }); @@ -1667,7 +1667,7 @@ describe('relations', function() { return {type: inst.jobType}; }, scope: function(inst, filter) { - var m = this.properties(inst); // re-use properties + const m = this.properties(inst); // re-use properties if (m) return {where: m}; }, }); @@ -1853,15 +1853,15 @@ describe('relations', function() { }); describe('relations validation', function() { - var validationError; + let validationError; // define a mockup getRelationValidationMsg() method to log the validation error - var logRelationValidationError = function(code, rType, rName) { + const logRelationValidationError = function(code, rType, rName) { validationError = {code, rType, rName}; }; it('rejects belongsTo relation if `model` is not provided', function() { try { - var Picture = db.define('Picture', {name: String}, {relations: { + const Picture = db.define('Picture', {name: String}, {relations: { author: { type: 'belongsTo', foreignKey: 'authorId'}, @@ -1877,7 +1877,7 @@ describe('relations', function() { it('rejects polymorphic belongsTo relation if `model` is provided', function() { try { - var Picture = db.define('Picture', {name: String}, {relations: { + const Picture = db.define('Picture', {name: String}, {relations: { imageable: { type: 'belongsTo', model: 'Picture', @@ -1894,7 +1894,7 @@ describe('relations', function() { it('rejects polymorphic non belongsTo relation if `model` is not provided', function() { try { - var Article = db.define('Picture', {name: String}, {relations: { + const Article = db.define('Picture', {name: String}, {relations: { pictures: { type: 'hasMany', polymorphic: 'imageable'}, @@ -1911,7 +1911,7 @@ describe('relations', function() { it('rejects polymorphic relation if `foreignKey` is provided but discriminator ' + 'is missing', function() { try { - var Article = db.define('Picture', {name: String}, {relations: { + const Article = db.define('Picture', {name: String}, {relations: { pictures: { type: 'hasMany', model: 'Picture', @@ -1929,7 +1929,7 @@ describe('relations', function() { it('rejects polymorphic relation if `discriminator` is provided but foreignKey ' + 'is missing', function() { try { - var Article = db.define('Picture', {name: String}, {relations: { + const Article = db.define('Picture', {name: String}, {relations: { pictures: { type: 'hasMany', model: 'Picture', @@ -1947,7 +1947,7 @@ describe('relations', function() { it('rejects polymorphic relation if `polymorphic.as` is provided along ' + 'with custom foreignKey/discriminator', function() { try { - var Article = db.define('Picture', {name: String}, {relations: { + const Article = db.define('Picture', {name: String}, {relations: { pictures: { type: 'hasMany', model: 'Picture', @@ -1969,7 +1969,7 @@ describe('relations', function() { it('rejects polymorphic relation if `polymorphic.selector` is provided along ' + 'with custom foreignKey/discriminator', function() { try { - var Article = db.define('Picture', {name: String}, {relations: { + const Article = db.define('Picture', {name: String}, {relations: { pictures: { type: 'hasMany', model: 'Picture', @@ -1989,10 +1989,10 @@ describe('relations', function() { }); it('warns on use of deprecated `polymorphic.as` keyword in polymorphic relation', function() { - var message = 'deprecation not reported'; + let message = 'deprecation not reported'; process.once('deprecation', function(err) { message = err.message; }); - var Article = db.define('Picture', {name: String}, {relations: { + const Article = db.define('Picture', {name: String}, {relations: { pictures: {type: 'hasMany', model: 'Picture', polymorphic: {as: 'imageable'}}, }}); @@ -2092,7 +2092,7 @@ describe('relations', function() { article.packshot(function(err, pic) { if (err) return done(err); - var packshot = article.packshot(); + const packshot = article.packshot(); packshot.should.equal(pic); pic.name.should.equal('Packshot'); @@ -2119,7 +2119,7 @@ describe('relations', function() { it('should include polymorphic relation - article', function(done) { Article.findOne({include: 'packshot'}, function(err, article) { should.not.exists(err); - var packshot = article.packshot(); + const packshot = article.packshot(); should.exist(packshot); packshot.name.should.equal('Packshot'); done(); @@ -2155,7 +2155,7 @@ describe('relations', function() { Picture.findOne({where: {name: 'Packshot'}, include: 'imageable'}, function(err, pic) { should.not.exists(err); - var imageable = pic.imageable(); + const imageable = pic.imageable(); should.exist(imageable); imageable.should.be.instanceof(Article); imageable.name.should.equal('Article 1'); @@ -2230,14 +2230,14 @@ describe('relations', function() { }, }); - var imageableRel = Picture.relations['imageable'].toJSON(); + const imageableRel = Picture.relations['imageable'].toJSON(); // assert idType independantly assert(typeof imageableRel.polymorphic.idType == 'function'); // backup idType and remove it temporarily from the relation // object to ease the test - var idType = imageableRel.polymorphic.idType; + const idType = imageableRel.polymorphic.idType; delete imageableRel.polymorphic.idType; imageableRel.should.eql({ @@ -2306,7 +2306,7 @@ describe('relations', function() { article.packshot(function(err, pic) { if (err) return done(err); - var packshot = article.packshot(); + const packshot = article.packshot(); packshot.should.equal(pic); pic.name.should.equal('Packshot'); @@ -2358,7 +2358,7 @@ describe('relations', function() { Employee.findOne({include: 'mugshot'}, function(err, employee) { should.not.exists(err); - var mugshot = employee.mugshot(); + const mugshot = employee.mugshot(); should.exist(mugshot); mugshot.name.should.equal('Mugshot'); done(); @@ -2369,7 +2369,7 @@ describe('relations', function() { Picture.findOne({where: {name: 'Mugshot'}, include: 'imageable'}, function(err, pic) { should.not.exists(err); - var imageable = pic.imageable(); + const imageable = pic.imageable(); should.exist(imageable); imageable.should.be.instanceof(Employee); imageable.name.should.equal('Employee 1'); @@ -2388,15 +2388,15 @@ describe('relations', function() { }); it('can be declared with model JSON definition when related model is already attached', function(done) { - var ds = new DataSource('memory'); + const ds = new DataSource('memory'); // by defining Picture model before Article model we make sure Picture IS // already attached when defining Article. This way, datasource.defineRelations // WILL NOT use the async listener to call hasMany relation method - var Picture = ds.define('Picture', {name: String}, {relations: { + const Picture = ds.define('Picture', {name: String}, {relations: { imageable: {type: 'belongsTo', polymorphic: true}, }}); - var Article = ds.define('Article', {name: String}, {relations: { + const Article = ds.define('Article', {name: String}, {relations: { pictures: {type: 'hasMany', model: 'Picture', polymorphic: 'imageable'}, }}); @@ -2435,15 +2435,15 @@ describe('relations', function() { }); it('can be declared with model JSON definition when related model is not yet attached', function(done) { - var ds = new DataSource('memory'); + const ds = new DataSource('memory'); // by defining Author model before Picture model we make sure Picture IS NOT // already attached when defining Author. This way, datasource.defineRelations // WILL use the async listener to call hasMany relation method - var Author = ds.define('Author', {name: String}, {relations: { + const Author = ds.define('Author', {name: String}, {relations: { pictures: {type: 'hasMany', model: 'Picture', polymorphic: 'imageable'}, }}); - var Picture = ds.define('Picture', {name: String}, {relations: { + const Picture = ds.define('Picture', {name: String}, {relations: { imageable: {type: 'belongsTo', polymorphic: true}, }}); @@ -2555,7 +2555,7 @@ describe('relations', function() { article.pictures(function(err, pics) { if (err) return done(err); - var pictures = article.pictures(); + const pictures = article.pictures(); pictures.should.eql(pics); pics.should.have.length(1); @@ -2629,8 +2629,8 @@ describe('relations', function() { Picture.find({include: 'imageable'}, function(err, pics) { if (err) return done(err); pics.should.have.length(2); - var names = ['Article Pic', 'Employee Pic']; - var imageables = ['Article 1', 'Employee 1']; + const names = ['Article Pic', 'Employee Pic']; + const imageables = ['Article 1', 'Employee 1']; names.should.containEql(pics[0].name); names.should.containEql(pics[1].name); imageables.should.containEql(pics[0].imageable().name); @@ -2642,7 +2642,7 @@ describe('relations', function() { it('should assign a polymorphic relation', function(done) { Article.create({name: 'Article 2'}, function(err, article) { should.not.exists(err); - var p = new Picture({name: 'Sample'}); + const p = new Picture({name: 'Sample'}); p.imageable(article); // assign p.imageableId.should.eql(article.id); p.imageableType.should.equal('Article'); @@ -2682,7 +2682,7 @@ describe('relations', function() { Picture.findOne({where: {name: 'Sample'}, include: 'imageable'}, function(err, p) { if (err) return done(err); - var imageable = p.imageable(); + const imageable = p.imageable(); should.exist(imageable); imageable.should.be.instanceof(Article); imageable.name.should.equal('Article 2'); @@ -2739,7 +2739,7 @@ describe('relations', function() { }); describe('polymorphic hasAndBelongsToMany through', function() { - var idArticle, idEmployee; + let idArticle, idEmployee; before(function(done) { idArticle = uid.fromConnector(db) || 3456; @@ -2767,24 +2767,24 @@ describe('relations', function() { // Optionally, define inverse relations: Picture.hasMany(Article, {through: PictureLink, polymorphic: 'imageable', invert: true}); Picture.hasMany(Employee, {through: PictureLink, polymorphic: 'imageable', invert: true}); - var article = new Article({id: idArticle}); - var scope1 = article.pictures._scope; + const article = new Article({id: idArticle}); + const scope1 = article.pictures._scope; scope1.should.have.property('collect', 'picture'); scope1.should.have.property('include', 'picture'); - var employee = new Employee({id: idEmployee}); - var scope2 = employee.pictures._scope; + const employee = new Employee({id: idEmployee}); + const scope2 = employee.pictures._scope; scope2.should.have.property('collect', 'picture'); scope2.should.have.property('include', 'picture'); - var picture = new Picture({id: idArticle}); - var scope3 = picture.articles._scope; + const picture = new Picture({id: idArticle}); + const scope3 = picture.articles._scope; scope3.should.have.property('collect', 'imageable'); scope3.should.have.property('include', 'imageable'); - var scope4 = picture.employees._scope; + const scope4 = picture.employees._scope; scope4.should.have.property('collect', 'imageable'); scope4.should.have.property('include', 'imageable'); }); - var article, employee, pictures = []; + let article, employee, pictures = []; it('should create polymorphic relation - article', function(done) { Article.create({name: 'Article 1'}, function(err, a) { if (err) return done(err); @@ -2888,7 +2888,7 @@ describe('relations', function() { }); }); - var anotherPicture; + let anotherPicture; it('should add to a polymorphic relation - article', function(done) { if (!article) return done(); Article.findById(article.id, function(err, article) { @@ -2920,7 +2920,7 @@ describe('relations', function() { }); }); - var anotherArticle, anotherEmployee; + let anotherArticle, anotherEmployee; // eslint-disable-next-line mocha/no-identical-title it('should add to a polymorphic relation - article', function(done) { Article.create({name: 'Article 2'}, function(err, article) { @@ -2972,7 +2972,7 @@ describe('relations', function() { if (connectorCapabilities.adhocSort !== false) { employees[0].name.should.equal('Employee 2'); } else { - var employeeNames = ['Employee 1', 'Employee 2']; + const employeeNames = ['Employee 1', 'Employee 2']; employees[0].name.should.be.oneOf(employeeNames); } done(); @@ -3025,7 +3025,7 @@ describe('relations', function() { article.pictures(function(err, pics) { // If deleteWithOtherThanId is not implemented, the above test is skipped and // the remove did not take place. Thus +1. - var expectedLength = connectorCapabilities.deleteWithOtherThanId !== false ? + const expectedLength = connectorCapabilities.deleteWithOtherThanId !== false ? 2 : 3; pics.should.have.length(expectedLength); @@ -3163,9 +3163,9 @@ describe('relations', function() { }); describe('belongsTo', function() { - var List, Item, Fear, Mind; + let List, Item, Fear, Mind; - var listId, itemId; + let listId, itemId; it('can be declared in different ways', function() { List = db.define('List', {name: String}); @@ -3189,14 +3189,14 @@ describe('relations', function() { }); it('should setup a custom method on accessor', function() { - var rel = Fear.relations['mind']; + const rel = Fear.relations['mind']; rel.defineMethod('other', function() { return true; }); }); it('should have setup a custom method on accessor', function() { - var f = new Fear(); + const f = new Fear(); f.mind.check.should.be.a.function; f.mind.check().should.be.true; f.mind.other.should.be.a.function; @@ -3347,7 +3347,7 @@ describe('relations', function() { }); it('should allow to create belongsTo model in beforeCreate hook', function(done) { - var mind; + let mind; Fear.beforeCreate = function(next) { this.mind.create(function(err, m) { mind = m; @@ -3364,7 +3364,7 @@ describe('relations', function() { }); it('should allow to create belongsTo model in beforeCreate hook with promises', function(done) { - var mind; + let mind; Fear.beforeCreate = function(next) { this.mind.create() .then(function(m) { @@ -3383,7 +3383,7 @@ describe('relations', function() { }); describe('belongsTo with scope', function() { - var Person, Passport; + let Person, Passport; it('can be declared with scope and properties', function(done) { Person = db.define('Person', {name: String, age: Number, passportNotes: String}); @@ -3395,9 +3395,9 @@ describe('relations', function() { db.automigrate(['Person', 'Passport'], done); }); - var personCreated; + let personCreated; it('should create record on scope', function(done) { - var p = new Passport({name: 'Passport', notes: 'Some notes...'}); + const p = new Passport({name: 'Passport', notes: 'Some notes...'}); p.person.create({name: 'Fred', age: 36}, function(err, person) { personCreated = person; p.personId.toString().should.eql(person.id.toString()); @@ -3423,7 +3423,7 @@ describe('relations', function() { }); it('should create record on scope with promises', function(done) { - var p = new Passport({name: 'Passport', notes: 'Some notes...'}); + const p = new Passport({name: 'Passport', notes: 'Some notes...'}); p.person.create({name: 'Fred', age: 36}) .then(function(person) { p.personId.should.eql(person.id); @@ -3461,7 +3461,7 @@ describe('relations', function() { // https://github.com/strongloop/loopback-datasource-juggler/pull/399 // is fixed describe.skip('belongsTo with embed', function() { - var Person, Passport; + let Person, Passport; it('can be declared with embed and properties', function(done) { Person = db.define('Person', {name: String, age: Number}); @@ -3475,10 +3475,10 @@ describe('relations', function() { it('should create record with embedded data', function(done) { Person.create({name: 'Fred', age: 36}, function(err, person) { - var p = new Passport({name: 'Passport', notes: 'Some notes...'}); + const p = new Passport({name: 'Passport', notes: 'Some notes...'}); p.person(person); p.personId.should.eql(person.id); - var data = p.toObject(true); + const data = p.toObject(true); data.person.id.should.eql(person.id); data.person.name.should.equal('Fred'); p.save(function(err) { @@ -3491,7 +3491,7 @@ describe('relations', function() { it('should find record with embedded data', function(done) { Passport.findOne(function(err, p) { should.not.exists(err); - var data = p.toObject(true); + const data = p.toObject(true); data.person.id.should.eql(p.personId); data.person.name.should.equal('Fred'); done(); @@ -3501,7 +3501,7 @@ describe('relations', function() { it('should find record with embedded data with promises', function(done) { Passport.findOne() .then(function(p) { - var data = p.toObject(true); + const data = p.toObject(true); data.person.id.should.eql(p.personId); data.person.name.should.equal('Fred'); done(); @@ -3510,8 +3510,8 @@ describe('relations', function() { }); describe('hasOne', function() { - var Supplier, Account; - var supplierId, accountId; + let Supplier, Account; + let supplierId, accountId; before(function() { Supplier = db.define('Supplier', {name: String}); @@ -3528,14 +3528,14 @@ describe('relations', function() { }); it('should setup a custom method on accessor', function() { - var rel = Supplier.relations['account']; + const rel = Supplier.relations['account']; rel.defineMethod('other', function() { return true; }); }); it('should have setup a custom method on accessor', function() { - var s = new Supplier(); + const s = new Supplier(); s.account.check.should.be.a.function; s.account.check().should.be.true; s.account.other.should.be.a.function; @@ -3650,7 +3650,7 @@ describe('relations', function() { it('should error trying to change the foreign key in the update', function(done) { Supplier.create({name: 'Supplier 2'}, function(e, supplier) { - var sid = supplier.id; + const sid = supplier.id; Supplier.findById(supplierId, function(e, supplier) { should.not.exist(e); should.exist(supplier); @@ -3770,8 +3770,8 @@ describe('relations', function() { }); describe('hasOne with scope', function() { - var Supplier, Account; - var supplierId, accountId; + let Supplier, Account; + let supplierId, accountId; before(function() { Supplier = db.define('Supplier', {name: String}); @@ -3884,8 +3884,8 @@ describe('relations', function() { }); describe('hasOne with non standard id', function() { - var Supplier, Account; - var supplierId, accountId; + let Supplier, Account; + let supplierId, accountId; before(function() { Supplier = db.define('Supplier', { @@ -3970,8 +3970,8 @@ describe('relations', function() { }); describe('hasOne with primaryKey different from model PK', function() { - var CompanyBoard, Boss; - var companyBoardId, bossId; + let CompanyBoard, Boss; + let companyBoardId, bossId; before(function() { CompanyBoard = db.define('CompanyBoard', { @@ -4042,8 +4042,8 @@ describe('relations', function() { }); describe('hasMany with primaryKey different from model PK', function() { - var Employee, Boss; - var COMPANY_ID = 'Company1'; + let Employee, Boss; + const COMPANY_ID = 'Company1'; before(function() { Employee = db.define('Employee', {name: String, companyId: String}); @@ -4069,7 +4069,7 @@ describe('relations', function() { should.exists(employees); return boss.employees(); }).then(function(employees) { - var employee = employees[0]; + const employee = employees[0]; should.exist(employee); employees.length.should.equal(2); employee.should.be.an.instanceOf(Employee); @@ -4098,9 +4098,9 @@ describe('relations', function() { }); describe('belongsTo with primaryKey different from model PK', function() { - var Employee, Boss; - var COMPANY_ID = 'Company1'; - var bossId; + let Employee, Boss; + const COMPANY_ID = 'Company1'; + let bossId; before(function() { Employee = db.define('Employee', {name: String, companyId: String}); @@ -4135,7 +4135,7 @@ describe('relations', function() { }); describe('hasAndBelongsToMany', function() { - var Article, TagName, ArticleTag; + let Article, TagName, ArticleTag; it('can be declared', function(done) { Article = db.define('Article', {title: String}); TagName = db.define('TagName', {name: String, flag: String}); @@ -4208,7 +4208,7 @@ describe('relations', function() { 'should allow to remove connection with instance', function(done) { Article.findOne(function(e, article) { article.tagNames(function(e, tags) { - var len = tags.length; + const len = tags.length; tags.should.not.be.empty; article.tagNames.remove(tags[0], function(e) { should.not.exist(e); @@ -4276,7 +4276,7 @@ describe('relations', function() { .then(function(article) { return article.tagNames.find() .then(function(tags) { - var len = tags.length; + const len = tags.length; tags.should.not.be.empty; return article.tagNames.remove(tags[0]) .then(function() { @@ -4306,11 +4306,11 @@ describe('relations', function() { function(e, articles) { should.not.exist(e); articles.should.have.property('length', 1); - var a = articles[0].toJSON(); + const a = articles[0].toJSON(); a.should.have.property('title', 'a1'); a.should.have.property('tagNames'); a.tagNames.should.have.property('length', 1); - var n = a.tagNames[0]; + const n = a.tagNames[0]; n.should.have.property('name', 't1'); n.should.have.property('flag', undefined); n.id.should.eql(t.id); @@ -4332,11 +4332,11 @@ describe('relations', function() { function(e, articles) { should.not.exist(e); articles.should.have.property('length', 1); - var a = articles[0].toJSON(); + const a = articles[0].toJSON(); a.should.have.property('title', 'a2'); a.should.have.property('tagNames'); a.tagNames.should.have.property('length', 1); - var n = a.tagNames[0]; + const n = a.tagNames[0]; n.should.have.property('name', 't2'); n.should.have.property('flag', '2'); n.id.should.eql(t2.id); @@ -4349,9 +4349,9 @@ describe('relations', function() { }); describe('embedsOne', function() { - var person; - var Passport; - var Other; + let person; + let Passport; + let Other; before(function() { tmp = getTransientDataSource(); @@ -4380,7 +4380,7 @@ describe('relations', function() { }); it('should have setup a property and accessor', function() { - var p = new Person(); + const p = new Person(); p.passport.should.be.an.object; // because of default p.passportItem.should.be.a.function; p.passportItem.create.should.be.a.function; @@ -4394,14 +4394,14 @@ describe('relations', function() { }); it('should setup a custom method on accessor', function() { - var rel = Person.relations['passportItem']; + const rel = Person.relations['passportItem']; rel.defineMethod('other', function() { return true; }); }); it('should have setup a custom method on accessor', function() { - var p = new Person(); + const p = new Person(); p.passportItem.check.should.be.a.function; p.passportItem.check().should.be.true; p.passportItem.other.should.be.a.function; @@ -4409,20 +4409,20 @@ describe('relations', function() { }); it('should behave properly without default or being set', function(done) { - var p = new Person(); + const p = new Person(); should.not.exist(p.address); - var a = p.addressItem(); + const a = p.addressItem(); should.not.exist(a); Person.create({}, function(err, p) { should.not.exist(p.address); - var a = p.addressItem(); + const a = p.addressItem(); should.not.exist(a); done(); }); }); it('should return an instance with default values', function() { - var p = new Person(); + const p = new Person(); p.passport.toObject().should.eql({name: 'Anonymous'}); p.passportItem().should.equal(p.passport); p.passportItem(function(err, passport) { @@ -4432,20 +4432,20 @@ describe('relations', function() { }); it('should embed a model instance', function() { - var p = new Person(); + const p = new Person(); p.passportItem(new Passport({name: 'Fred'})); p.passport.toObject().should.eql({name: 'Fred'}); p.passport.should.be.an.instanceOf(Passport); }); it('should not embed an invalid model type', function() { - var p = new Person(); + const p = new Person(); p.passportItem(new Other()); p.passport.toObject().should.eql({name: 'Anonymous'}); p.passport.should.be.an.instanceOf(Passport); }); - var personId; + let personId; it('should create an embedded item on scope', function(done) { Person.create({name: 'Fred'}, function(err, p) { if (err) return done(err); @@ -4462,7 +4462,7 @@ describe('relations', function() { it('should get an embedded item on scope', function(done) { Person.findById(personId, function(err, p) { if (err) return done(err); - var passport = p.passportItem(); + const passport = p.passportItem(); passport.toObject().should.eql({name: 'Fredric'}); passport.should.be.an.instanceOf(Passport); passport.should.equal(p.passport); @@ -4472,7 +4472,7 @@ describe('relations', function() { }); it('should validate an embedded item on scope - on creation', function(done) { - var p = new Person({name: 'Fred'}); + const p = new Person({name: 'Fred'}); p.passportItem.create({}, function(err, passport) { should.exist(err); err.name.should.equal('ValidationError'); @@ -4483,7 +4483,7 @@ describe('relations', function() { it('should validate an embedded item on scope - on update', function(done) { Person.findById(personId, function(err, p) { - var passport = p.passportItem(); + const passport = p.passportItem(); passport.name = null; p.save(function(err) { should.exist(err); @@ -4511,7 +4511,7 @@ describe('relations', function() { it('should get an embedded item on scope - verify', function(done) { Person.findById(personId, function(err, p) { if (err) return done(err); - var passport = p.passportItem(); + const passport = p.passportItem(); passport.toObject().should.eql({name: 'Freddy'}); done(); }); @@ -4537,7 +4537,7 @@ describe('relations', function() { }); it('should save an unsaved model', function(done) { - var p = new Person({name: 'Fred'}); + const p = new Person({name: 'Fred'}); p.isNewRecord().should.be.true; p.passportItem.create({name: 'Fredric'}, function(err, passport) { if (err) return done(err); @@ -4563,7 +4563,7 @@ describe('relations', function() { it('should get an embedded item on scope with promises', function(done) { Person.findById(personId) .then(function(p) { - var passport = p.passportItem(); + const passport = p.passportItem(); passport.toObject().should.eql({name: 'Fredric'}); passport.should.be.an.instanceOf(Passport); passport.should.equal(p.passport); @@ -4573,7 +4573,7 @@ describe('relations', function() { }); it('should validate an embedded item on scope with promises - on creation', function(done) { - var p = new Person({name: 'Fred'}); + const p = new Person({name: 'Fred'}); p.passportItem.create({}) .then(function(passport) { should.not.exist(passport); @@ -4590,7 +4590,7 @@ describe('relations', function() { it('should validate an embedded item on scope with promises - on update', function(done) { Person.findById(personId) .then(function(p) { - var passport = p.passportItem(); + const passport = p.passportItem(); passport.name = null; return p.save() .then(function(p) { @@ -4624,7 +4624,7 @@ describe('relations', function() { it('should get an embedded item on scope with promises - verify', function(done) { Person.findById(personId) .then(function(p) { - var passport = p.passportItem(); + const passport = p.passportItem(); passport.toObject().should.eql({name: 'Jason'}); done(); }).catch(done); @@ -4652,7 +4652,7 @@ describe('relations', function() { it('should also save changes when directly saving the embedded model', function(done) { // Passport should normally have an id for the direct save to work. For now override the check - var originalHasPK = Passport.definition.hasPK; + const originalHasPK = Passport.definition.hasPK; Passport.definition.hasPK = function() { return true; }; Person.findById(personId) .then(function(p) { @@ -4678,7 +4678,7 @@ describe('relations', function() { }); it('should delete the embedded document and also update parent', function(done) { - var originalHasPK = Passport.definition.hasPK; + const originalHasPK = Passport.definition.hasPK; Passport.definition.hasPK = function() { return true; }; Person.findById(personId) .then(function(p) { @@ -4702,7 +4702,7 @@ describe('relations', function() { // This test spefically uses the Memory connector // in order to test the use of the auto-generated // id, in the sequence of the related model. - var Passport, Person; + let Passport, Person; before(function() { db = getMemoryDataSource(); Person = db.define('Person', {name: String}); @@ -4752,7 +4752,7 @@ describe('relations', function() { }); describe('embedsOne - generated id', function() { - var Passport; + let Passport; before(function() { tmp = getTransientDataSource(); Person = db.define('Person', {name: String}); @@ -4782,7 +4782,7 @@ describe('relations', function() { }); describe('embedsMany', function() { - var address1, address2; + let address1, address2; before(function(done) { tmp = getTransientDataSource({defaultIdType: Number}); @@ -4807,7 +4807,7 @@ describe('relations', function() { }); it('should have setup embedded accessor/scope', function() { - var p = new Person({name: 'Fred'}); + const p = new Person({name: 'Fred'}); p.addresses.should.be.an.array; p.addresses.should.have.length(0); p.addressList.should.be.a.function; @@ -4854,7 +4854,7 @@ describe('relations', function() { p.addressList(function(err, addresses) { if (err) return done(err); - var list = p.addressList(); + const list = p.addressList(); list.should.equal(addresses); list.should.equal(p.addresses); @@ -5020,7 +5020,7 @@ describe('relations', function() { }); it('should save an unsaved model', function(done) { - var p = new Person({name: 'Fred'}); + const p = new Person({name: 'Fred'}); p.isNewRecord().should.be.true; p.addressList.create({street: 'Street 4'}, function(err, address) { if (err) return done(err); @@ -5056,7 +5056,7 @@ describe('relations', function() { }); it('should not set default value for embedded item', function() { - var p = new Person({name: 'Fred'}); + const p = new Person({name: 'Fred'}); p.should.have.property('addresses', undefined); }); @@ -5084,7 +5084,7 @@ describe('relations', function() { }); it('should not create embedded from attributes - relation name', function(done) { - var addresses = [ + const addresses = [ {id: 'home', street: 'Home Street'}, {id: 'work', street: 'Work Street'}, ]; @@ -5211,7 +5211,7 @@ describe('relations', function() { }); it('should validate all embedded items', function(done) { - var addresses = []; + const addresses = []; addresses.push({id: 'home', street: 'Home Street'}); addresses.push({id: 'work', street: ''}); Person.create({name: 'Wilma', addresses: addresses}, function(err, p) { @@ -5262,7 +5262,7 @@ describe('relations', function() { }); it('should create embedded from attributes - property name', function(done) { - var addresses = [ + const addresses = [ {id: 'home', street: 'Home Street'}, {id: 'work', street: 'Work Street'}, ]; @@ -5275,7 +5275,7 @@ describe('relations', function() { }); it('should not create embedded from attributes - relation name', function(done) { - var addresses = [ + const addresses = [ {id: 'home', street: 'Home Street'}, {id: 'work', street: 'Work Street'}, ]; @@ -5299,8 +5299,8 @@ describe('relations', function() { }); describe('embedsMany - persisted model', function() { - var address0, address1, address2; - var person; + let address0, address1, address2; + let person; // This test spefically uses the Memory connector // in order to test the use of the auto-generated @@ -5408,13 +5408,13 @@ describe('relations', function() { }); it('should validate embedded items on scope - street', function(done) { - var newId = uid.fromConnector(db) || 1234; + const newId = uid.fromConnector(db) || 1234; Person.create({name: 'Wilma'}, function(err, p) { p.addressList.create({id: newId}, function(err, address) { should.exist(err); err.name.should.equal('ValidationError'); err.details.codes.street.should.eql(['presence']); - var expected = 'The `Address` instance is not valid. '; + let expected = 'The `Address` instance is not valid. '; expected += 'Details: `street` can\'t be blank (value: undefined).'; err.message.should.equal(expected); done(); @@ -5424,7 +5424,7 @@ describe('relations', function() { }); describe('embedsMany - relations, scope and properties', function() { - var category, job1, job2, job3; + let category, job1, job2, job3; before(function() { Category = db.define('Category', {name: String}); @@ -5467,13 +5467,13 @@ describe('relations', function() { it('should associate items on scope', function(done) { Category.create({name: 'Category A'}, function(err, cat) { if (err) return done(err); - var link = cat.items.build(); + let link = cat.items.build(); link.job(job1); link = cat.items.build(); link.job(job2); cat.save(function(err, cat) { if (err) return done(err); - var job = cat.items.at(0); + let job = cat.items.at(0); job.should.be.instanceof(Link); job.should.not.have.property('jobId'); job.id.should.eql(job1.id); @@ -5597,13 +5597,13 @@ describe('relations', function() { }); }); - var jobId; + let jobId; it('should create items on scope', function(done) { Category.create({name: 'Category B'}, function(err, cat) { if (err) return done(err); category = cat; - var link = cat.items.build({notes: 'Some notes...'}); + const link = cat.items.build({notes: 'Some notes...'}); link.job.create({name: 'Job 1'}, function(err, p) { if (err) return done(err); jobId = p.id; @@ -5640,7 +5640,7 @@ describe('relations', function() { it('should update items on scope - and save parent', function(done) { Category.findById(category.id, function(err, cat) { if (err) return done(err); - var link = cat.items.at(0); + const link = cat.items.at(0); // use 'updateById' instead as a replacement as it is one of the embedsMany methods, // that works with all connectors. `updateAttributes` does not recognize the query done on // the Category Model, resulting with an error in three connectors: mssql, oracle, postgresql @@ -5685,7 +5685,7 @@ describe('relations', function() { }); describe('embedsMany - polymorphic relations', function() { - var person1, person2; + let person1, person2; before(function(done) { tmp = getTransientDataSource(); @@ -5705,7 +5705,7 @@ describe('relations', function() { }); it('can be declared', function(done) { - var idType = db.connector.getDefaultIdType(); + const idType = db.connector.getDefaultIdType(); Book.embedsMany(Link, {as: 'people', polymorphic: 'linked', @@ -5731,14 +5731,14 @@ describe('relations', function() { it('should create items on scope', function(done) { Book.create({name: 'Book'}, function(err, book) { - var link = book.people.build({notes: 'Something ...'}); + let link = book.people.build({notes: 'Something ...'}); link.linked(person1); link = book.people.build(); link.linked(person2); book.save(function(err, book) { if (err) return done(err); - var link = book.people.at(0); + let link = book.people.at(0); link.should.be.instanceof(Link); link.id.should.equal(1); link.linkedId.should.eql(person1.id); @@ -5761,7 +5761,7 @@ describe('relations', function() { Book.findOne(function(err, book) { book.links.should.have.length(2); - var link = book.people.at(0); + let link = book.people.at(0); link.should.be.instanceof(Link); link.id.should.eql(1); link.linkedId.should.eql(person1.id); @@ -5796,7 +5796,7 @@ describe('relations', function() { // In loopback, an afterRemote filter could do this as well. Book.find({include: 'people'}, function(err, books) { - var obj = books[0].toObject(); + const obj = books[0].toObject(); obj.should.have.property('links'); obj.should.have.property('people'); @@ -5819,7 +5819,7 @@ describe('relations', function() { }); describe('referencesMany', function() { - var job1, job2, job3; + let job1, job2, job3; before(function(done) { Category = db.define('Category', {name: String}); @@ -5829,11 +5829,11 @@ describe('relations', function() { }); it('can be declared', function(done) { - var reverse = function(cb) { + const reverse = function(cb) { cb = cb || createPromiseCallback(); - var modelInstance = this.modelInstance; - var fk = this.definition.keyFrom; - var ids = modelInstance[fk] || []; + const modelInstance = this.modelInstance; + const fk = this.definition.keyFrom; + const ids = modelInstance[fk] || []; modelInstance.updateAttribute(fk, ids.reverse(), function(err, inst) { cb(err, inst[fk] || []); }); @@ -5897,7 +5897,7 @@ describe('relations', function() { cat.jobIds[0].should.eql(job2.id); cat.jobs(function(err, jobs) { if (err) return done(err); - var p = jobs[0]; + const p = jobs[0]; p.id.should.eql(job2.id); p.name.should.equal('Job 2'); done(); @@ -5931,7 +5931,7 @@ describe('relations', function() { it('should update a record on scope', function(done) { Category.findOne(function(err, cat) { - var attrs = {name: 'Job 2 - edit'}; + const attrs = {name: 'Job 2 - edit'}; cat.jobs.updateById(job2.id, attrs, function(err, p) { if (err) return done(err); p.name.should.equal(attrs.name); @@ -5970,7 +5970,7 @@ describe('relations', function() { Category.findOne(function(err, cat) { cat.jobs.add(job3.id, function(err, prod) { if (err) return done(err); - var expected = [job2.id, job1.id, job3.id]; + const expected = [job2.id, job1.id, job3.id]; cat.jobIds[0].should.eql(expected[0]); cat.jobIds[1].should.eql(expected[1]); cat.jobIds[2].should.eql(expected[2]); @@ -5995,11 +5995,11 @@ describe('relations', function() { it('should find items on scope - filter', function(done) { Category.findOne(function(err, cat) { - var filter = {where: {name: 'Job 1'}}; + const filter = {where: {name: 'Job 1'}}; cat.jobs(filter, function(err, jobs) { if (err) return done(err); jobs.should.have.length(1); - var p = jobs[0]; + const p = jobs[0]; p.id.should.eql(job1.id); p.name.should.equal('Job 1'); done(); @@ -6011,7 +6011,7 @@ describe('relations', function() { Category.findOne(function(err, cat) { cat.jobs.remove(job1.id, function(err, ids) { if (err) return done(err); - var expected = [job2.id, job3.id]; + const expected = [job2.id, job3.id]; cat.jobIds[0].should.eql(expected[0]); cat.jobIds[1].should.eql(expected[1]); cat.jobIds[0].should.eql(ids[0]); @@ -6023,7 +6023,7 @@ describe('relations', function() { it('should find items on scope - verify', function(done) { Category.findOne(function(err, cat) { - var expected = [job2.id, job3.id]; + const expected = [job2.id, job3.id]; cat.jobIds[0].should.eql(expected[0]); cat.jobIds[1].should.eql(expected[1]); cat.jobs(function(err, jobs) { @@ -6054,7 +6054,7 @@ describe('relations', function() { 'should allow custom scope methods - reverse', function(done) { Category.findOne(function(err, cat) { cat.jobs.reverse(function(err, ids) { - var expected = [job3.id, job2.id]; + const expected = [job3.id, job2.id]; ids.toArray().should.eql(expected); cat.jobIds.toArray().should.eql(expected); done(); @@ -6066,7 +6066,7 @@ describe('relations', function() { 'should allow custom scope methods - reverse', function(done) { Category.findOne(function(err, cat) { cat.jobs.reverse(function(err, ids) { - var expected = [job3.id, job2.id]; + const expected = [job3.id, job2.id]; ids[0].should.be.oneOf(expected); ids[1].should.be.oneOf(expected); cat.jobIds[0].should.be.oneOf(expected); @@ -6080,7 +6080,7 @@ describe('relations', function() { 'should include related items from scope', function(done) { Category.find({include: 'jobs'}, function(err, categories) { categories.should.have.length(1); - var cat = categories[0].toObject(); + const cat = categories[0].toObject(); cat.name.should.equal('Category A'); cat.jobs.should.have.length(2); cat.jobs[0].id.should.eql(job3.id); @@ -6173,7 +6173,7 @@ describe('relations', function() { return cat.jobs.find(); }) .then(function(jobs) { - var p = jobs[0]; + const p = jobs[0]; p.id.should.eql(job2.id); p.name.should.equal('Job 2'); done(); @@ -6183,15 +6183,15 @@ describe('relations', function() { bdd.itIf(connectorCapabilities.adhocSort === false, 'should find items on scope with promises', function(done) { - var theExpectedIds = [job1.id, job2.id, job3.id]; - var theExpectedNames = ['Job 1', 'Job 2', 'Job 3']; + const theExpectedIds = [job1.id, job2.id, job3.id]; + const theExpectedNames = ['Job 1', 'Job 2', 'Job 3']; Category.findOne() .then(function(cat) { cat.jobIds[0].should.be.oneOf(theExpectedIds); return cat.jobs.find(); }) .then(function(jobs) { - var p = jobs[0]; + const p = jobs[0]; p.id.should.be.oneOf(theExpectedIds); p.name.should.be.oneOf(theExpectedNames); done(); @@ -6229,7 +6229,7 @@ describe('relations', function() { it('should update a record on scope with promises', function(done) { Category.findOne() .then(function(cat) { - var attrs = {name: 'Job 2 - edit'}; + const attrs = {name: 'Job 2 - edit'}; return cat.jobs.updateById(job2.id, attrs) .then(function(p) { p.name.should.equal(attrs.name); @@ -6258,7 +6258,7 @@ describe('relations', function() { .then(function(cat) { return cat.jobs.add(job1) .then(function(prod) { - var expected = [job2.id, job1.id]; + const expected = [job2.id, job1.id]; cat.jobIds.should.have.lengthOf(expected.length); cat.jobIds.should.containDeep(expected); prod.id.should.eql(job1.id); @@ -6275,7 +6275,7 @@ describe('relations', function() { .then(function(cat) { return cat.jobs.add(job3.id) .then(function(prod) { - var expected = [job2.id, job1.id, job3.id]; + const expected = [job2.id, job1.id, job3.id]; cat.jobIds.should.have.lengthOf(expected.length); cat.jobIds.should.containDeep(expected); prod.id.should.eql(job3.id); @@ -6303,12 +6303,12 @@ describe('relations', function() { it('should find items on scope with promises - filter', function(done) { Category.findOne() .then(function(cat) { - var filter = {where: {name: 'Job 1'}}; + const filter = {where: {name: 'Job 1'}}; return cat.jobs.find(filter); }) .then(function(jobs) { jobs.should.have.length(1); - var p = jobs[0]; + const p = jobs[0]; p.id.should.eql(job1.id); p.name.should.equal('Job 1'); done(); @@ -6321,7 +6321,7 @@ describe('relations', function() { .then(function(cat) { return cat.jobs.remove(job1.id) .then(function(ids) { - var expected = [job2.id, job3.id]; + const expected = [job2.id, job3.id]; cat.jobIds.should.have.lengthOf(expected.length); cat.jobIds.should.containDeep(expected); cat.jobIds.should.eql(ids); @@ -6334,7 +6334,7 @@ describe('relations', function() { it('should find items on scope with promises - verify', function(done) { Category.findOne() .then(function(cat) { - var expected = [job2.id, job3.id]; + const expected = [job2.id, job3.id]; cat.jobIds.should.have.lengthOf(expected.length); cat.jobIds.should.containDeep(expected); return cat.jobs.find(); @@ -6370,7 +6370,7 @@ describe('relations', function() { .then(function(cat) { return cat.jobs.reverse() .then(function(ids) { - var expected = [job3.id, job2.id]; + const expected = [job3.id, job2.id]; ids.toArray().should.eql(expected); cat.jobIds.toArray().should.eql(expected); done(); @@ -6385,7 +6385,7 @@ describe('relations', function() { Category.find({include: 'jobs'}) .then(function(categories) { categories.should.have.length(1); - var cat = categories[0].toObject(); + const cat = categories[0].toObject(); cat.name.should.equal('Category A'); cat.jobs.should.have.length(2); cat.jobs[0].id.should.eql(job3.id); @@ -6399,7 +6399,7 @@ describe('relations', function() { .then(function(cat) { return cat.jobs.destroy(job2.id) .then(function() { - var expected = [job3.id]; + const expected = [job3.id]; if (connectorCapabilities.adhocSort !== false) { cat.jobIds.toArray().should.eql(expected); } else { @@ -6420,7 +6420,7 @@ describe('relations', function() { it('should find items on scope with promises - verify', function(done) { Category.findOne() .then(function(cat) { - var expected = [job3.id]; + const expected = [job3.id]; cat.jobIds.should.have.lengthOf(expected.length); cat.jobIds.should.containDeep(expected); return cat.jobs.find(); @@ -6435,7 +6435,7 @@ describe('relations', function() { }); describe('custom relation/scope methods', function() { - var categoryId; + let categoryId; before(function(done) { Category = db.define('Category', {name: String}); @@ -6445,15 +6445,15 @@ describe('relations', function() { }); it('can be declared', function(done) { - var relation = Category.hasMany(Job); + const relation = Category.hasMany(Job); - var summarize = function(cb) { + const summarize = function(cb) { cb = cb || createPromiseCallback(); - var modelInstance = this.modelInstance; + const modelInstance = this.modelInstance; this.fetch(function(err, items) { if (err) return cb(err, []); - var summary = items.map(function(item) { - var obj = item.toObject(); + const summary = items.map(function(item) { + const obj = item.toObject(); obj.categoryName = modelInstance.name; return obj; }); @@ -6486,8 +6486,8 @@ describe('relations', function() { }); it('should allow custom scope methods - summarize', function(done) { - var categoryIdStr = categoryId.toString(); - var expected = [ + const categoryIdStr = categoryId.toString(); + const expected = [ {name: 'Job 1', categoryId: categoryIdStr, categoryName: 'Category A'}, {name: 'Job 2', categoryId: categoryIdStr, categoryName: 'Category A'}, ]; @@ -6495,7 +6495,7 @@ describe('relations', function() { Category.findOne(function(err, cat) { cat.jobs.summarize(function(err, summary) { if (err) return done(err); - var result = summary.map(function(item) { + const result = summary.map(function(item) { delete item.id; item.categoryId = item.categoryId.toString(); return item; @@ -6509,8 +6509,8 @@ describe('relations', function() { }); it('should allow custom scope methods with promises - summarize', function(done) { - var categoryIdStr = categoryId.toString(); - var expected = [ + const categoryIdStr = categoryId.toString(); + const expected = [ {name: 'Job 1', categoryId: categoryIdStr, categoryName: 'Category A'}, {name: 'Job 2', categoryId: categoryIdStr, categoryName: 'Category A'}, ]; @@ -6520,7 +6520,7 @@ describe('relations', function() { return cat.jobs.summarize(); }) .then(function(summary) { - var result = summary.map(function(item) { + const result = summary.map(function(item) { delete item.id; item.categoryId = item.categoryId.toString(); return item; diff --git a/test/schema.test.js b/test/schema.test.js index 3dd9ace4..3b58df9a 100644 --- a/test/schema.test.js +++ b/test/schema.test.js @@ -7,15 +7,15 @@ 'use strict'; /* global getSchema:false */ -var should = require('./init.js'); +const should = require('./init.js'); -var db = getSchema(), slave = getSchema(), Model, SlaveModel; +let db = getSchema(), slave = getSchema(), Model, SlaveModel; describe('dataSource', function() { it('should define Model', function() { Model = db.define('Model'); Model.dataSource.should.eql(db); - var m = new Model; + const m = new Model; m.getDataSource().should.eql(db); }); @@ -23,7 +23,7 @@ describe('dataSource', function() { SlaveModel = slave.copyModel(Model); SlaveModel.dataSource.should.equal(slave); slave.should.not.equal(db); - var sm = new SlaveModel; + const sm = new SlaveModel; sm.should.be.instanceOf(Model); sm.getDataSource().should.not.equal(db); sm.getDataSource().should.equal(slave); @@ -34,10 +34,10 @@ describe('dataSource', function() { }); it('should create transaction', function(done) { - var tr = db.transaction(); + const tr = db.transaction(); tr.connected.should.be.false; tr.connecting.should.be.false; - var called = false; + let called = false; tr.models.Model.create(Array(3), function() { called = true; }); diff --git a/test/scope.test.js b/test/scope.test.js index 06158953..495ed60f 100644 --- a/test/scope.test.js +++ b/test/scope.test.js @@ -7,9 +7,9 @@ 'use strict'; /* global getSchema:false */ -var should = require('./init.js'); +const should = require('./init.js'); -var db, Railway, Station; +let db, Railway, Station; describe('scope', function() { before(function() { @@ -161,7 +161,7 @@ describe('scope - order', function() { }); describe('scope - filtered count, updateAll and destroyAll', function() { - var stationA; + let stationA; before(function() { db = getSchema(); @@ -290,7 +290,7 @@ describe('scope - filtered count, updateAll and destroyAll', function() { count.should.equal(2); done(); }); - }; + } }); it('should allow filtered updateAll', function(done) { @@ -306,7 +306,7 @@ describe('scope - filtered count, updateAll and destroyAll', function() { count.should.equal(2); done(); }); - }; + } }); it('should allow filtered destroyAll', function(done) { @@ -325,12 +325,12 @@ describe('scope - filtered count, updateAll and destroyAll', function() { done(); }); }); - }; + } }); }); describe('scope - dynamic target class', function() { - var Collection, Image, Video; + let Collection, Image, Video; before(function() { db = getSchema(); @@ -414,7 +414,7 @@ describe('scope - dynamic target class', function() { }); describe('scope - dynamic function', function() { - var Item, seed = 0; + let Item, seed = 0; before(function() { db = getSchema(); diff --git a/test/spec_helper.js b/test/spec_helper.js index acf9ebcb..082ac83f 100644 --- a/test/spec_helper.js +++ b/test/spec_helper.js @@ -15,7 +15,7 @@ 'use strict'; -var group_name = false, EXT_EXP; +let group_name = false, EXT_EXP; function it(should, test_case) { check_external_exports(); if (group_name) { diff --git a/test/transaction.test.js b/test/transaction.test.js index 5c973ab5..74221182 100644 --- a/test/transaction.test.js +++ b/test/transaction.test.js @@ -159,7 +159,7 @@ describe('Transactions on test connector with execute()', () => { }); function createDataSource() { - let db = new DataSource({ + const db = new DataSource({ initialize: (dataSource, cb) => { dataSource.connector = new TestConnector(); cb(); diff --git a/test/transient.test.js b/test/transient.test.js index 4aaf84e2..76aa7d26 100644 --- a/test/transient.test.js +++ b/test/transient.test.js @@ -4,15 +4,15 @@ // License text available at https://opensource.org/licenses/MIT 'use strict'; -var jdb = require('../'); -var DataSource = jdb.DataSource; -var assert = require('assert'); -var async = require('async'); -var should = require('./init.js'); +const jdb = require('../'); +const DataSource = jdb.DataSource; +const assert = require('assert'); +const async = require('async'); +const should = require('./init.js'); -var db, TransientModel, Person, Widget, Item; +let db, TransientModel, Person, Widget, Item; -var getTransientDataSource = function(settings) { +const getTransientDataSource = function(settings) { return new DataSource('transient', settings); }; diff --git a/test/util.test.js b/test/util.test.js index bc15d23d..9c3baf25 100644 --- a/test/util.test.js +++ b/test/util.test.js @@ -4,20 +4,20 @@ // License text available at https://opensource.org/licenses/MIT 'use strict'; -var should = require('./init.js'); -var utils = require('../lib/utils'); -var ObjectID = require('bson').ObjectID; -var fieldsToArray = utils.fieldsToArray; -var sanitizeQuery = utils.sanitizeQuery; -var deepMerge = utils.deepMerge; -var rankArrayElements = utils.rankArrayElements; -var mergeIncludes = utils.mergeIncludes; -var sortObjectsByIds = utils.sortObjectsByIds; -var uniq = utils.uniq; +const should = require('./init.js'); +const utils = require('../lib/utils'); +const ObjectID = require('bson').ObjectID; +const fieldsToArray = utils.fieldsToArray; +const sanitizeQuery = utils.sanitizeQuery; +const deepMerge = utils.deepMerge; +const rankArrayElements = utils.rankArrayElements; +const mergeIncludes = utils.mergeIncludes; +const sortObjectsByIds = utils.sortObjectsByIds; +const uniq = utils.uniq; describe('util.fieldsToArray', function() { function sample(fields, excludeUnknown) { - var properties = ['foo', 'bar', 'bat', 'baz']; + const properties = ['foo', 'bar', 'bat', 'baz']; return { expect: function(arr) { should.deepEqual(fieldsToArray(fields, properties, excludeUnknown), arr); @@ -54,13 +54,13 @@ describe('util.fieldsToArray', function() { describe('util.sanitizeQuery', function() { it('Remove undefined values from the query object', function() { - var q1 = {where: {x: 1, y: undefined}}; + const q1 = {where: {x: 1, y: undefined}}; should.deepEqual(sanitizeQuery(q1), {where: {x: 1}}); - var q2 = {where: {x: 1, y: 2}}; + const q2 = {where: {x: 1, y: 2}}; should.deepEqual(sanitizeQuery(q2), {where: {x: 1, y: 2}}); - var q3 = {where: {x: 1, y: {in: [2, undefined]}}}; + const q3 = {where: {x: 1, y: {in: [2, undefined]}}}; should.deepEqual(sanitizeQuery(q3), {where: {x: 1, y: {in: [2]}}}); should.equal(sanitizeQuery(null), null); @@ -69,29 +69,29 @@ describe('util.sanitizeQuery', function() { should.equal(sanitizeQuery('x'), 'x'); - var date = new Date(); - var q4 = {where: {x: 1, y: date}}; + const date = new Date(); + const q4 = {where: {x: 1, y: date}}; should.deepEqual(sanitizeQuery(q4), {where: {x: 1, y: date}}); // test handling of undefined - var q5 = {where: {x: 1, y: undefined}}; + let q5 = {where: {x: 1, y: undefined}}; should.deepEqual(sanitizeQuery(q5, 'nullify'), {where: {x: 1, y: null}}); q5 = {where: {x: 1, y: undefined}}; should.deepEqual(sanitizeQuery(q5, {normalizeUndefinedInQuery: 'nullify'}), {where: {x: 1, y: null}}); - var q6 = {where: {x: 1, y: undefined}}; + const q6 = {where: {x: 1, y: undefined}}; (function() { sanitizeQuery(q6, 'throw'); }).should.throw(/`undefined` in query/); }); it('Report errors for circular or deep query objects', function() { - var q7 = {where: {x: 1}}; + const q7 = {where: {x: 1}}; q7.where.y = q7; (function() { sanitizeQuery(q7); }).should.throw( /The query object is circular/ ); - var q8 = {where: {and: [{and: [{and: [{and: [{and: [{and: + const q8 = {where: {and: [{and: [{and: [{and: [{and: [{and: [{and: [{and: [{and: [{x: 1}]}]}]}]}]}]}]}]}]}}; (function() { sanitizeQuery(q8, {maxDepth: 12}); }).should.throw( /The query object exceeds maximum depth 12/ @@ -100,18 +100,18 @@ describe('util.sanitizeQuery', function() { // maxDepth is default to maximum integer sanitizeQuery(q8).should.eql(q8); - var q9 = {where: {and: [{and: [{and: [{and: [{x: 1}]}]}]}]}}; + const q9 = {where: {and: [{and: [{and: [{and: [{x: 1}]}]}]}]}}; (function() { sanitizeQuery(q8, {maxDepth: 4}); }).should.throw( /The query object exceeds maximum depth 4/ ); }); it('Removed prohibited properties in query objects', function() { - var q1 = {where: {secret: 'guess'}}; + const q1 = {where: {secret: 'guess'}}; sanitizeQuery(q1, {prohibitedKeys: ['secret']}); q1.where.should.eql({}); - var q2 = {and: [{secret: 'guess'}, {x: 1}]}; + const q2 = {and: [{secret: 'guess'}, {x: 1}]}; sanitizeQuery(q2, {prohibitedKeys: ['secret']}); q2.should.eql({and: [{}, {x: 1}]}); }); @@ -119,8 +119,8 @@ describe('util.sanitizeQuery', function() { describe('util.parseSettings', function() { it('Parse a full url into a settings object', function() { - var url = 'mongodb://x:y@localhost:27017/mydb?w=2'; - var settings = utils.parseSettings(url); + const url = 'mongodb://x:y@localhost:27017/mydb?w=2'; + const settings = utils.parseSettings(url); should.equal(settings.hostname, 'localhost'); should.equal(settings.port, 27017); should.equal(settings.host, 'localhost'); @@ -133,8 +133,8 @@ describe('util.parseSettings', function() { }); it('Parse a url without auth into a settings object', function() { - var url = 'mongodb://localhost:27017/mydb/abc?w=2'; - var settings = utils.parseSettings(url); + const url = 'mongodb://localhost:27017/mydb/abc?w=2'; + const settings = utils.parseSettings(url); should.equal(settings.hostname, 'localhost'); should.equal(settings.port, 27017); should.equal(settings.host, 'localhost'); @@ -147,8 +147,8 @@ describe('util.parseSettings', function() { }); it('Parse a url with complex query into a settings object', function() { - var url = 'mysql://127.0.0.1:3306/mydb?x[a]=1&x[b]=2&engine=InnoDB'; - var settings = utils.parseSettings(url); + const url = 'mysql://127.0.0.1:3306/mydb?x[a]=1&x[b]=2&engine=InnoDB'; + const settings = utils.parseSettings(url); should.equal(settings.hostname, '127.0.0.1'); should.equal(settings.port, 3306); should.equal(settings.host, '127.0.0.1'); @@ -163,8 +163,8 @@ describe('util.parseSettings', function() { }); it('Parse a Memory url without auth into a settings object', function() { - var url = 'memory://?x=1'; - var settings = utils.parseSettings(url); + const url = 'memory://?x=1'; + const settings = utils.parseSettings(url); should.equal(settings.hostname, ''); should.equal(settings.user, undefined); should.equal(settings.password, undefined); @@ -177,7 +177,7 @@ describe('util.parseSettings', function() { describe('util.deepMerge', function() { it('should deep merge objects', function() { - var extras = {base: 'User', + const extras = {base: 'User', relations: {accessTokens: {model: 'accessToken', type: 'hasMany', foreignKey: 'userId'}, account: {model: 'account', type: 'belongsTo'}}, @@ -196,7 +196,7 @@ describe('util.deepMerge', function() { principalType: 'ROLE', principalId: '$owner'}, ]}; - var base = {strict: false, + const base = {strict: false, acls: [ {principalType: 'ROLE', principalId: '$everyone', @@ -210,9 +210,9 @@ describe('util.deepMerge', function() { maxTTL: 31556926, ttl: 1209600}; - var merged = deepMerge(base, extras); + const merged = deepMerge(base, extras); - var expected = {strict: false, + const expected = {strict: false, acls: [ {principalType: 'ROLE', principalId: '$everyone', @@ -249,20 +249,20 @@ describe('util.deepMerge', function() { describe('util.rankArrayElements', function() { it('should add property \'__rank\' to array elements of type object {}', function() { - var acls = [ + const acls = [ {accessType: '*', permission: 'DENY', principalType: 'ROLE', principalId: '$everyone'}, ]; - var rankedAcls = rankArrayElements(acls, 2); + const rankedAcls = rankArrayElements(acls, 2); should.equal(rankedAcls[0].__rank, 2); }); it('should not replace existing \'__rank\' property of array elements', function() { - var acls = [ + const acls = [ {accessType: '*', permission: 'DENY', principalType: 'ROLE', @@ -271,14 +271,14 @@ describe('util.rankArrayElements', function() { }, ]; - var rankedAcls = rankArrayElements(acls, 2); + const rankedAcls = rankArrayElements(acls, 2); should.equal(rankedAcls[0].__rank, 1); }); }); describe('util.sortObjectsByIds', function() { - var items = [ + const items = [ {id: 1, name: 'a'}, {id: 2, name: 'b'}, {id: 3, name: 'c'}, @@ -288,35 +288,35 @@ describe('util.sortObjectsByIds', function() { ]; it('should sort', function() { - var sorted = sortObjectsByIds('id', [6, 5, 4, 3, 2, 1], items); - var names = sorted.map(function(u) { return u.name; }); + const sorted = sortObjectsByIds('id', [6, 5, 4, 3, 2, 1], items); + const names = sorted.map(function(u) { return u.name; }); should.deepEqual(names, ['f', 'e', 'd', 'c', 'b', 'a']); }); it('should sort - partial ids', function() { - var sorted = sortObjectsByIds('id', [5, 3, 2], items); - var names = sorted.map(function(u) { return u.name; }); + const sorted = sortObjectsByIds('id', [5, 3, 2], items); + const names = sorted.map(function(u) { return u.name; }); should.deepEqual(names, ['e', 'c', 'b', 'a', 'd', 'f']); }); it('should sort - strict', function() { - var sorted = sortObjectsByIds('id', [5, 3, 2], items, true); - var names = sorted.map(function(u) { return u.name; }); + const sorted = sortObjectsByIds('id', [5, 3, 2], items, true); + const names = sorted.map(function(u) { return u.name; }); should.deepEqual(names, ['e', 'c', 'b']); }); }); describe('util.mergeIncludes', function() { function checkInputOutput(baseInclude, updateInclude, expectedInclude) { - var mergedInclude = mergeIncludes(baseInclude, updateInclude); + const mergedInclude = mergeIncludes(baseInclude, updateInclude); should.deepEqual(mergedInclude, expectedInclude, 'Merged include should match the expectation'); } it('Merge string values to object', function() { - var baseInclude = 'relation1'; - var updateInclude = 'relation2'; - var expectedInclude = [ + const baseInclude = 'relation1'; + const updateInclude = 'relation2'; + const expectedInclude = [ {relation2: true}, {relation1: true}, ]; @@ -324,9 +324,9 @@ describe('util.mergeIncludes', function() { }); it('Merge string & array values to object', function() { - var baseInclude = 'relation1'; - var updateInclude = ['relation2']; - var expectedInclude = [ + const baseInclude = 'relation1'; + const updateInclude = ['relation2']; + const expectedInclude = [ {relation2: true}, {relation1: true}, ]; @@ -334,9 +334,9 @@ describe('util.mergeIncludes', function() { }); it('Merge string & object values to object', function() { - var baseInclude = ['relation1']; - var updateInclude = {relation2: 'relation2Include'}; - var expectedInclude = [ + const baseInclude = ['relation1']; + const updateInclude = {relation2: 'relation2Include'}; + const expectedInclude = [ {relation2: 'relation2Include'}, {relation1: true}, ]; @@ -344,9 +344,9 @@ describe('util.mergeIncludes', function() { }); it('Merge array & array values to object', function() { - var baseInclude = ['relation1']; - var updateInclude = ['relation2']; - var expectedInclude = [ + const baseInclude = ['relation1']; + const updateInclude = ['relation2']; + const expectedInclude = [ {relation2: true}, {relation1: true}, ]; @@ -354,9 +354,9 @@ describe('util.mergeIncludes', function() { }); it('Merge array & object values to object', function() { - var baseInclude = ['relation1']; - var updateInclude = {relation2: 'relation2Include'}; - var expectedInclude = [ + const baseInclude = ['relation1']; + const updateInclude = {relation2: 'relation2Include'}; + const expectedInclude = [ {relation2: 'relation2Include'}, {relation1: true}, ]; @@ -364,9 +364,9 @@ describe('util.mergeIncludes', function() { }); it('Merge object & object values to object', function() { - var baseInclude = {relation1: 'relation1Include'}; - var updateInclude = {relation2: 'relation2Include'}; - var expectedInclude = [ + const baseInclude = {relation1: 'relation1Include'}; + const updateInclude = {relation2: 'relation2Include'}; + const expectedInclude = [ {relation2: 'relation2Include'}, {relation1: 'relation1Include'}, ]; @@ -374,9 +374,9 @@ describe('util.mergeIncludes', function() { }); it('Override property collision with update value', function() { - var baseInclude = {relation1: 'baseValue'}; - var updateInclude = {relation1: 'updateValue'}; - var expectedInclude = [ + const baseInclude = {relation1: 'baseValue'}; + const updateInclude = {relation1: 'updateValue'}; + const expectedInclude = [ {relation1: 'updateValue'}, ]; checkInputOutput(baseInclude, updateInclude, expectedInclude); @@ -384,21 +384,21 @@ describe('util.mergeIncludes', function() { it('Merge string includes & include with relation syntax properly', function() { - var baseInclude = 'relation1'; - var updateInclude = {relation: 'relation1'}; - var expectedInclude = [ + const baseInclude = 'relation1'; + const updateInclude = {relation: 'relation1'}; + const expectedInclude = [ {relation: 'relation1'}, ]; checkInputOutput(baseInclude, updateInclude, expectedInclude); }); it('Merge string includes & include with scope properly', function() { - var baseInclude = 'relation1'; - var updateInclude = { + const baseInclude = 'relation1'; + const updateInclude = { relation: 'relation1', scope: {include: 'relation2'}, }; - var expectedInclude = [ + const expectedInclude = [ {relation: 'relation1', scope: {include: 'relation2'}}, ]; checkInputOutput(baseInclude, updateInclude, expectedInclude); @@ -407,12 +407,12 @@ describe('util.mergeIncludes', function() { it('Merge includes with and without relation syntax properly', function() { // w & w/o relation syntax - no collision - var baseInclude = ['relation2']; - var updateInclude = { + let baseInclude = ['relation2']; + let updateInclude = { relation: 'relation1', scope: {include: 'relation2'}, }; - var expectedInclude = [{ + let expectedInclude = [{ relation: 'relation1', scope: {include: 'relation2'}, }, {relation2: true}]; @@ -433,13 +433,13 @@ describe('util.mergeIncludes', function() { }); it('Merge includes with mixture of strings, arrays & objects properly', function() { - var baseInclude = ['relation1', {relation2: true}, + const baseInclude = ['relation1', {relation2: true}, {relation: 'relation3', scope: {where: {id: 'some id'}}}, {relation: 'relation5', scope: {where: {id: 'some id'}}}, ]; - var updateInclude = ['relation4', {relation3: true}, + const updateInclude = ['relation4', {relation3: true}, {relation: 'relation2', scope: {where: {id: 'some id'}}}]; - var expectedInclude = [{relation4: true}, {relation3: true}, + const expectedInclude = [{relation4: true}, {relation3: true}, {relation: 'relation2', scope: {where: {id: 'some id'}}}, {relation1: true}, {relation: 'relation5', scope: {where: {id: 'some id'}}}]; @@ -449,57 +449,57 @@ describe('util.mergeIncludes', function() { describe('util.uniq', function() { it('should dedupe an array with duplicate number entries', function() { - var a = [1, 2, 1, 3]; - var b = uniq(a); + const a = [1, 2, 1, 3]; + const b = uniq(a); b.should.eql([1, 2, 3]); }); it('should dedupe an array with duplicate string entries', function() { - var a = ['a', 'a', 'b', 'a']; - var b = uniq(a); + const a = ['a', 'a', 'b', 'a']; + const b = uniq(a); b.should.eql(['a', 'b']); }); it('should dedupe an array with duplicate bson entries', function() { - var idOne = new ObjectID('59f9ec5dc7d59a00042f7c62'); - var idTwo = new ObjectID('59f9ec5dc7d59a00042f7c63'); - var a = [idOne, idTwo, new ObjectID('59f9ec5dc7d59a00042f7c62'), + const idOne = new ObjectID('59f9ec5dc7d59a00042f7c62'); + const idTwo = new ObjectID('59f9ec5dc7d59a00042f7c63'); + const a = [idOne, idTwo, new ObjectID('59f9ec5dc7d59a00042f7c62'), new ObjectID('59f9ec5dc7d59a00042f7c62')]; - var b = uniq(a); + const b = uniq(a); b.should.eql([idOne, idTwo]); }); it('should dedupe an array without duplicate number entries', function() { - var a = [1, 3, 2]; - var b = uniq(a); + const a = [1, 3, 2]; + const b = uniq(a); b.should.eql([1, 3, 2]); }); it('should dedupe an array without duplicate string entries', function() { - var a = ['a', 'c', 'b']; - var b = uniq(a); + const a = ['a', 'c', 'b']; + const b = uniq(a); b.should.eql(['a', 'c', 'b']); }); it('should dedupe an array without duplicate bson entries', function() { - var idOne = new ObjectID('59f9ec5dc7d59a00042f7c62'); - var idTwo = new ObjectID('59f9ec5dc7d59a00042f7c63'); - var idThree = new ObjectID('59f9ec5dc7d59a00042f7c64'); - var a = [idOne, idTwo, idThree]; - var b = uniq(a); + const idOne = new ObjectID('59f9ec5dc7d59a00042f7c62'); + const idTwo = new ObjectID('59f9ec5dc7d59a00042f7c63'); + const idThree = new ObjectID('59f9ec5dc7d59a00042f7c64'); + const a = [idOne, idTwo, idThree]; + const b = uniq(a); b.should.eql([idOne, idTwo, idThree]); }); it('should allow null/undefined array', function() { - var a = null; - var b = uniq(a); + const a = null; + const b = uniq(a); b.should.eql([]); }); it('should report error for non-array arg', function() { - var a = '1'; + const a = '1'; try { - var b = uniq(a); + const b = uniq(a); throw new Error('The test should have thrown an error'); } catch (err) { err.should.be.instanceof(Error); @@ -508,8 +508,8 @@ describe('util.uniq', function() { }); describe('util.toRegExp', function() { - var invalidDataTypes; - var validDataTypes; + let invalidDataTypes; + let validDataTypes; before(function() { invalidDataTypes = [0, true, {}, [], Function, null]; diff --git a/test/validations.test.js b/test/validations.test.js index ae0a68a0..a092b8ac 100644 --- a/test/validations.test.js +++ b/test/validations.test.js @@ -7,11 +7,11 @@ 'use strict'; /* global getSchema:false */ -var should = require('./init.js'); -var async = require('async'); +const should = require('./init.js'); +const async = require('async'); -var j = require('../'), db, User; -var ValidationError = j.ValidationError; +let j = require('../'), db, User; +const ValidationError = j.ValidationError; function getValidAttributes() { return { @@ -26,7 +26,7 @@ function getValidAttributes() { } describe('validations', function() { - var User, Entry, Employee; + let User, Entry, Employee; before(function(done) { db = getSchema(); @@ -76,7 +76,7 @@ describe('validations', function() { describe('skipping', function() { it('should NOT skip when `if` is fulfilled', function() { User.validatesPresenceOf('pendingPeriod', {if: 'createdByAdmin'}); - var user = new User; + const user = new User; user.createdByAdmin = true; user.isValid().should.be.false(); user.errors.pendingPeriod.should.eql(['can\'t be blank']); @@ -86,7 +86,7 @@ describe('validations', function() { it('should skip when `if` is NOT fulfilled', function() { User.validatesPresenceOf('pendingPeriod', {if: 'createdByAdmin'}); - var user = new User; + const user = new User; user.createdByAdmin = false; user.isValid().should.be.true(); user.errors.should.be.false(); @@ -96,7 +96,7 @@ describe('validations', function() { it('should NOT skip when `unless` is fulfilled', function() { User.validatesPresenceOf('pendingPeriod', {unless: 'createdByAdmin'}); - var user = new User; + const user = new User; user.createdByAdmin = false; user.isValid().should.be.false(); user.errors.pendingPeriod.should.eql(['can\'t be blank']); @@ -106,7 +106,7 @@ describe('validations', function() { it('should skip when `unless` is NOT fulfilled', function() { User.validatesPresenceOf('pendingPeriod', {unless: 'createdByAdmin'}); - var user = new User; + const user = new User; user.createdByAdmin = true; user.isValid().should.be.true(); user.errors.should.be.false(); @@ -121,7 +121,7 @@ describe('validations', function() { if (!this.pendingPeriod) err(); done(); }, {if: 'createdByAdmin', code: 'presence', message: 'can\'t be blank'}); - var user = new User; + const user = new User; user.createdByAdmin = false; user.isValid(function(valid) { valid.should.be.true(); @@ -135,7 +135,7 @@ describe('validations', function() { if (!this.pendingPeriod) err(); done(); }, {if: 'createdByAdmin', code: 'presence', message: 'can\'t be blank'}); - var user = new User; + const user = new User; user.createdByAdmin = true; user.isValid(function(valid) { valid.should.be.false(); @@ -149,7 +149,7 @@ describe('validations', function() { if (!this.pendingPeriod) err(); done(); }, {unless: 'createdByAdmin', code: 'presence', message: 'can\'t be blank'}); - var user = new User; + const user = new User; user.createdByAdmin = true; user.isValid(function(valid) { valid.should.be.true(); @@ -163,7 +163,7 @@ describe('validations', function() { if (!this.pendingPeriod) err(); done(); }, {unless: 'createdByAdmin', code: 'presence', message: 'can\'t be blank'}); - var user = new User; + const user = new User; user.createdByAdmin = false; user.isValid(function(valid) { valid.should.be.false(); @@ -214,7 +214,7 @@ describe('validations', function() { }); it('should be skipped by upsert when disabled via settings', function(done) { - var Customer = User.extend('Customer'); + const Customer = User.extend('Customer'); Customer.attachTo(db); db.autoupdate(function(err) { if (err) return done(err); @@ -296,10 +296,10 @@ describe('validations', function() { }); it('should return validation metadata', function() { - var expected = {name: [{validation: 'presence', options: {}}]}; + const expected = {name: [{validation: 'presence', options: {}}]}; delete User.validations; User.validatesPresenceOf('name'); - var validations = User.validations; + const validations = User.validations; validations.should.eql(expected); }); }); @@ -412,11 +412,11 @@ describe('validations', function() { it('should validate presence', function() { User.validatesPresenceOf('name', 'email'); - var validations = User.validations; + const validations = User.validations; validations.name.should.eql([{validation: 'presence', options: {}}]); validations.email.should.eql([{validation: 'presence', options: {}}]); - var u = new User; + const u = new User; u.isValid().should.not.be.true(); u.name = 1; u.isValid().should.not.be.true(); @@ -426,7 +426,7 @@ describe('validations', function() { it('should reject NaN value as a number', function() { User.validatesPresenceOf('age'); - var u = new User(); + const u = new User(); u.isValid().should.be.false(); u.age = NaN; u.isValid().should.be.false(); @@ -436,7 +436,7 @@ describe('validations', function() { it('should allow "NaN" value as a string', function() { User.validatesPresenceOf('name'); - var u = new User(); + const u = new User(); u.isValid().should.be.false(); u.name = 'NaN'; u.isValid().should.be.true(); @@ -445,7 +445,7 @@ describe('validations', function() { it('should skip validation by property (if/unless)', function() { User.validatesPresenceOf('domain', {unless: 'createdByScript'}); - var user = new User(getValidAttributes()); + const user = new User(getValidAttributes()); user.isValid().should.be.true(); user.createdByScript = false; @@ -474,7 +474,7 @@ describe('validations', function() { }); it('succeeds when validate condition is met', function(done) { - var data = {name: 'Foo-new', age: 5}; + const data = {name: 'Foo-new', age: 5}; Employee.updateAll({id: 1}, data, function(err, emp) { should.not.exist(err); @@ -506,7 +506,7 @@ describe('validations', function() { describe('absence', function() { it('should validate absence', function() { User.validatesAbsenceOf('reserved', {if: 'locked'}); - var u = new User({reserved: 'foo', locked: true}); + let u = new User({reserved: 'foo', locked: true}); u.isValid().should.not.be.true(); u.reserved = null; u.isValid().should.be.true(); @@ -532,7 +532,7 @@ describe('validations', function() { }); it('succeeds when validate condition is met', function(done) { - var data = {age: 5}; + const data = {age: 5}; Employee.updateAll({id: 1}, data, function(err, emp) { should.not.exist(err); @@ -565,11 +565,11 @@ describe('validations', function() { describe('uniqueness', function() { it('should validate uniqueness', function(done) { User.validatesUniquenessOf('email'); - var u = new User({email: 'hey'}); + const u = new User({email: 'hey'}); Boolean(u.isValid(function(valid) { valid.should.be.true(); u.save(function() { - var u2 = new User({email: 'hey'}); + const u2 = new User({email: 'hey'}); u2.isValid(function(valid) { valid.should.be.false(); done(); @@ -580,7 +580,7 @@ describe('validations', function() { it('should handle same object modification', function(done) { User.validatesUniquenessOf('email'); - var u = new User({email: 'hey'}); + const u = new User({email: 'hey'}); Boolean(u.isValid(function(valid) { valid.should.be.true(); u.save(function() { @@ -595,8 +595,8 @@ describe('validations', function() { }); it('should support multi-key constraint', function(done) { - var EMAIL = 'user@xample.com'; - var SiteUser = db.define('SiteUser', { + const EMAIL = 'user@xample.com'; + const SiteUser = db.define('SiteUser', { siteId: String, email: String, }); @@ -618,7 +618,7 @@ describe('validations', function() { ); }, function validateDuplicateUser(user2, next) { - var user3 = new SiteUser({siteId: 1, email: EMAIL}); + const user3 = new SiteUser({siteId: 1, email: EMAIL}); user3.isValid(function(valid) { valid.should.be.false(); next(); @@ -634,11 +634,11 @@ describe('validations', function() { it('should skip blank values', function(done) { User.validatesUniquenessOf('email'); - var u = new User({email: ' '}); + const u = new User({email: ' '}); Boolean(u.isValid(function(valid) { valid.should.be.true(); u.save(function() { - var u2 = new User({email: null}); + const u2 = new User({email: null}); u2.isValid(function(valid) { valid.should.be.true(); done(); @@ -652,7 +652,7 @@ describe('validations', function() { if: function() { return true; }, unless: function() { return false; }, }); - var u = new User({email: 'hello'}); + const u = new User({email: 'hello'}); Boolean(u.isValid(function(valid) { valid.should.be.true(); done(); @@ -661,7 +661,7 @@ describe('validations', function() { it('should work with id property on create', function(done) { Entry.create({id: 'entry'}, function(err, entry) { - var e = new Entry({id: 'entry'}); + const e = new Entry({id: 'entry'}); Boolean(e.isValid(function(valid) { valid.should.be.false(); done(); @@ -680,12 +680,12 @@ describe('validations', function() { it('passes case insensitive validation', function(done) { User.validatesUniquenessOf('email', {ignoreCase: true}); - var u = new User({email: 'hey'}); + const u = new User({email: 'hey'}); Boolean(u.isValid(function(valid) { valid.should.be.true(); u.save(function(err) { if (err) return done(err); - var u2 = new User({email: 'HEY'}); + const u2 = new User({email: 'HEY'}); u2.isValid(function(valid) { valid.should.be.false(); done(); @@ -696,12 +696,12 @@ describe('validations', function() { it('passed case sensitive validation', function(done) { User.validatesUniquenessOf('email', {ignoreCase: false}); - var u = new User({email: 'hey'}); + const u = new User({email: 'hey'}); Boolean(u.isValid(function(valid) { valid.should.be.true(); u.save(function(err) { if (err) return done(err); - var u2 = new User({email: 'HEY'}); + const u2 = new User({email: 'HEY'}); u2.isValid(function(valid) { valid.should.be.true(); done(); @@ -712,12 +712,12 @@ describe('validations', function() { it('passes case insensitive validation with string that needs escaping', function(done) { User.validatesUniquenessOf('email', {ignoreCase: true}); - var u = new User({email: 'me+me@my.com'}); + const u = new User({email: 'me+me@my.com'}); Boolean(u.isValid(function(valid) { valid.should.be.true(); u.save(function(err) { if (err) return done(err); - var u2 = new User({email: 'ME+ME@MY.COM'}); + const u2 = new User({email: 'ME+ME@MY.COM'}); u2.isValid(function(valid) { valid.should.be.false(); done(); @@ -728,12 +728,12 @@ describe('validations', function() { it('passed case sensitive validation with string that needs escaping', function(done) { User.validatesUniquenessOf('email', {ignoreCase: false}); - var u = new User({email: 'me+me@my.com'}); + const u = new User({email: 'me+me@my.com'}); Boolean(u.isValid(function(valid) { valid.should.be.true(); u.save(function(err) { if (err) return done(err); - var u2 = new User({email: 'ME+ME@MY.COM'}); + const u2 = new User({email: 'ME+ME@MY.COM'}); u2.isValid(function(valid) { valid.should.be.true(); done(); @@ -744,12 +744,12 @@ describe('validations', function() { it('passes partial case insensitive validation with string that needs escaping', function(done) { User.validatesUniquenessOf('email', {ignoreCase: true}); - var u = new User({email: 'also+me@my.com'}); + const u = new User({email: 'also+me@my.com'}); Boolean(u.isValid(function(valid) { valid.should.be.true(); u.save(function(err) { if (err) return done(err); - var u2 = new User({email: 'Me@My.com'}); + const u2 = new User({email: 'Me@My.com'}); u2.isValid(function(valid) { valid.should.be.true(); done(); @@ -760,12 +760,12 @@ describe('validations', function() { it('passes partial case sensitive validation with string that needs escaping', function(done) { User.validatesUniquenessOf('email', {ignoreCase: false}); - var u = new User({email: 'also+me@my.com'}); + const u = new User({email: 'also+me@my.com'}); Boolean(u.isValid(function(valid) { valid.should.be.true(); u.save(function(err) { if (err) return done(err); - var u2 = new User({email: 'Me@My.com'}); + const u2 = new User({email: 'Me@My.com'}); u2.isValid(function(valid) { valid.should.be.true(); done(); @@ -792,7 +792,7 @@ describe('validations', function() { }); it('succeeds when validate condition is met', function(done) { - var data = {name: 'Foo-new', age: 5}; + const data = {name: 'Foo-new', age: 5}; Employee.updateAll({id: 1}, data, function(err, emp) { should.not.exist(err); @@ -824,32 +824,32 @@ describe('validations', function() { describe('format', function() { it('should validate the format of valid strings', function() { User.validatesFormatOf('name', {with: /[a-z][A-Z]*$/}); - var u = new User({name: 'valid name'}); + const u = new User({name: 'valid name'}); u.isValid().should.be.true(); }); it('should validate the format of invalid strings', function() { User.validatesFormatOf('name', {with: /[a-z][A-Z]*$/}); - var u = new User({name: 'invalid name!'}); + const u = new User({name: 'invalid name!'}); u.isValid().should.be.false(); }); it('should validate the format of valid numbers', function() { User.validatesFormatOf('age', {with: /^\d+$/}); - var u = new User({age: 30}); + const u = new User({age: 30}); u.isValid().should.be.true(); }); it('should validate the format of invalid numbers', function() { User.validatesFormatOf('age', {with: /^\d+$/}); - var u = new User({age: 'thirty'}); + const u = new User({age: 'thirty'}); u.isValid().should.be.false(); }); it('should overwrite default blank message with custom format message', function() { - var CUSTOM_MESSAGE = 'custom validation message'; + const CUSTOM_MESSAGE = 'custom validation message'; User.validatesFormatOf('name', {with: /[a-z][A-Z]*$/, message: CUSTOM_MESSAGE}); - var u = new User({name: 'invalid name string 123'}); + const u = new User({name: 'invalid name string 123'}); u.isValid().should.be.false(); u.errors.should.containEql({ name: [CUSTOM_MESSAGE], @@ -861,25 +861,25 @@ describe('validations', function() { it('should skip missing values when allowing blank', function() { User.validatesFormatOf('email', {with: /^\S+@\S+\.\S+$/, allowBlank: true}); - var u = new User({}); + const u = new User({}); u.isValid().should.be.true(); }); it('should skip null values when allowing null', function() { User.validatesFormatOf('email', {with: /^\S+@\S+\.\S+$/, allowNull: true}); - var u = new User({email: null}); + const u = new User({email: null}); u.isValid().should.be.true(); }); it('should not skip missing values', function() { User.validatesFormatOf('email', {with: /^\S+@\S+\.\S+$/}); - var u = new User({}); + const u = new User({}); u.isValid().should.be.false(); }); it('should not skip null values', function() { User.validatesFormatOf('email', {with: /^\S+@\S+\.\S+$/}); - var u = new User({email: null}); + const u = new User({email: null}); u.isValid().should.be.false(); }); @@ -935,7 +935,7 @@ describe('validations', function() { }); it('succeeds when validate condition is met', function(done) { - var data = {name: 'Foo Mo', age: 5}; + const data = {name: 'Foo Mo', age: 5}; Employee.updateAll({id: 1}, data, function(err, emp) { should.not.exist(err); @@ -967,59 +967,59 @@ describe('validations', function() { describe('numericality', function() { it('passes when given numeric values', function() { User.validatesNumericalityOf('age'); - var user = new User({age: 10}); + const user = new User({age: 10}); user.isValid().should.be.true(); }); it('fails when given non-numeric values', function() { User.validatesNumericalityOf('age'); - var user = new User({age: 'notanumber'}); + const user = new User({age: 'notanumber'}); user.isValid().should.be.false(); user.errors.should.containEql({age: ['is not a number']}); }); it('fails when given undefined values', function() { User.validatesNumericalityOf('age'); - var user = new User({}); + const user = new User({}); user.isValid().should.be.false(); user.errors.should.containEql({age: ['is blank']}); }); it('skips undefined values when allowBlank option is true', function() { User.validatesNumericalityOf('age', {allowBlank: true}); - var user = new User({}); + const user = new User({}); user.isValid().should.be.true(); }); it('fails when given non-numeric values when allowBlank option is true', function() { User.validatesNumericalityOf('age', {allowBlank: true}); - var user = new User({age: 'test'}); + const user = new User({age: 'test'}); user.isValid().should.be.false(); user.errors.should.containEql({age: ['is not a number']}); }); it('fails when given null values', function() { User.validatesNumericalityOf('age'); - var user = new User({age: null}); + const user = new User({age: null}); user.isValid().should.be.false(); user.errors.should.containEql({age: ['is null']}); }); it('passes when given null values when allowNull option is true', function() { User.validatesNumericalityOf('age', {allowNull: true}); - var user = new User({age: null}); + const user = new User({age: null}); user.isValid().should.be.true(); }); it('passes when given float values', function() { User.validatesNumericalityOf('age'); - var user = new User({age: 13.37}); + const user = new User({age: 13.37}); user.isValid().should.be.true(); }); it('fails when given non-integer values when int option is true', function() { User.validatesNumericalityOf('age', {int: true}); - var user = new User({age: 13.37}); + const user = new User({age: 13.37}); user.isValid().should.be.false(); user.errors.should.match({age: /is not an integer/}); }); @@ -1042,7 +1042,7 @@ describe('validations', function() { }); it('succeeds when validate condition is met', function(done) { - var data = {name: 'Foo-new', age: 5}; + const data = {name: 'Foo-new', age: 5}; Employee.updateAll({id: 1}, data, function(err, emp) { should.not.exist(err); @@ -1159,7 +1159,7 @@ describe('validations', function() { }); it('succeeds when validate condition is met', function(done) { - var data = {name: 'Foo-new', age: 5}; + const data = {name: 'Foo-new', age: 5}; Employee.updateAll({id: 1}, data, function(err, emp) { should.not.exist(err); @@ -1258,7 +1258,7 @@ describe('validations', function() { }); it('succeeds when validate condition is met', function(done) { - var data = {name: 'Foo-new', age: 5}; + const data = {name: 'Foo-new', age: 5}; Employee.updateAll({id: 1}, data, function(err, emp) { should.not.exist(err); @@ -1308,7 +1308,7 @@ describe('validations', function() { }); it('succeeds when validate condition is met', function(done) { - var data = {name: 'Foo-new', age: 5}; + const data = {name: 'Foo-new', age: 5}; Employee.updateAll({id: 1}, data, function(err, emp) { should.not.exist(err); @@ -1342,7 +1342,7 @@ describe('validations', function() { User.validate('email', function(err) { if (this.email === 'hello') err(); }, {code: 'invalid-email'}); - var u = new User({email: 'hello'}); + const u = new User({email: 'hello'}); Boolean(u.isValid()).should.be.false(); u.errors.codes.should.eql({email: ['invalid-email']}); }); @@ -1354,7 +1354,7 @@ describe('validations', function() { err(false); // false: prevent global error message } }); - var u = new User({email: 'hello'}); + const u = new User({email: 'hello'}); Boolean(u.isValid()).should.be.false(); u.errors.should.containEql({email: ['Cannot be `hello`']}); u.errors.codes.should.eql({email: ['invalid-email']}); @@ -1367,7 +1367,7 @@ describe('validations', function() { if: function() { return true; }, unless: function() { return false; }, }); - var u = new User({email: 'hello'}); + const u = new User({email: 'hello'}); Boolean(u.isValid(function(valid) { valid.should.be.true(); done(); @@ -1376,7 +1376,7 @@ describe('validations', function() { }); describe('invalid value formatting', function() { - var origMaxLen; + let origMaxLen; beforeEach(function saveAndSetMaxLen() { origMaxLen = ValidationError.maxPropertyStringLength; }); @@ -1387,53 +1387,53 @@ describe('validations', function() { it('should truncate long strings', function() { ValidationError.maxPropertyStringLength = 9; - var err = givenValidationError('prop', '1234567890abc', 'is invalid'); + const err = givenValidationError('prop', '1234567890abc', 'is invalid'); getErrorDetails(err) .should.equal('`prop` is invalid (value: "12...abc").'); }); it('should truncate long objects', function() { ValidationError.maxPropertyStringLength = 12; - var err = givenValidationError('prop', {foo: 'bar'}, 'is invalid'); + const err = givenValidationError('prop', {foo: 'bar'}, 'is invalid'); getErrorDetails(err) .should.equal('`prop` is invalid (value: { foo:... }).'); }); it('should truncate long arrays', function() { ValidationError.maxPropertyStringLength = 12; - var err = givenValidationError('prop', [{a: 1, b: 2}], 'is invalid'); + const err = givenValidationError('prop', [{a: 1, b: 2}], 'is invalid'); getErrorDetails(err) .should.equal('`prop` is invalid (value: [ { a...} ]).'); }); it('should print only top-level object properties', function() { - var err = givenValidationError('prop', {a: {b: 'c'}}, 'is invalid'); + const err = givenValidationError('prop', {a: {b: 'c'}}, 'is invalid'); getErrorDetails(err) .should.equal('`prop` is invalid (value: { a: [Object] }).'); }); it('should print only top-level props of objects in array', function() { - var err = givenValidationError('prop', [{a: {b: 'c'}}], 'is invalid'); + const err = givenValidationError('prop', [{a: {b: 'c'}}], 'is invalid'); getErrorDetails(err) .should.equal('`prop` is invalid (value: [ { a: [Object] } ]).'); }); it('should exclude colors from Model values', function() { - var obj = new User(); + const obj = new User(); obj.email = 'test@example.com'; - var err = givenValidationError('user', obj, 'is invalid'); + const err = givenValidationError('user', obj, 'is invalid'); getErrorDetails(err).should.equal( '`user` is invalid (value: { email: \'test@example.com\' }).' ); }); function givenValidationError(propertyName, propertyValue, errorMessage) { - var jsonVal = {}; + const jsonVal = {}; jsonVal[propertyName] = propertyValue; - var errorVal = {}; + const errorVal = {}; errorVal[propertyName] = [errorMessage]; - var obj = { + const obj = { errors: errorVal, toJSON: function() { return jsonVal; }, }; @@ -1448,31 +1448,31 @@ describe('validations', function() { describe('date', function() { it('should validate a date object', function() { User.validatesDateOf('updatedAt'); - var u = new User({updatedAt: new Date()}); + const u = new User({updatedAt: new Date()}); u.isValid().should.be.true(); }); it('should validate a date string', function() { User.validatesDateOf('updatedAt'); - var u = new User({updatedAt: '2000-01-01'}); + const u = new User({updatedAt: '2000-01-01'}); u.isValid().should.be.true(); }); it('should validate a null date', function() { User.validatesDateOf('updatedAt'); - var u = new User({updatedAt: null}); + const u = new User({updatedAt: null}); u.isValid().should.be.true(); }); it('should validate an undefined date', function() { User.validatesDateOf('updatedAt'); - var u = new User({updatedAt: undefined}); + const u = new User({updatedAt: undefined}); u.isValid().should.be.true(); }); it('should validate an invalid date string', function() { User.validatesDateOf('updatedAt'); - var u = new User({updatedAt: 'invalid date string'}); + const u = new User({updatedAt: 'invalid date string'}); u.isValid().should.not.be.true(); u.errors.should.containEql({ updatedAt: ['is not a valid date'], @@ -1483,7 +1483,7 @@ describe('validations', function() { }); it('should attach validation by default to all date properties', function() { - var AnotherUser = db.define('User', { + const AnotherUser = db.define('User', { email: String, name: String, password: String, @@ -1496,7 +1496,7 @@ describe('validations', function() { createdByScript: Boolean, updatedAt: Date, }); - var u = new AnotherUser({updatedAt: 'invalid date string'}); + const u = new AnotherUser({updatedAt: 'invalid date string'}); u.isValid().should.not.be.true(); u.errors.should.containEql({ updatedAt: ['is not a valid date'], @@ -1507,9 +1507,9 @@ describe('validations', function() { }); it('should overwrite default blank message with custom format message', function() { - var CUSTOM_MESSAGE = 'custom validation message'; + const CUSTOM_MESSAGE = 'custom validation message'; User.validatesDateOf('updatedAt', {message: CUSTOM_MESSAGE}); - var u = new User({updatedAt: 'invalid date string'}); + const u = new User({updatedAt: 'invalid date string'}); u.isValid().should.not.be.true(); u.errors.should.containEql({ updatedAt: [CUSTOM_MESSAGE], From 9e0f624ad5e71a7995d255162a2df02bef1f4cdb Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Miroslav=20Bajto=C5=A1?= Date: Fri, 7 Dec 2018 16:22:36 +0100 Subject: [PATCH 3/3] manually fix remaining problems --- lib/connectors/kv-memory.js | 11 +++++------ lib/connectors/memory.js | 4 ++-- lib/connectors/transient.js | 3 ++- lib/dao.js | 14 ++++++++------ lib/datasource.js | 2 +- lib/geo.js | 8 ++++---- lib/include.js | 6 ++++-- lib/model-builder.js | 23 ++++++++++------------- lib/model.js | 12 ++++++------ lib/relation-definition.js | 3 +-- lib/scope.js | 7 ++++--- lib/validations.js | 11 ++++++----- test/datasource.test.js | 12 ++++++------ test/datatype.test.js | 6 ++++-- test/discovery.test.js | 3 ++- test/hooks.test.js | 9 +++++---- test/include.test.js | 8 ++++---- test/loopback-dl.test.js | 3 +-- test/manipulation.test.js | 4 ++-- test/memory.test.js | 3 ++- test/persistence-hooks.suite.js | 3 +-- test/relations.test.js | 3 ++- test/schema.test.js | 4 +++- test/scope.test.js | 6 +++--- test/validations.test.js | 5 +++-- 25 files changed, 91 insertions(+), 82 deletions(-) diff --git a/lib/connectors/kv-memory.js b/lib/connectors/kv-memory.js index 9962ff49..8ac84c0a 100644 --- a/lib/connectors/kv-memory.js +++ b/lib/connectors/kv-memory.js @@ -33,14 +33,13 @@ KeyValueMemoryConnector.prototype._setupRegularCleanup = function() { // in order to release memory. Note that GET operation checks // key expiration too, the scheduled cleanup is merely a performance // optimization. - const self = this; - var timer = this._cleanupTimer = setInterval( - function() { - if (self && self._removeExpiredItems) { - self._removeExpiredItems(); + this._cleanupTimer = setInterval( + () => { + if (this && this._removeExpiredItems) { + this._removeExpiredItems(); } else { // The datasource/connector was destroyed - cancel the timer - clearInterval(timer); + clearInterval(this._cleanupTimer); } }, 1000 diff --git a/lib/connectors/memory.js b/lib/connectors/memory.js index 9d44c8d1..d3f37fe0 100644 --- a/lib/connectors/memory.js +++ b/lib/connectors/memory.js @@ -119,7 +119,7 @@ Memory.prototype.setupFileQueue = function() { const file = self.settings.file; if (task.operation === 'write') { // Flush out the models/ids - var data = JSON.stringify({ + const data = JSON.stringify({ ids: self.ids, models: self.cache, }, null, ' '); @@ -130,7 +130,7 @@ Memory.prototype.setupFileQueue = function() { callback(err, task.data); }); } else if (task.operation === 'read') { - debug('Reading cache from %s: %s', file, data); + debug('Reading cache from %s', file); fs.readFile(file, { encoding: 'utf8', flag: 'r', diff --git a/lib/connectors/transient.js b/lib/connectors/transient.js index 8baa5b5d..6edb9739 100644 --- a/lib/connectors/transient.js +++ b/lib/connectors/transient.js @@ -91,8 +91,9 @@ Transient.prototype.count = function count(model, callback, where) { Transient.prototype.create = function create(model, data, callback) { const props = this._models[model].properties; const idName = this.idName(model); + let id = undefined; if (idName && props[idName]) { - var id = this.getIdValue(model, data) || this.generateId(model, data, idName); + id = this.getIdValue(model, data) || this.generateId(model, data, idName); id = (props[idName] && props[idName].type && props[idName].type(id)) || id; this.setIdValue(model, data, id); } diff --git a/lib/dao.js b/lib/dao.js index a6f95d57..cf7dc7ea 100644 --- a/lib/dao.js +++ b/lib/dao.js @@ -89,9 +89,9 @@ function convertSubsetOfPropertiesByType(inst, data) { function applyStrictCheck(model, strict, data, inst, cb) { const props = model.definition.properties; const keys = Object.keys(data); - let result = {}, key; + const result = {}; for (let i = 0; i < keys.length; i++) { - key = keys[i]; + const key = keys[i]; if (props[key]) { result[key] = data[key]; } else if (strict && strict !== 'filter') { @@ -1105,7 +1105,8 @@ DataAccessObject.findOrCreate = function findOrCreate(query, data, options, cb) if (err) return cb(err); data = ctx.data; - let obj, Model = self.lookupModel(data); + const Model = self.lookupModel(data); + let obj; if (data) { obj = new Model(data, {fields: query.fields, applySetters: false, @@ -2594,9 +2595,10 @@ DataAccessObject.replaceById = function(id, data, options, cb) { const pkName = idName(this); if (!data[pkName]) data[pkName] = id; + let Model = this; + let inst; try { - var Model = this; - var inst = new Model(data, {persisted: true}); + inst = new Model(data, {persisted: true}); const enforced = {}; this.applyProperties(enforced, inst); @@ -2808,7 +2810,7 @@ function(data, options, cb) { for (let i = 0, n = idNames.length; i < n; i++) { const idName = idNames[i]; if (data[idName] !== undefined && !idEquals(data[idName], inst[idName])) { - var err = new Error(g.f('{{id}} cannot be updated from ' + + const err = new Error(g.f('{{id}} cannot be updated from ' + '%s to %s when {{forceId}} is set to true', inst[idName], data[idName])); err.statusCode = 400; diff --git a/lib/datasource.js b/lib/datasource.js index fa300e36..e15debdc 100644 --- a/lib/datasource.js +++ b/lib/datasource.js @@ -2275,7 +2275,7 @@ DataSource.prototype.transaction = function(execute, options, cb) { }); }); - var done = function(err) { + let done = function(err) { if (err) { transaction.rollback(function(error) { cb(err || error); diff --git a/lib/geo.js b/lib/geo.js index 094fd5e7..9314b64c 100644 --- a/lib/geo.js +++ b/lib/geo.js @@ -12,6 +12,10 @@ const assert = require('assert'); */ exports.nearFilter = function nearFilter(where) { + const nearResults = []; + nearSearch(where); + return (!nearResults.length ? false : nearResults); + function nearSearch(clause, parentKeys) { if (typeof clause !== 'object') { return false; @@ -41,10 +45,6 @@ exports.nearFilter = function nearFilter(where) { } }); } - var nearResults = []; - nearSearch(where); - - return (!nearResults.length ? false : nearResults); }; /*! diff --git a/lib/include.js b/lib/include.js index 28e9e6f3..117c6e4d 100644 --- a/lib/include.js +++ b/lib/include.js @@ -505,8 +505,10 @@ Inclusion.include = function(objects, include, options, cb) { function linkManyToMany(target, next) { const targetId = target[modelToIdName]; if (!targetId) { - const err = new Error(g.f('LinkManyToMany received target that doesn\'t contain required "%s"', - modelToIdName)); + const err = new Error(g.f( + 'LinkManyToMany received target that doesn\'t contain required "%s"', + modelToIdName + )); return next(err); } const objList = targetObjsMap[targetId.toString()]; diff --git a/lib/model-builder.js b/lib/model-builder.js index c9908095..cd831f43 100644 --- a/lib/model-builder.js +++ b/lib/model-builder.js @@ -229,7 +229,7 @@ ModelBuilder.prototype.define = function defineClass(className, properties, sett hiddenProperty(ModelClass, '_warned', {}); // inherit ModelBaseClass static methods - for (var i in ModelBaseClass) { + for (const i in ModelBaseClass) { // We need to skip properties that are already in the subclass, for example, the event emitter methods if (i !== '_mixins' && !(i in ModelClass)) { ModelClass[i] = ModelBaseClass[i]; @@ -306,7 +306,7 @@ ModelBuilder.prototype.define = function defineClass(className, properties, sett idNames = modelDefinition.idNames(); // Reload it after rebuild // Create a virtual property 'id' if (idNames.length === 1) { - var idProp = idNames[0]; + const idProp = idNames[0]; if (idProp !== 'id') { Object.defineProperty(ModelClass.prototype, 'id', { get: function() { @@ -323,7 +323,7 @@ ModelBuilder.prototype.define = function defineClass(className, properties, sett get: function() { const compositeId = {}; const idNames = ModelClass.definition.idNames(); - for (var i = 0, p; i < idNames.length; i++) { + for (let i = 0, p; i < idNames.length; i++) { p = idNames[i]; compositeId[p] = this.__data[p]; } @@ -339,7 +339,7 @@ ModelBuilder.prototype.define = function defineClass(className, properties, sett let forceId = ModelClass.settings.forceId; if (idNames.length > 0) { const idName = modelDefinition.idName(); - idProp = ModelClass.definition.rawProperties[idName]; + const idProp = ModelClass.definition.rawProperties[idName]; if (idProp.generated && forceId !== false) { forceId = 'auto'; } else if (!idProp.generated && forceId === 'auto') { @@ -624,7 +624,7 @@ ModelBuilder.prototype.define = function defineClass(className, properties, sett const props = ModelClass.definition.properties; let keys = Object.keys(props); let size = keys.length; - for (i = 0; i < size; i++) { + for (let i = 0; i < size; i++) { const propertyName = keys[i]; ModelClass.registerProperty(propertyName); } @@ -632,8 +632,8 @@ ModelBuilder.prototype.define = function defineClass(className, properties, sett const mixinSettings = settings.mixins || {}; keys = Object.keys(mixinSettings); size = keys.length; - for (i = 0; i < size; i++) { - var name = keys[i]; + for (let i = 0; i < size; i++) { + const name = keys[i]; let mixin = mixinSettings[name]; if (mixin === true) { mixin = {}; @@ -929,12 +929,9 @@ ModelBuilder.prototype.buildModels = function(schemas, createModel) { for (let s = 0, n = schemas.length; s < n; s++) { const name = this.getSchemaName(schemas[s].name); schemas[s].name = name; - var model; - 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); - } + const model = typeof createModel === 'function' ? + createModel(schemas[s].name, schemas[s].properties, schemas[s].options) : + this.define(schemas[s].name, schemas[s].properties, schemas[s].options); models[name] = model; relations = relations.concat(model.definition.relations); } diff --git a/lib/model.js b/lib/model.js index d4c2aad1..5b2bc33e 100644 --- a/lib/model.js +++ b/lib/model.js @@ -187,7 +187,7 @@ ModelBaseClass.prototype._initProperties = function(data, options) { let size = keys.length; let p, propVal; - for (var k = 0; k < size; k++) { + for (let k = 0; k < size; k++) { p = keys[k]; propVal = data[p]; if (typeof propVal === 'function') { @@ -208,7 +208,7 @@ ModelBaseClass.prototype._initProperties = function(data, options) { } else if (ctor.relations[p]) { const relationType = ctor.relations[p].type; - var modelTo; + let modelTo; if (!properties[p]) { modelTo = ctor.relations[p].modelTo || ModelBaseClass; const multiple = ctor.relations[p].multiple; @@ -272,7 +272,7 @@ ModelBaseClass.prototype._initProperties = function(data, options) { size = keys.length; - for (k = 0; k < size; k++) { + for (let k = 0; k < size; k++) { p = keys[k]; propVal = self.__data[p]; const type = properties[p].type; @@ -446,7 +446,7 @@ ModelBaseClass.prototype.toObject = function(onlySchema, removeHidden, removePro let keys = Object.keys(props); let propertyName, val; - for (var i = 0; i < keys.length; i++) { + for (let i = 0; i < keys.length; i++) { propertyName = keys[i]; val = self[propertyName]; @@ -483,7 +483,7 @@ ModelBaseClass.prototype.toObject = function(onlySchema, removeHidden, removePro // triggered to add it to __data keys = Object.keys(self); let size = keys.length; - for (i = 0; i < size; i++) { + for (let i = 0; i < size; i++) { propertyName = keys[i]; if (props[propertyName]) { continue; @@ -517,7 +517,7 @@ ModelBaseClass.prototype.toObject = function(onlySchema, removeHidden, removePro // Now continue to check __data keys = Object.keys(self.__data); size = keys.length; - for (i = 0; i < size; i++) { + for (let i = 0; i < size; i++) { propertyName = keys[i]; if (propertyName.indexOf('__') === 0) { continue; diff --git a/lib/relation-definition.js b/lib/relation-definition.js index 7e5e4eb8..5bf58d07 100644 --- a/lib/relation-definition.js +++ b/lib/relation-definition.js @@ -111,14 +111,13 @@ function bindRelationMethods(relation, relationMethod, definition) { function preventFkOverride(inst, data, fkProp) { if (!fkProp) return undefined; if (data[fkProp] !== undefined && !idEquals(data[fkProp], inst[fkProp])) { - var err = new Error(g.f( + return new Error(g.f( 'Cannot override foreign key %s from %s to %s', fkProp, inst[fkProp], data[fkProp] )); } - return err; } /** diff --git a/lib/scope.js b/lib/scope.js index 17ffd93b..a163a0bb 100644 --- a/lib/scope.js +++ b/lib/scope.js @@ -99,10 +99,11 @@ ScopeDefinition.prototype.related = function(receiver, scopeParams, condOrRefres const scopeOnRelatedModel = params.collect && params.include.scope !== null && typeof params.include.scope === 'object'; + let filter, queryRelated; if (scopeOnRelatedModel) { - var filter = params.include; + filter = params.include; // The filter applied on relatedModel - var queryRelated = filter.scope; + queryRelated = filter.scope; delete params.include.scope; } @@ -239,7 +240,7 @@ function defineScope(cls, targetClass, name, params, methods, options) { const targetModel = definition.targetModel(this); const self = this; - var f = function(condOrRefresh, options, cb) { + const f = function(condOrRefresh, options, cb) { if (arguments.length === 0) { if (typeof f.value === 'function') { return f.value(self); diff --git a/lib/validations.js b/lib/validations.js index fb978ca7..82184e0a 100644 --- a/lib/validations.js +++ b/lib/validations.js @@ -513,7 +513,8 @@ function getConfigurator(name, opts) { */ Validatable.prototype.isValid = function(callback, data, options) { options = options || {}; - let valid = true, inst = this, wait = 0, async = false; + let valid = true, wait = 0, async = false; + const inst = this; const validations = this.constructor.validations; const reportDiscardedProperties = this.__strict && @@ -539,8 +540,8 @@ Validatable.prototype.isValid = function(callback, data, options) { }); this.trigger('validate', function(validationsDone) { - let inst = this, - asyncFail = false; + const inst = this; + let asyncFail = false; const attrs = Object.keys(validations || {}); @@ -687,7 +688,7 @@ function skipValidation(inst, conf, kind) { return !doValidate; } -var defaultMessages = { +const defaultMessages = { presence: 'can\'t be blank', absence: 'can\'t be set', 'unknown-property': 'is not defined in the model', @@ -894,7 +895,7 @@ function ValidationError(obj) { util.inherits(ValidationError, Error); -var errorHasStackProperty = !!(new Error).stack; +const errorHasStackProperty = !!(new Error).stack; ValidationError.maxPropertyStringLength = 32; diff --git a/test/datasource.test.js b/test/datasource.test.js index 920f66c7..aa34c27f 100644 --- a/test/datasource.test.js +++ b/test/datasource.test.js @@ -108,7 +108,7 @@ describe('DataSource', function() { * new DataSource(connectorInstance) */ it('should accept resolved connector', function() { - var mockConnector = { + const mockConnector = { name: 'loopback-connector-mock', initialize: function(ds, cb) { ds.connector = mockConnector; @@ -125,7 +125,7 @@ describe('DataSource', function() { * new DataSource(dsName, connectorInstance) */ it('should accept dsName and resolved connector', function() { - var mockConnector = { + const mockConnector = { name: 'loopback-connector-mock', initialize: function(ds, cb) { ds.connector = mockConnector; @@ -142,7 +142,7 @@ describe('DataSource', function() { * new DataSource(connectorInstance, settings) */ it('should accept resolved connector and settings', function() { - var mockConnector = { + const mockConnector = { name: 'loopback-connector-mock', initialize: function(ds, cb) { ds.connector = mockConnector; @@ -156,7 +156,7 @@ describe('DataSource', function() { }); it('should set states correctly with eager connect', function(done) { - var mockConnector = { + const mockConnector = { name: 'loopback-connector-mock', initialize: function(ds, cb) { ds.connector = mockConnector; @@ -211,7 +211,7 @@ describe('DataSource', function() { }); it('should set states correctly with deferred connect', function(done) { - var mockConnector = { + const mockConnector = { name: 'loopback-connector-mock', initialize: function(ds, cb) { ds.connector = mockConnector; @@ -267,7 +267,7 @@ describe('DataSource', function() { }); it('should set states correctly with lazyConnect = true', function(done) { - var mockConnector = { + const mockConnector = { name: 'loopback-connector-mock', initialize: function(ds, cb) { ds.connector = mockConnector; diff --git a/test/datatype.test.js b/test/datatype.test.js index 1dbe12c1..ee069191 100644 --- a/test/datatype.test.js +++ b/test/datatype.test.js @@ -53,7 +53,8 @@ describe('datatypes', function() { }); it('should keep types when get read data from db', function(done) { - let d = new Date('2015-01-01T12:00:00'), id; + const d = new Date('2015-01-01T12:00:00'); + let id; Model.create({ str: 'hello', date: d, num: '3', bool: 1, list: ['test'], arr: [1, 'str'], @@ -101,7 +102,8 @@ describe('datatypes', function() { }); it('should respect data types when updating attributes', function(done) { - const d = new Date, id; + const d = new Date; + let id; Model.create({ str: 'hello', date: d, num: '3', bool: 1}, function(err, m) { diff --git a/test/discovery.test.js b/test/discovery.test.js index cf501762..0f569c0f 100644 --- a/test/discovery.test.js +++ b/test/discovery.test.js @@ -632,7 +632,8 @@ describe('Mock connector', function() { }); describe('Default memory connector', function() { - let ds, nonExistantError = 'Table \'NONEXISTENT\' does not exist.'; + const nonExistantError = 'Table \'NONEXISTENT\' does not exist.'; + let ds; before(function() { ds = new DataSource({connector: 'memory'}); diff --git a/test/hooks.test.js b/test/hooks.test.js index 65ffa9c4..bf4e1e0f 100644 --- a/test/hooks.test.js +++ b/test/hooks.test.js @@ -9,12 +9,12 @@ /* global getSchema:false */ const should = require('./init.js'); -let j = require('../'), +const j = require('../'), Schema = j.Schema, AbstractClass = j.AbstractClass, - Hookable = j.Hookable, + Hookable = j.Hookable; - db, User; +let db, User; describe('hooks', function() { before(function(done) { @@ -436,7 +436,8 @@ describe('hooks', function() { }); function addHooks(name, done) { - let called = false, random = String(Math.floor(Math.random() * 1000)); + const random = String(Math.floor(Math.random() * 1000)); + let called = false; User['before' + name] = function(next, data) { called = true; data.email = random; diff --git a/test/include.test.js b/test/include.test.js index aac7e472..4703bbf6 100644 --- a/test/include.test.js +++ b/test/include.test.js @@ -1493,10 +1493,10 @@ describe('include', function() { }); }); -var createdUsers = []; -var createdPassports = []; -var createdProfiles = []; -var createdPosts = []; +let createdUsers = []; +let createdPassports = []; +let createdProfiles = []; +let createdPosts = []; function setup(done) { db = getSchema(); City = db.define('City'); diff --git a/test/loopback-dl.test.js b/test/loopback-dl.test.js index 669a7dce..91f70bea 100644 --- a/test/loopback-dl.test.js +++ b/test/loopback-dl.test.js @@ -615,8 +615,7 @@ describe('DataSource define model', function() { it('updates instances with unknown properties in non-strict mode', function(done) { const ds = new DataSource('memory');// define models - let Post; - Post = ds.define('Post', { + const Post = ds.define('Post', { title: {type: String, length: 255, index: true}, content: {type: String}, }); diff --git a/test/manipulation.test.js b/test/manipulation.test.js index 164939c2..9c939c0d 100644 --- a/test/manipulation.test.js +++ b/test/manipulation.test.js @@ -137,7 +137,7 @@ describe('manipulation', function() { }); it('should not return instance of object', function(done) { - var person = Person.create(function(err, p) { + const person = Person.create(function(err, p) { if (err) return done(err); should.exist(p.id); if (person) person.should.not.be.an.instanceOf(Person); @@ -254,7 +254,7 @@ describe('manipulation', function() { {name: 'Boltay'}, {}, ]; - var res = Person.create(batch, function(e, ps) { + const res = Person.create(batch, function(e, ps) { if (res) res.should.not.be.instanceOf(Array); should.not.exist(e); should.exist(ps); diff --git a/test/memory.test.js b/test/memory.test.js index 8ff100d8..16dccc21 100644 --- a/test/memory.test.js +++ b/test/memory.test.js @@ -923,7 +923,8 @@ describe('Unoptimized connector', function() { }); describe('Memory connector with options', function() { - let ds, savedOptions = {}, Post; + const savedOptions = {}; + let ds, Post; before(function() { ds = new DataSource({connector: 'memory'}); diff --git a/test/persistence-hooks.suite.js b/test/persistence-hooks.suite.js index 398e2a95..8f1c0081 100644 --- a/test/persistence-hooks.suite.js +++ b/test/persistence-hooks.suite.js @@ -143,8 +143,7 @@ module.exports = function(dataSource, should, connectorCapabilities) { it('triggers the loaded hook multiple times when multiple instances exist when near filter is used', function(done) { - let hookMonitorGeoModel; - hookMonitorGeoModel = new HookMonitor({includeModelName: false}); + const hookMonitorGeoModel = new HookMonitor({includeModelName: false}); function monitorHookExecutionGeoModel(hookNames) { hookMonitorGeoModel.install(GeoModel, hookNames); diff --git a/test/relations.test.js b/test/relations.test.js index 5bd3b5f2..1d5b0970 100644 --- a/test/relations.test.js +++ b/test/relations.test.js @@ -2784,7 +2784,8 @@ describe('relations', function() { scope4.should.have.property('include', 'imageable'); }); - let article, employee, pictures = []; + let article, employee; + const pictures = []; it('should create polymorphic relation - article', function(done) { Article.create({name: 'Article 1'}, function(err, a) { if (err) return done(err); diff --git a/test/schema.test.js b/test/schema.test.js index 3b58df9a..eefe04e4 100644 --- a/test/schema.test.js +++ b/test/schema.test.js @@ -9,7 +9,9 @@ /* global getSchema:false */ const should = require('./init.js'); -let db = getSchema(), slave = getSchema(), Model, SlaveModel; +const db = getSchema(); +const slave = getSchema(); +let Model, SlaveModel; describe('dataSource', function() { it('should define Model', function() { diff --git a/test/scope.test.js b/test/scope.test.js index 495ed60f..b73d47a8 100644 --- a/test/scope.test.js +++ b/test/scope.test.js @@ -284,7 +284,7 @@ describe('scope - filtered count, updateAll and destroyAll', function() { verify(); }); - var verify = function() { + function verify() { Station.flagged.count(function(err, count) { if (err) return done(err); count.should.equal(2); @@ -300,7 +300,7 @@ describe('scope - filtered count, updateAll and destroyAll', function() { verify(); }); - var verify = function() { + function verify() { Station.flagged.count(function(err, count) { if (err) return done(err); count.should.equal(2); @@ -315,7 +315,7 @@ describe('scope - filtered count, updateAll and destroyAll', function() { verify(); }); - var verify = function() { + function verify() { Station.ordered.count(function(err, count) { if (err) return done(err); count.should.equal(2); diff --git a/test/validations.test.js b/test/validations.test.js index a092b8ac..c336b4c0 100644 --- a/test/validations.test.js +++ b/test/validations.test.js @@ -10,7 +10,8 @@ const should = require('./init.js'); const async = require('async'); -let j = require('../'), db, User; +const j = require('../'); +let db, User; const ValidationError = j.ValidationError; function getValidAttributes() { @@ -1521,7 +1522,7 @@ describe('validations', function() { }); }); -var empData = [{ +const empData = [{ id: 1, name: 'Foo', age: 1,