From 4c4d05fe87506182269852a7913b09038305caec Mon Sep 17 00:00:00 2001 From: Nora Date: Fri, 2 Aug 2019 09:50:51 -0400 Subject: [PATCH] chore: update deps and fix lint violations --- index.js | 2 +- lib/binary-packer.js | 8 +- lib/connector.js | 20 +- lib/json-string-packer.js | 12 +- lib/model-key-composer.js | 19 +- lib/parameterized-sql.js | 10 +- lib/sql.js | 398 +++++++++++++------------- lib/transaction.js | 16 +- lib/utils.js | 6 +- package.json | 13 +- test/automigrate.test.js | 8 +- test/binary-packer.test.js | 10 +- test/connectors/test-sql-connector.js | 44 +-- test/json-string-packer.test.js | 10 +- test/model-key-composer.test.js | 9 +- test/smoke.test.js | 4 +- test/sql.test.js | 132 ++++----- test/transaction.test.js | 25 +- 18 files changed, 378 insertions(+), 368 deletions(-) diff --git a/index.js b/index.js index c31768a..69db571 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.Connector = require('./lib/connector'); diff --git a/lib/binary-packer.js b/lib/binary-packer.js index 2a04a62..f0a94af 100644 --- a/lib/binary-packer.js +++ b/lib/binary-packer.js @@ -5,8 +5,8 @@ 'use strict'; -var createPromiseCallback = require('./utils').createPromiseCallback; -var msgpack = require('msgpack5'); +const createPromiseCallback = require('./utils').createPromiseCallback; +const msgpack = require('msgpack5'); module.exports = BinaryPacker; @@ -36,7 +36,7 @@ BinaryPacker.prototype.encode = function(value, cb) { try { // msgpack5 returns https://www.npmjs.com/package/bl instead of Buffer // use .slice() to convert to a Buffer - var data = this._packer.encode(value).slice(); + const data = this._packer.encode(value).slice(); setImmediate(function() { cb(null, data); }); @@ -59,7 +59,7 @@ BinaryPacker.prototype.encode = function(value, cb) { BinaryPacker.prototype.decode = function(binary, cb) { cb = cb || createPromiseCallback(); try { - var value = this._packer.decode(binary); + const value = this._packer.decode(binary); setImmediate(function() { cb(null, value); }); diff --git a/lib/connector.js b/lib/connector.js index 609c9e4..14484d9 100644 --- a/lib/connector.js +++ b/lib/connector.js @@ -4,9 +4,9 @@ // License text available at https://opensource.org/licenses/MIT 'use strict'; -var SG = require('strong-globalize'); -var g = SG(); -var debug = require('debug')('loopback:connector'); +const SG = require('strong-globalize'); +const g = SG(); +const debug = require('debug')('loopback:connector'); module.exports = Connector; @@ -62,9 +62,9 @@ Connector.prototype.getDefaultIdType = function(prop) { */ Connector.prototype.generateUniqueId = function(modelName) { - var idType = this.getDefaultIdType && this.getDefaultIdType(); - var isTypeFunction = (typeof idType === 'function'); - var id = this.generateValueByColumnType ? this.generateValueByColumnType(idType) : + const idType = this.getDefaultIdType && this.getDefaultIdType(); + const isTypeFunction = (typeof idType === 'function'); + const id = this.generateValueByColumnType ? this.generateValueByColumnType(idType) : (typeof idType === 'function' ? idType() : null); return id; }; @@ -124,7 +124,7 @@ Connector.prototype.getModelDefinition = function(modelName) { * @returns {Object} The connector specific settings */ Connector.prototype.getConnectorSpecificSettings = function(modelName) { - var settings = this.getModelDefinition(modelName).settings || {}; + const settings = this.getModelDefinition(modelName).settings || {}; return settings[this.name]; }; @@ -181,7 +181,7 @@ Connector.getNestedPropertyDefinition = function(definition, propPath) { * @returns {DataSource} The data source */ Connector.prototype.getDataSource = function(model) { - var m = this.getModelDefinition(model); + const m = this.getModelDefinition(model); if (!m) { debug('Model not found: ' + model); } @@ -214,7 +214,7 @@ Connector.prototype.idNames = function(model) { * of the primary key */ Connector.prototype.id = function(model, prop) { - var p = this.getModelDefinition(model).properties[prop]; + const p = this.getModelDefinition(model).properties[prop]; return p && p.id; }; @@ -234,7 +234,7 @@ Connector.prototype.define = function(modelDefinition) { * @param {Object} propertyDefinition The object for property definition */ Connector.prototype.defineProperty = function(model, propertyName, propertyDefinition) { - var modelDef = this.getModelDefinition(model); + const modelDef = this.getModelDefinition(model); modelDef.properties[propertyName] = propertyDefinition; }; diff --git a/lib/json-string-packer.js b/lib/json-string-packer.js index 30baaf2..290ed3b 100644 --- a/lib/json-string-packer.js +++ b/lib/json-string-packer.js @@ -5,11 +5,11 @@ 'use strict'; -var createPromiseCallback = require('./utils').createPromiseCallback; +const createPromiseCallback = require('./utils').createPromiseCallback; module.exports = JSONStringPacker; -var ISO_DATE_REGEXP = /^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2}(?:\.\d*))(?:Z|(\+|-)([\d|:]*))?$/; +const ISO_DATE_REGEXP = /^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2}(?:\.\d*))(?:Z|(\+|-)([\d|:]*))?$/; /** * Create a new Packer instance that can be used to convert between JavaScript @@ -31,11 +31,11 @@ function JSONStringPacker(encoding) { * @promise */ JSONStringPacker.prototype.encode = function(value, cb) { - var encoding = this.encoding; + const encoding = this.encoding; cb = cb || createPromiseCallback(); try { - var data = JSON.stringify(value, function(key, value) { + const data = JSON.stringify(value, function(key, value) { if (Buffer.isBuffer(this[key])) { return { type: 'Buffer', @@ -66,11 +66,11 @@ JSONStringPacker.prototype.encode = function(value, cb) { * @promise */ JSONStringPacker.prototype.decode = function(jsonString, cb) { - var encoding = this.encoding; + const encoding = this.encoding; cb = cb || createPromiseCallback(); try { - var value = JSON.parse(jsonString, function(k, v) { + const value = JSON.parse(jsonString, function(k, v) { if (v && v.type && v.type === 'Buffer') { return new Buffer(v.data, encoding); } diff --git a/lib/model-key-composer.js b/lib/model-key-composer.js index b438047..0a59058 100644 --- a/lib/model-key-composer.js +++ b/lib/model-key-composer.js @@ -5,9 +5,9 @@ 'use strict'; -var createPromiseCallback = require('./utils').createPromiseCallback; -var debug = require('debug')('loopback:connector:model-key-composer'); -var g = require('strong-globalize')(); +const createPromiseCallback = require('./utils').createPromiseCallback; +const debug = require('debug')('loopback:connector:model-key-composer'); +const g = require('strong-globalize')(); /** * Build a single key string from a tuple (modelName, key). @@ -27,7 +27,7 @@ exports.compose = function composeKeyFromModelNameAndKey(modelName, key, cb) { // Escape model name to prevent collision // 'model' + 'foo:bar' --vs-- 'model:foo' + 'bar' - var value = encodeURIComponent(modelName) + ':' + key; + const value = encodeURIComponent(modelName) + ':' + key; setImmediate(function() { cb(null, value); @@ -35,7 +35,7 @@ exports.compose = function composeKeyFromModelNameAndKey(modelName, key, cb) { return cb.promise; }; -var PARSE_KEY_REGEX = /^([^:]*):(.*)/; +const PARSE_KEY_REGEX = /^([^:]*):(.*)/; /** * Parse a composed key string into a tuple (modelName, key). @@ -53,9 +53,9 @@ var PARSE_KEY_REGEX = /^([^:]*):(.*)/; exports.parse = function(composed, cb) { cb = cb || createPromiseCallback(); - var matchResult = composed.match(PARSE_KEY_REGEX); + const matchResult = composed.match(PARSE_KEY_REGEX); if (matchResult) { - var result = { + const result = { modelName: matchResult[1], key: matchResult[2], }; @@ -64,9 +64,10 @@ exports.parse = function(composed, cb) { }); } else { debug('Invalid key - missing model-name prefix: %s', composed); - var err = new Error(g.f( + const err = new Error(g.f( 'Invalid key %j - missing model-name prefix', - composed)); + composed + )); err.code = 'NO_MODEL_PREFIX'; setImmediate(function() { cb(err); diff --git a/lib/parameterized-sql.js b/lib/parameterized-sql.js index 7c320fc..ceb2537 100644 --- a/lib/parameterized-sql.js +++ b/lib/parameterized-sql.js @@ -4,8 +4,8 @@ // License text available at https://opensource.org/licenses/MIT 'use strict'; -var assert = require('assert'); -var PLACEHOLDER = '?'; +const assert = require('assert'); +const PLACEHOLDER = '?'; module.exports = ParameterizedSQL; @@ -34,7 +34,7 @@ function ParameterizedSQL(sql, params) { assert(typeof this.sql === 'string', 'sql must be a string'); assert(Array.isArray(this.params), 'params must be an array'); - var parts = this.sql.split(PLACEHOLDER); + const parts = this.sql.split(PLACEHOLDER); assert(parts.length - 1 === this.params.length, 'The number of ? (' + (parts.length - 1) + ') in the sql (' + this.sql + ') must match the number of params (' + @@ -96,8 +96,8 @@ ParameterizedSQL.append = function(currentStmt, stmt, separator) { */ ParameterizedSQL.join = function(sqls, separator) { assert(Array.isArray(sqls), 'sqls must be an array'); - var ps = new ParameterizedSQL('', []); - for (var i = 0, n = sqls.length; i < n; i++) { + const ps = new ParameterizedSQL('', []); + for (let i = 0, n = sqls.length; i < n; i++) { this.append(ps, sqls[i], separator); } return ps; diff --git a/lib/sql.js b/lib/sql.js index 8e9665d..ae0515e 100644 --- a/lib/sql.js +++ b/lib/sql.js @@ -4,16 +4,16 @@ // License text available at https://opensource.org/licenses/MIT 'use strict'; -var SG = require('strong-globalize'); -var g = SG(); +const SG = require('strong-globalize'); +const g = SG(); -var util = require('util'); -var async = require('async'); -var assert = require('assert'); -var Connector = require('./connector'); -var debug = require('debug')('loopback:connector:sql'); -var ParameterizedSQL = require('./parameterized-sql'); -var Transaction = require('./transaction'); +const util = require('util'); +const async = require('async'); +const assert = require('assert'); +const Connector = require('./connector'); +const debug = require('debug')('loopback:connector:sql'); +const ParameterizedSQL = require('./parameterized-sql'); +const Transaction = require('./transaction'); module.exports = SQLConnector; @@ -35,7 +35,7 @@ util.inherits(SQLConnector, Connector); SQLConnector.ParameterizedSQL = ParameterizedSQL; // The generic placeholder -var PLACEHOLDER = SQLConnector.PLACEHOLDER = ParameterizedSQL.PLACEHOLDER; +const PLACEHOLDER = SQLConnector.PLACEHOLDER = ParameterizedSQL.PLACEHOLDER; SQLConnector.Transaction = Transaction; @@ -51,8 +51,8 @@ SQLConnector.prototype.relational = true; * @param {String} methodName Method name */ SQLConnector.prototype.invokeSuper = function(methodName) { - var args = [].slice.call(arguments, 1); - var superMethod = this.constructor.super_.prototype[methodName]; + const args = [].slice.call(arguments, 1); + const superMethod = this.constructor.super_.prototype[methodName]; return superMethod.apply(this, args); }; @@ -63,7 +63,7 @@ SQLConnector.prototype.invokeSuper = function(methodName) { * @param {Function} [cb] The callback function */ SQLConnector.prototype.autoupdate = function(models, cb) { - var self = this; + const self = this; if ((!cb) && ('function' === typeof models)) { cb = models; models = undefined; @@ -98,7 +98,7 @@ SQLConnector.prototype.autoupdate = function(models, cb) { * @param {Function} [cb] The callback function */ SQLConnector.prototype.isActual = function(models, cb) { - var self = this; + const self = this; if ((!cb) && ('function' === typeof models)) { cb = models; @@ -111,7 +111,7 @@ SQLConnector.prototype.isActual = function(models, cb) { models = models || Object.keys(this._models); - var changes = []; + let changes = []; async.each(models, function(model, done) { self.getTableStatus(model, function(err, fields) { changes = changes.concat(self.getAddModifyColumns(model, fields)); @@ -122,14 +122,14 @@ SQLConnector.prototype.isActual = function(models, cb) { if (err) { return cb && cb(err); } - var actual = (changes.length === 0); + const actual = (changes.length === 0); if (cb) cb(null, actual); }); }; SQLConnector.prototype.getAddModifyColumns = function(model, fields) { - var sql = []; - var self = this; + let sql = []; + const self = this; sql = sql.concat(self.getColumnsToAdd(model, fields)); return sql; }; @@ -139,8 +139,8 @@ SQLConnector.prototype.getColumnsToAdd = function(model, fields) { }; SQLConnector.prototype.getDropColumns = function(model, fields) { - var sql = []; - var self = this; + let sql = []; + const self = this; sql = sql.concat(self.getColumnsToDrop(model, fields)); return sql; }; @@ -151,8 +151,8 @@ SQLConnector.prototype.getColumnsToDrop = function(model, fields) { SQLConnector.prototype.searchForPropertyInActual = function(model, propName, actualFields) { - var self = this; - var found = false; + const self = this; + let found = false; actualFields.forEach(function(f) { if (f.column === self.column(model, propName)) { found = f; @@ -163,8 +163,8 @@ SQLConnector.prototype.searchForPropertyInActual = function(model, propName, }; SQLConnector.prototype.addPropertyToActual = function(model, propName) { - var self = this; - var sqlCommand = self.columnEscaped(model, propName) + + const self = this; + const sqlCommand = self.columnEscaped(model, propName) + ' ' + self.columnDataType(model, propName) + (self.isNullable(self.getPropertyDefinition(model, propName)) ? '' : ' NOT NULL'); @@ -172,16 +172,16 @@ SQLConnector.prototype.addPropertyToActual = function(model, propName) { }; SQLConnector.prototype.columnDataType = function(model, property) { - var columnMetadata = this.columnMetadata(model, property); - var colType = columnMetadata && columnMetadata.dataType; + const columnMetadata = this.columnMetadata(model, property); + let colType = columnMetadata && columnMetadata.dataType; if (colType) { colType = colType.toUpperCase(); } - var prop = this.getModelDefinition(model).properties[property]; + const prop = this.getModelDefinition(model).properties[property]; if (!prop) { return null; } - var colLength = columnMetadata && columnMetadata.dataLength || + const colLength = columnMetadata && columnMetadata.dataLength || prop.length || prop.limit; if (colType && colLength) { return colType + '(' + colLength + ')'; @@ -198,10 +198,10 @@ SQLConnector.prototype.propertyHasNotBeenDeleted = function(model, propName) { }; SQLConnector.prototype.applySqlChanges = function(model, pendingChanges, cb) { - var self = this; + const self = this; if (pendingChanges.length) { - var thisQuery = 'ALTER TABLE ' + self.tableEscaped(model); - var ranOnce = false; + let thisQuery = 'ALTER TABLE ' + self.tableEscaped(model); + let ranOnce = false; pendingChanges.forEach(function(change) { if (ranOnce) { thisQuery = thisQuery + ' '; @@ -234,8 +234,8 @@ SQLConnector.prototype.checkFieldAndIndex = function(fields, indexes) { * @param {Function} cb The callback function */ SQLConnector.prototype.getTableStatus = function(model, cb) { - var fields, indexes; - var self = this; + let fields, indexes; + const self = this; this.showFields(model, function(err, data) { if (err) return cb(err); @@ -314,8 +314,8 @@ SQLConnector.prototype.getDefaultSchemaName = function() { */ SQLConnector.prototype.schema = function(model) { // Check if there is a 'schema' property for connector - var dbMeta = this.getConnectorSpecificSettings(model); - var schemaName = (dbMeta && (dbMeta.schema || dbMeta.schemaName)) || + const dbMeta = this.getConnectorSpecificSettings(model); + const schemaName = (dbMeta && (dbMeta.schema || dbMeta.schemaName)) || (this.settings.schema || this.settings.schemaName) || this.getDefaultSchemaName(); return schemaName; @@ -338,8 +338,8 @@ SQLConnector.prototype.schema = function(model) { * @param {String} model The model name */ SQLConnector.prototype.table = function(model) { - var dbMeta = this.getConnectorSpecificSettings(model); - var tableName; + const dbMeta = this.getConnectorSpecificSettings(model); + let tableName; if (dbMeta) { tableName = dbMeta.table || dbMeta.tableName; if (tableName) { @@ -373,8 +373,8 @@ SQLConnector.prototype.table = function(model) { * @returns {String} The column name */ SQLConnector.prototype.column = function(model, property) { - var prop = this.getPropertyDefinition(model, property); - var columnName; + const prop = this.getPropertyDefinition(model, property); + let columnName; if (prop && prop[this.name]) { columnName = prop[this.name].column || prop[this.name].columnName; if (columnName) { @@ -411,8 +411,8 @@ SQLConnector.prototype.columnMetadata = function(model, property) { * @returns {String} The property name for a given column */ SQLConnector.prototype.propertyName = function(model, column) { - var props = this.getModelDefinition(model).properties; - for (var p in props) { + const props = this.getModelDefinition(model).properties; + for (const p in props) { if (this.column(model, p) === column) { return p; } @@ -426,8 +426,8 @@ SQLConnector.prototype.propertyName = function(model, column) { * @returns {String} The id column name */ SQLConnector.prototype.idColumn = function(model) { - var name = this.getDataSource(model).idColumnName(model); - var dbName = this.dbName; + let name = this.getDataSource(model).idColumnName(model); + const dbName = this.dbName; if (typeof dbName === 'function') { name = dbName(name); } @@ -488,7 +488,7 @@ function isIdValuePresent(idValue, cb, returningNull) { * @returns {*} The escaped id column value */ SQLConnector.prototype.idColumnValue = function(model, idValue) { - var idProp = this.getDataSource(model).idProperty(model); + const idProp = this.getDataSource(model).idProperty(model); if (typeof this.toColumnValue === 'function') { return this.toColumnValue(idProp, idValue); } else { @@ -517,9 +517,9 @@ SQLConnector.prototype.parameterize = function(ps) { // The value is parameterized, for example // {sql: 'to_point(?,?)', values: [1, 2]} - var parts = ps.sql.split(PLACEHOLDER); - var clause = []; - for (var j = 0, m = parts.length; j < m; j++) { + const parts = ps.sql.split(PLACEHOLDER); + const clause = []; + for (let j = 0, m = parts.length; j < m; j++) { // Replace ? with the keyed placeholder, such as :5 clause.push(parts[j]); if (j !== parts.length - 1) { @@ -538,8 +538,8 @@ SQLConnector.prototype.parameterize = function(ps) { * @returns {ParameterizedSQL} */ SQLConnector.prototype.buildInsertInto = function(model, fields, options) { - var stmt = new ParameterizedSQL('INSERT INTO ' + this.tableEscaped(model)); - var columnNames = fields.names.join(','); + const stmt = new ParameterizedSQL('INSERT INTO ' + this.tableEscaped(model)); + const columnNames = fields.names.join(','); if (columnNames) { stmt.merge('(' + columnNames + ')', ''); } @@ -576,18 +576,18 @@ SQLConnector.prototype.buildInsertDefaultValues = function(model, data, options) * @returns {string} The INSERT SQL statement */ SQLConnector.prototype.buildInsert = function(model, data, options) { - var fields = this.buildFields(model, data); - var insertStmt = this.buildInsertInto(model, fields, options); - var columnValues = fields.columnValues; - var fieldNames = fields.names; + const fields = this.buildFields(model, data); + const insertStmt = this.buildInsertInto(model, fields, options); + const columnValues = fields.columnValues; + const fieldNames = fields.names; if (fieldNames.length) { - var values = ParameterizedSQL.join(columnValues, ','); + const values = ParameterizedSQL.join(columnValues, ','); values.sql = 'VALUES(' + values.sql + ')'; insertStmt.merge(values); } else { insertStmt.merge(this.buildInsertDefaultValues(model, data, options)); } - var returning = this.buildInsertReturning(model, data, options); + const returning = this.buildInsertReturning(model, data, options); if (returning) { insertStmt.merge(returning); } @@ -621,13 +621,13 @@ SQLConnector.prototype.execute = function(sql, params, options, callback) { assert(typeof options === 'object', 'options must be an object'); assert(typeof callback === 'function', 'callback must be a function'); - var self = this; + const self = this; if (!this.dataSource.connected) { return this.dataSource.once('connected', function() { self.execute(sql, params, options, callback); }); } - var context = { + const context = { req: { sql: sql, params: params, @@ -659,13 +659,13 @@ SQLConnector.prototype.execute = function(sql, params, options, callback) { * @param {Function} [callback] The callback function */ SQLConnector.prototype.create = function(model, data, options, callback) { - var self = this; - var stmt = this.buildInsert(model, data, options); + const self = this; + const stmt = this.buildInsert(model, data, options); this.execute(stmt.sql, stmt.params, options, function(err, info) { if (err) { callback(err); } else { - var insertedId = self.getInsertedId(model, info); + const insertedId = self.getInsertedId(model, info); callback(err, insertedId); } }); @@ -679,19 +679,19 @@ SQLConnector.prototype.create = function(model, data, options, callback) { * @param {Function} cb The callback function */ SQLConnector.prototype.save = function(model, data, options, cb) { - var idName = this.idName(model); - var idValue = data[idName]; + const idName = this.idName(model); + const idValue = data[idName]; if (!isIdValuePresent(idValue, cb)) { return; } - var where = {}; + const where = {}; where[idName] = idValue; - var updateStmt = new ParameterizedSQL('UPDATE ' + this.tableEscaped(model)); + let updateStmt = new ParameterizedSQL('UPDATE ' + this.tableEscaped(model)); updateStmt.merge(this.buildFieldsForUpdate(model, data)); - var whereStmt = this.buildWhere(model, where); + const whereStmt = this.buildWhere(model, where); updateStmt.merge(whereStmt); updateStmt = this.parameterize(updateStmt); this.execute(updateStmt.sql, updateStmt.params, options, @@ -711,10 +711,10 @@ SQLConnector.prototype.exists = function(model, id, options, cb) { if (!isIdValuePresent(id, cb, true)) { return; } - var idName = this.idName(model); - var where = {}; + const idName = this.idName(model); + const where = {}; where[idName] = id; - var selectStmt = new ParameterizedSQL( + let selectStmt = new ParameterizedSQL( 'SELECT 1 FROM ' + this.tableEscaped(model) + ' WHERE ' + this.idColumnEscaped(model) ); @@ -752,8 +752,8 @@ SQLConnector.prototype.destroy = function(model, id, options, cb) { if (!isIdValuePresent(id, cb, true)) { return; } - var idName = this.idName(model); - var where = {}; + const idName = this.idName(model); + const where = {}; where[idName] = id; this.destroyAll(model, where, options, cb); }; @@ -770,7 +770,7 @@ Connector.defineAliases(SQLConnector.prototype, 'destroy', * @returns {ParameterizedSQL} The SQL DELETE FROM statement */ SQLConnector.prototype.buildDelete = function(model, where, options) { - var deleteStmt = new ParameterizedSQL('DELETE FROM ' + + const deleteStmt = new ParameterizedSQL('DELETE FROM ' + this.tableEscaped(model)); deleteStmt.merge(this.buildWhere(model, where)); return this.parameterize(deleteStmt); @@ -785,7 +785,7 @@ SQLConnector.prototype.buildDelete = function(model, where, options) { * @param {Function} cb The callback function */ SQLConnector.prototype.destroyAll = function(model, where, options, cb) { - var stmt = this.buildDelete(model, where, options); + const stmt = this.buildDelete(model, where, options); this._executeAlteringQuery(model, stmt.sql, stmt.params, options, cb || NOOP); }; @@ -808,21 +808,22 @@ Connector.defineAliases(SQLConnector.prototype, 'destroyAll', ['deleteAll']); */ SQLConnector.prototype.updateAttributes = function(model, id, data, options, cb) { if (!isIdValuePresent(id, cb)) return; - var where = this._buildWhereObjById(model, id, data); + const where = this._buildWhereObjById(model, id, data); this.updateAll(model, where, data, options, function(err, info) { if (err) return cb(err); if (info.count === 0) { return cb(errorIdNotFoundForUpdate(where.id)); } else { return cb(null, info); - }; + } }); }; function errorIdNotFoundForUpdate(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; } @@ -839,7 +840,7 @@ function errorIdNotFoundForUpdate(idValue) { */ SQLConnector.prototype.replaceById = function(model, id, data, options, cb) { if (!isIdValuePresent(id, cb)) return; - var where = this._buildWhereObjById(model, id, data); + const where = this._buildWhereObjById(model, id, data); this._replace(model, where, data, options, cb); }; @@ -851,9 +852,9 @@ SQLConnector.prototype.replaceById = function(model, id, data, options, cb) { * @private */ SQLConnector.prototype._buildWhereObjById = function(model, id, data) { - var idName = this.idName(model); + const idName = this.idName(model); delete data[idName]; - var where = {}; + const where = {}; where[idName] = id; return where; }; @@ -868,7 +869,7 @@ SQLConnector.prototype._buildWhereObjById = function(model, id, data) { * @returns {ParameterizedSQL} The UPDATE SQL statement */ SQLConnector.prototype.buildUpdate = function(model, where, data, options) { - var fields = this.buildFieldsForUpdate(model, data); + const fields = this.buildFieldsForUpdate(model, data); return this._constructUpdateQuery(model, where, fields); }; @@ -882,7 +883,7 @@ SQLConnector.prototype.buildUpdate = function(model, where, data, options) { * @returns {ParameterizedSQL} The UPDATE SQL statement for replacing fields */ SQLConnector.prototype.buildReplace = function(model, where, data, options) { - var fields = this.buildFieldsForReplace(model, data); + const fields = this.buildFieldsForReplace(model, data); return this._constructUpdateQuery(model, where, fields); }; @@ -894,8 +895,8 @@ SQLConnector.prototype.buildReplace = function(model, where, data, options) { * @private */ SQLConnector.prototype._constructUpdateQuery = function(model, where, fields) { - var updateClause = new ParameterizedSQL('UPDATE ' + this.tableEscaped(model)); - var whereClause = this.buildWhere(model, where); + const updateClause = new ParameterizedSQL('UPDATE ' + this.tableEscaped(model)); + const whereClause = this.buildWhere(model, where); updateClause.merge([fields, whereClause]); return this.parameterize(updateClause); }; @@ -910,7 +911,7 @@ SQLConnector.prototype._constructUpdateQuery = function(model, where, fields) { * @param {Function} cb The callback function */ SQLConnector.prototype.update = function(model, where, data, options, cb) { - var stmt = this.buildUpdate(model, where, data, options); + const stmt = this.buildUpdate(model, where, data, options); this._executeAlteringQuery(model, stmt.sql, stmt.params, options, cb || NOOP); }; @@ -924,12 +925,12 @@ SQLConnector.prototype.update = function(model, where, data, options, cb) { * @param {Function} cb The callback function */ SQLConnector.prototype._replace = function(model, where, data, options, cb) { - var self = this; - var stmt = this.buildReplace(model, where, data, options); + const self = this; + const stmt = this.buildReplace(model, where, data, options); this.execute(stmt.sql, stmt.params, options, function(err, info) { if (err) return cb(err); - var affectedRows = self.getCountForAffectedRows(model, info); - var rowCount = typeof (affectedRows) === 'number' ? + const affectedRows = self.getCountForAffectedRows(model, info); + const rowCount = typeof (affectedRows) === 'number' ? affectedRows : info.affectedRows; if (rowCount === 0) { return cb(errorIdNotFoundForReplace(where.id)); @@ -940,16 +941,16 @@ SQLConnector.prototype._replace = function(model, where, data, options, cb) { }; function errorIdNotFoundForReplace(idValue) { - var msg = g.f('Could not replace. Object with id %s does not exist!', idValue); - var error = new Error(msg); + const msg = g.f('Could not replace. Object with id %s does not exist!', idValue); + const error = new Error(msg); error.statusCode = error.status = 404; return error; } SQLConnector.prototype._executeAlteringQuery = function(model, sql, params, options, cb) { - var self = this; + const self = this; this.execute(sql, params, options, function(err, info) { - var affectedRows = self.getCountForAffectedRows(model, info); + const affectedRows = self.getCountForAffectedRows(model, info); cb(err, {count: affectedRows}); }); }; @@ -965,7 +966,7 @@ Connector.defineAliases(SQLConnector.prototype, 'replace', ['replaceAll']); * @returns {ParameterizedSQL} The SQL WHERE clause */ SQLConnector.prototype.buildWhere = function(model, where) { - var whereClause = this._buildWhere(model, where); + const whereClause = this._buildWhere(model, where); if (whereClause.sql) { whereClause.sql = 'WHERE ' + whereClause.sql; } @@ -983,8 +984,8 @@ SQLConnector.prototype.buildWhere = function(model, where) { SQLConnector.prototype.buildExpression = function(columnName, operator, columnValue, propertyValue) { function buildClause(columnValue, separator, grouping) { - var values = []; - for (var i = 0, n = columnValue.length; i < n; i++) { + const values = []; + for (let i = 0, n = columnValue.length; i < n; i++) { if (columnValue[i] instanceof ParameterizedSQL) { values.push(columnValue[i]); } else { @@ -992,15 +993,15 @@ function(columnName, operator, columnValue, propertyValue) { } } separator = separator || ','; - var clause = ParameterizedSQL.join(values, separator); + const clause = ParameterizedSQL.join(values, separator); if (grouping) { clause.sql = '(' + clause.sql + ')'; } return clause; } - var sqlExp = columnName; - var clause; + let sqlExp = columnName; + let clause; if (columnValue instanceof ParameterizedSQL) { clause = columnValue; } else { @@ -1049,7 +1050,7 @@ function(columnName, operator, columnValue, propertyValue) { sqlExp += ' REGEXP '; break; } - var stmt = ParameterizedSQL.join([sqlExp, clause], ''); + const stmt = ParameterizedSQL.join([sqlExp, clause], ''); return stmt; }; @@ -1060,7 +1061,7 @@ function(columnName, operator, columnValue, propertyValue) { * @returns {ParameterizedSQL} */ SQLConnector.prototype._buildWhere = function(model, where) { - var columnValue, sqlExp; + let columnValue, sqlExp; if (!where) { return new ParameterizedSQL(''); } @@ -1068,20 +1069,20 @@ SQLConnector.prototype._buildWhere = function(model, where) { debug('Invalid value for where: %j', where); return new ParameterizedSQL(''); } - var self = this; - var props = self.getModelDefinition(model).properties; + const self = this; + const props = self.getModelDefinition(model).properties; - var whereStmts = []; - for (var key in where) { - var stmt = new ParameterizedSQL('', []); + const whereStmts = []; + for (const key in where) { + const stmt = new ParameterizedSQL('', []); // Handle and/or operators if (key === 'and' || key === 'or') { - var branches = []; - var branchParams = []; - var clauses = where[key]; + const branches = []; + let branchParams = []; + const clauses = where[key]; if (Array.isArray(clauses)) { - for (var i = 0, n = clauses.length; i < n; i++) { - var stmtForClause = self._buildWhere(model, clauses[i]); + for (let i = 0, n = clauses.length; i < n; i++) { + const stmtForClause = self._buildWhere(model, clauses[i]); if (stmtForClause.sql) { stmtForClause.sql = '(' + stmtForClause.sql + ')'; branchParams = branchParams.concat(stmtForClause.params); @@ -1097,27 +1098,27 @@ SQLConnector.prototype._buildWhere = function(model, where) { } // The value is not an array, fall back to regular fields } - var p = props[key]; + const p = props[key]; if (p == null) { // Unknown property, ignore it debug('Unknown property %s is skipped for model %s', key, model); continue; } // eslint-disable one-var - var expression = where[key]; - var columnName = self.columnEscaped(model, key); + let expression = where[key]; + const columnName = self.columnEscaped(model, key); // eslint-enable one-var if (expression === null || expression === undefined) { stmt.merge(columnName + ' IS NULL'); } else if (expression && expression.constructor === Object) { - var operator = Object.keys(expression)[0]; + const operator = Object.keys(expression)[0]; // Get the expression without the operator expression = expression[operator]; if (operator === 'inq' || operator === 'nin' || operator === 'between') { columnValue = []; if (Array.isArray(expression)) { // Column value is a list - for (var j = 0, m = expression.length; j < m; j++) { + for (let j = 0, m = expression.length; j < m; j++) { columnValue.push(this.toColumnValue(p, expression[j])); } } else { @@ -1125,8 +1126,8 @@ SQLConnector.prototype._buildWhere = function(model, where) { } if (operator === 'between') { // BETWEEN v1 AND v2 - var v1 = columnValue[0] === undefined ? null : columnValue[0]; - var v2 = columnValue[1] === undefined ? null : columnValue[1]; + const v1 = columnValue[0] === undefined ? null : columnValue[0]; + const v2 = columnValue[1] === undefined ? null : columnValue[1]; columnValue = [v1, v2]; } else { // IN (v1,v2,v3) or NOT IN (v1,v2,v3) @@ -1165,13 +1166,13 @@ SQLConnector.prototype._buildWhere = function(model, where) { } whereStmts.push(stmt); } - var params = []; - var sqls = []; - for (var k = 0, s = whereStmts.length; k < s; k++) { + let params = []; + const sqls = []; + for (let k = 0, s = whereStmts.length; k < s; k++) { sqls.push(whereStmts[k].sql); params = params.concat(whereStmts[k].params); } - var whereStmt = new ParameterizedSQL({ + const whereStmt = new ParameterizedSQL({ sql: sqls.join(' AND '), params: params, }); @@ -1188,13 +1189,13 @@ SQLConnector.prototype.buildOrderBy = function(model, order) { if (!order) { return ''; } - var self = this; + const self = this; if (typeof order === 'string') { order = [order]; } - var clauses = []; - for (var i = 0, n = order.length; i < n; i++) { - var t = order[i].split(/[\s,]+/); + const clauses = []; + for (let i = 0, n = order.length; i < n; i++) { + const t = order[i].split(/[\s,]+/); if (t.length === 1) { clauses.push(self.columnEscaped(model, order[i])); } else { @@ -1212,7 +1213,7 @@ SQLConnector.prototype.buildOrderBy = function(model, order) { * @returns {{names: Array, values: Array, properties: Array}} */ SQLConnector.prototype.buildFields = function(model, data, excludeIds) { - var keys = Object.keys(data); + const keys = Object.keys(data); return this._buildFieldsForKeys(model, data, keys, excludeIds); }; @@ -1224,8 +1225,8 @@ SQLConnector.prototype.buildFields = function(model, data, excludeIds) { * @returns {{names: Array, values: Array, properties: Array}} */ SQLConnector.prototype.buildReplaceFields = function(model, data, excludeIds) { - var props = this.getModelDefinition(model).properties; - var keys = Object.keys(props); + const props = this.getModelDefinition(model).properties; + const keys = Object.keys(props); return this._buildFieldsForKeys(model, data, keys, excludeIds); }; @@ -1237,15 +1238,15 @@ SQLConnector.prototype.buildReplaceFields = function(model, data, excludeIds) { * @private */ SQLConnector.prototype._buildFieldsForKeys = function(model, data, keys, excludeIds) { - var props = this.getModelDefinition(model).properties; - var fields = { + const props = this.getModelDefinition(model).properties; + const fields = { names: [], // field names columnValues: [], // an array of ParameterizedSQL properties: [], // model properties }; - for (var i = 0, n = keys.length; i < n; i++) { - var key = keys[i]; - var p = props[key]; + for (let i = 0, n = keys.length; i < n; i++) { + const key = keys[i]; + const p = props[key]; if (p == null) { // Unknown property, ignore it debug('Unknown property %s is skipped for model %s', key, model); @@ -1255,8 +1256,8 @@ SQLConnector.prototype._buildFieldsForKeys = function(model, data, keys, exclude if (excludeIds && p.id) { continue; } - var k = this.columnEscaped(model, key); - var v = this.toColumnValue(p, data[key]); + const k = this.columnEscaped(model, key); + const v = this.toColumnValue(p, data[key]); if (v !== undefined) { fields.names.push(k); if (v instanceof ParameterizedSQL) { @@ -1281,7 +1282,7 @@ SQLConnector.prototype.buildFieldsForUpdate = function(model, data, excludeIds) if (excludeIds === undefined) { excludeIds = true; } - var fields = this.buildFields(model, data, excludeIds); + const fields = this.buildFields(model, data, excludeIds); return this._constructUpdateParameterizedSQL(fields); }; @@ -1296,7 +1297,7 @@ SQLConnector.prototype.buildFieldsForReplace = function(model, data, excludeIds) if (excludeIds === undefined) { excludeIds = true; } - var fields = this.buildReplaceFields(model, data, excludeIds); + const fields = this.buildReplaceFields(model, data, excludeIds); return this._constructUpdateParameterizedSQL(fields); }; @@ -1306,9 +1307,9 @@ SQLConnector.prototype.buildFieldsForReplace = function(model, data, excludeIds) * @private */ SQLConnector.prototype._constructUpdateParameterizedSQL = function(fields) { - var columns = new ParameterizedSQL(''); - for (var i = 0, n = fields.names.length; i < n; i++) { - var clause = ParameterizedSQL.append(fields.names[i], + const columns = new ParameterizedSQL(''); + for (let i = 0, n = fields.names.length; i < n; i++) { + const clause = ParameterizedSQL.append(fields.names[i], fields.columnValues[i], '='); columns.merge(clause, ','); } @@ -1323,13 +1324,13 @@ SQLConnector.prototype._constructUpdateParameterizedSQL = function(fields) { * @returns {string} Comma separated string of escaped column names */ SQLConnector.prototype.buildColumnNames = function(model, filter) { - var fieldsFilter = filter && filter.fields; - var cols = this.getModelDefinition(model).properties; + const fieldsFilter = filter && filter.fields; + const cols = this.getModelDefinition(model).properties; if (!cols) { return '*'; } - var self = this; - var keys = Object.keys(cols); + const self = this; + let keys = Object.keys(cols); if (Array.isArray(fieldsFilter) && fieldsFilter.length > 0) { // Not empty array, including all the fields that are valid properties keys = fieldsFilter.filter(function(f) { @@ -1338,8 +1339,8 @@ SQLConnector.prototype.buildColumnNames = function(model, filter) { } else if ('object' === typeof fieldsFilter && Object.keys(fieldsFilter).length > 0) { // { field1: boolean, field2: boolean ... } - var included = []; - var excluded = []; + const included = []; + const excluded = []; keys.forEach(function(k) { if (fieldsFilter[k]) { included.push(k); @@ -1351,12 +1352,12 @@ SQLConnector.prototype.buildColumnNames = function(model, filter) { keys = included; } else if (excluded.length > 0) { excluded.forEach(function(e) { - var index = keys.indexOf(e); + const index = keys.indexOf(e); keys.splice(index, 1); }); } } - var names = keys.map(function(c) { + const names = keys.map(function(c) { return self.columnEscaped(model, c); }); return names.join(','); @@ -1371,20 +1372,19 @@ SQLConnector.prototype.buildColumnNames = function(model, filter) { */ SQLConnector.prototype.buildSelect = function(model, filter, options) { if (!filter.order) { - var idNames = this.idNames(model); + const idNames = this.idNames(model); if (idNames && idNames.length) { filter.order = idNames; } } - var selectStmt = new ParameterizedSQL('SELECT ' + + let selectStmt = new ParameterizedSQL('SELECT ' + this.buildColumnNames(model, filter) + - ' FROM ' + this.tableEscaped(model) - ); + ' FROM ' + this.tableEscaped(model)); if (filter) { if (filter.where) { - var whereStmt = this.buildWhere(model, filter.where); + const whereStmt = this.buildWhere(model, filter.where); selectStmt.merge(whereStmt); } @@ -1394,7 +1394,8 @@ SQLConnector.prototype.buildSelect = function(model, filter, options) { if (filter.limit || filter.skip || filter.offset) { selectStmt = this.applyPagination( - model, selectStmt, filter); + model, selectStmt, filter + ); } } return this.parameterize(selectStmt); @@ -1411,12 +1412,12 @@ function(model, rowData) { if (rowData == null) { return rowData; } - var props = this.getModelDefinition(model).properties; - var data = {}; - for (var p in props) { - var columnName = this.column(model, p); + const props = this.getModelDefinition(model).properties; + const data = {}; + for (const p in props) { + const columnName = this.column(model, p); // Load properties from the row - var columnValue = this.fromColumnValue(props[p], rowData[columnName]); + const columnValue = this.fromColumnValue(props[p], rowData[columnName]); if (columnValue !== undefined) { data[p] = columnValue; } @@ -1438,21 +1439,22 @@ function(model, rowData) { * @param {Function} [cb] The cb function */ SQLConnector.prototype.all = function find(model, filter, options, cb) { - var self = this; + const self = this; // Order by id if no order is specified filter = filter || {}; - var stmt = this.buildSelect(model, filter, options); + const stmt = this.buildSelect(model, filter, options); this.execute(stmt.sql, stmt.params, options, function(err, data) { if (err) { return cb(err, []); } - var objs = data.map(function(obj) { + const objs = data.map(function(obj) { return self.fromRow(model, obj); }); if (filter && filter.include) { self.getModelDefinition(model).model.include( - objs, filter.include, options, cb); + objs, filter.include, options, cb + ); } else { cb(null, objs); } @@ -1483,18 +1485,18 @@ Connector.defineAliases(SQLConnector.prototype, 'all', ['findAll']); SQLConnector.prototype.find = function(model, id, options, cb) { if (id == null) { process.nextTick(function() { - var err = new Error(g.f('id value is required')); + const err = new Error(g.f('id value is required')); if (cb) { cb(err); } }); return; } - var where = {}; - var idName = this.idName(model); + const where = {}; + const idName = this.idName(model); where[idName] = id; - var filter = {limit: 1, offset: 0, order: idName, where: where}; + const filter = {limit: 1, offset: 0, order: idName, where: where}; return this.all(model, filter, options, function(err, results) { cb(err, (results && results[0]) || null); }); @@ -1514,12 +1516,12 @@ SQLConnector.prototype.count = function(model, where, options, cb) { if (typeof where === 'function') { // Backward compatibility for 1.x style signature: // count(model, cb, where) - var tmp = options; + const tmp = options; cb = where; where = tmp; } - var stmt = new ParameterizedSQL('SELECT count(*) as "cnt" FROM ' + + let stmt = new ParameterizedSQL('SELECT count(*) as "cnt" FROM ' + this.tableEscaped(model)); stmt = stmt.merge(this.buildWhere(model, where)); stmt = this.parameterize(stmt); @@ -1528,7 +1530,7 @@ SQLConnector.prototype.count = function(model, where, options, cb) { if (err) { return cb(err); } - var c = (res && res[0] && res[0].cnt) || 0; + const c = (res && res[0] && res[0].cnt) || 0; // Some drivers return count as a string to contain bigint // See https://github.com/brianc/node-postgres/pull/427 cb(err, Number(c)); @@ -1550,7 +1552,7 @@ SQLConnector.prototype.dropTable = function(model, cb) { * @param {Function} [cb] The callback function */ SQLConnector.prototype.createTable = function(model, cb) { - var sql = 'CREATE TABLE ' + this.tableEscaped(model) + + const sql = 'CREATE TABLE ' + this.tableEscaped(model) + ' (\n ' + this.buildColumnDefinitions(model) + '\n)'; this.execute(sql, cb); }; @@ -1562,7 +1564,7 @@ SQLConnector.prototype.createTable = function(model, cb) { * @param {Function} [cb] The callback function */ SQLConnector.prototype.automigrate = function(models, cb) { - var self = this; + const self = this; if ((!cb) && ('function' === typeof models)) { cb = models; @@ -1578,7 +1580,7 @@ SQLConnector.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); }); if (invalidModels.length) { @@ -1612,7 +1614,7 @@ SQLConnector.prototype.automigrate = function(models, cb) { * @returns {*} */ SQLConnector.prototype.serializeObject = function(obj) { - var val; + let val; if (obj && typeof obj.toJSON === 'function') { obj = obj.toJSON(); } @@ -1628,7 +1630,7 @@ SQLConnector.prototype.serializeObject = function(obj) { * @param obj */ SQLConnector.prototype.escapeObject = function(obj) { - var val = this.serializeObject(obj); + const val = this.serializeObject(obj); return this.escapeValue(val); }; @@ -1753,7 +1755,7 @@ SQLConnector.prototype.executeSQL = function(sql, params, options, callback) { * @param {Object} options Options for discoverDatabaseSchemas */ SQLConnector.prototype.buildQuerySchemas = function(options) { - var sql = 'SELECT catalog_name as "catalog",' + + const sql = 'SELECT catalog_name as "catalog",' + ' schema_name as "schema"' + ' FROM information_schema.schemata'; return this.paginateSQL(sql, 'schema_name', options); @@ -1780,7 +1782,7 @@ SQLConnector.prototype.discoverDatabaseSchemas = function(options, cb) { options = {}; } options = options || {}; - var self = this; + const self = this; this.execute(self.buildQuerySchemas(options), cb); }; @@ -1819,8 +1821,8 @@ SQLConnector.prototype.discoverModelDefinitions = function(options, cb) { } options = options || {}; - var self = this; - var calls = [function(callback) { + const self = this; + const calls = [function(callback) { self.execute(self.buildQueryTables(options), callback); }]; @@ -1833,7 +1835,7 @@ SQLConnector.prototype.discoverModelDefinitions = function(options, cb) { if (err) { cb(err, data); } else { - var merged = []; + let merged = []; merged = merged.concat(data.shift()); if (data.length) { merged = merged.concat(data.shift()); @@ -1880,9 +1882,9 @@ SQLConnector.prototype.getArgs = function(table, options, cb) { * @param {Function} [cb] The callback function */ SQLConnector.prototype.discoverModelProperties = function(table, options, cb) { - var self = this; - var args = self.getArgs(table, options, cb); - var schema = args.schema || args.owner; + const self = this; + const args = self.getArgs(table, options, cb); + let schema = args.schema || args.owner; table = args.table; options = args.options; @@ -1894,8 +1896,8 @@ SQLConnector.prototype.discoverModelProperties = function(table, options, cb) { self.setDefaultOptions(options); cb = args.cb; - var sql = self.buildQueryColumns(schema, table); - var callback = function(err, results) { + const sql = self.buildQueryColumns(schema, table); + const callback = function(err, results) { if (err) { cb(err, results); } else { @@ -1930,9 +1932,9 @@ SQLConnector.prototype.buildQueryPrimaryKeys = function(schema, table) { * @param {Function} [cb] The callback function */ SQLConnector.prototype.discoverPrimaryKeys = function(table, options, cb) { - var self = this; - var args = self.getArgs(table, options, cb); - var schema = args.schema || args.owner; + const self = this; + const args = self.getArgs(table, options, cb); + let schema = args.schema || args.owner; if (typeof(self.getDefaultSchema) === 'function' && !schema) { schema = self.getDefaultSchema(); @@ -1941,7 +1943,7 @@ SQLConnector.prototype.discoverPrimaryKeys = function(table, options, cb) { options = args.options; cb = args.cb; - var sql = self.buildQueryPrimaryKeys(schema, table); + const sql = self.buildQueryPrimaryKeys(schema, table); this.execute(sql, cb); }; @@ -1964,9 +1966,9 @@ SQLConnector.prototype.buildQueryForeignKeys = function(schema, table) { * @param {Function} [cb] The callback function */ SQLConnector.prototype.discoverForeignKeys = function(table, options, cb) { - var self = this; - var args = self.getArgs(table, options, cb); - var schema = args.schema || args.owner; + const self = this; + const args = self.getArgs(table, options, cb); + let schema = args.schema || args.owner; if (typeof(self.getDefaultSchema) === 'function' && !schema) { schema = self.getDefaultSchema(); @@ -1975,7 +1977,7 @@ SQLConnector.prototype.discoverForeignKeys = function(table, options, cb) { options = args.options; cb = args.cb; - var sql = self.buildQueryForeignKeys(schema, table); + const sql = self.buildQueryForeignKeys(schema, table); this.execute(sql, cb); }; @@ -2001,9 +2003,9 @@ SQLConnector.prototype.buildQueryExportedForeignKeys = function(schema, table) { * @param {Function} [cb] The callback function */ SQLConnector.prototype.discoverExportedForeignKeys = function(table, options, cb) { - var self = this; - var args = self.getArgs(table, options, cb); - var schema = args.schema || args.owner; + const self = this; + const args = self.getArgs(table, options, cb); + let schema = args.schema || args.owner; if (typeof(self.getDefaultSchema) === 'function' && !schema) { schema = self.getDefaultSchema(); @@ -2012,7 +2014,7 @@ SQLConnector.prototype.discoverExportedForeignKeys = function(table, options, cb options = args.options; cb = args.cb; - var sql = self.buildQueryExportedForeignKeys(schema, table); + const sql = self.buildQueryExportedForeignKeys(schema, table); this.execute(sql, cb); }; diff --git a/lib/transaction.js b/lib/transaction.js index 93b2c2b..7548a92 100644 --- a/lib/transaction.js +++ b/lib/transaction.js @@ -4,11 +4,11 @@ // 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 debug = require('debug')('loopback:connector:transaction'); -var uuid = require('uuid'); +const assert = require('assert'); +const util = require('util'); +const EventEmitter = require('events').EventEmitter; +const debug = require('debug')('loopback:connector:transaction'); +const uuid = require('uuid'); const {createPromiseCallback} = require('./utils'); module.exports = Transaction; @@ -86,7 +86,7 @@ Transaction.begin = function(connector, options, cb) { if (typeof options === 'string') { options = {isolationLevel: options}; } - var isolationLevel = options.isolationLevel || Transaction.READ_COMMITTED; + const isolationLevel = options.isolationLevel || Transaction.READ_COMMITTED; assert(isolationLevel === Transaction.SERIALIZABLE || isolationLevel === Transaction.REPEATABLE_READ || isolationLevel === Transaction.READ_COMMITTED || @@ -99,7 +99,7 @@ Transaction.begin = function(connector, options, cb) { if (err) { return cb(err); } - var tx = connection; + let tx = connection; // When the connector and juggler node module have different version of this module as a dependency, // the transaction is not an instanceof Transaction. @@ -117,7 +117,7 @@ Transaction.begin = function(connector, options, cb) { // see: https://github.com/strongloop/loopback-datasource-juggler/pull/1484 if (options.timeout) { tx.timeout = setTimeout(function() { - var context = { + const context = { transaction: tx, operation: 'timeout', }; diff --git a/lib/utils.js b/lib/utils.js index 75eb43f..ca63f63 100644 --- a/lib/utils.js +++ b/lib/utils.js @@ -4,13 +4,13 @@ // License text available at https://opensource.org/licenses/MIT 'use strict'; -var Promise = require('bluebird'); +const Promise = require('bluebird'); exports.createPromiseCallback = createPromiseCallback; 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); diff --git a/package.json b/package.json index 800bebc..a452d60 100644 --- a/package.json +++ b/package.json @@ -18,24 +18,25 @@ "main": "index.js", "scripts": { "lint": "eslint .", + "lint:fix": "eslint . --fix", "posttest": "npm run lint", "test": "mocha" }, "license": "MIT", "dependencies": { - "async": "^2.1.5", + "async": "^3.1.0", "bluebird": "^3.4.6", - "debug": "^3.1.0", + "debug": "^4.1.1", "msgpack5": "^4.2.0", - "strong-globalize": "^4.1.1", + "strong-globalize": "^5.0.0", "uuid": "^3.0.1" }, "devDependencies": { "chai": "^4.2.0", "chai-as-promised": "^7.1.1", - "eslint": "^4.19.1", - "eslint-config-loopback": "^10.0.0", + "eslint": "^6.1.0", + "eslint-config-loopback": "^13.1.0", "loopback-datasource-juggler": "^3.12.0", - "mocha": "^5.2.0" + "mocha": "^6.2.0" } } diff --git a/test/automigrate.test.js b/test/automigrate.test.js index 15a25d2..f064ab0 100644 --- a/test/automigrate.test.js +++ b/test/automigrate.test.js @@ -4,11 +4,11 @@ // License text available at https://opensource.org/licenses/MIT 'use strict'; -var expect = require('chai').expect; -var testConnector = require('./connectors/test-sql-connector'); +const expect = require('chai').expect; +const testConnector = require('./connectors/test-sql-connector'); -var juggler = require('loopback-datasource-juggler'); -var ds = new juggler.DataSource({ +const juggler = require('loopback-datasource-juggler'); +const ds = new juggler.DataSource({ connector: testConnector, debug: true, }); diff --git a/test/binary-packer.test.js b/test/binary-packer.test.js index cbd3dfc..d0530fc 100644 --- a/test/binary-packer.test.js +++ b/test/binary-packer.test.js @@ -5,11 +5,11 @@ 'use strict'; -var BinaryPacker = require('../lib/binary-packer'); -var expect = require('chai').expect; +const BinaryPacker = require('../lib/binary-packer'); +const expect = require('chai').expect; describe('BinaryPacker', function() { - var packer; + let packer; beforeEach(function createPacker() { packer = new BinaryPacker(); @@ -35,7 +35,7 @@ describe('BinaryPacker', function() { }); describe('roundtrip', function() { - var TEST_CASES = { + const TEST_CASES = { String: 'a-value', Object: {a: 1, b: 2}, Buffer: new Buffer([1, 2, 3]), @@ -47,7 +47,7 @@ describe('BinaryPacker', function() { Object.keys(TEST_CASES).forEach(function(tc) { it('works for ' + tc + ' values', function() { - var value = TEST_CASES[tc]; + const value = TEST_CASES[tc]; return encodeAndDecode(value) .then(function(result) { expect(result).to.eql(value); diff --git a/test/connectors/test-sql-connector.js b/test/connectors/test-sql-connector.js index 2244feb..1623a34 100644 --- a/test/connectors/test-sql-connector.js +++ b/test/connectors/test-sql-connector.js @@ -7,11 +7,11 @@ /* * A mockup connector that extends SQL connector */ -var util = require('util'); -var SQLConnector = require('../../lib/sql'); -var debug = require('debug')('loopback:connector:test-sql'); +const util = require('util'); +const SQLConnector = require('../../lib/sql'); +const debug = require('debug')('loopback:connector:test-sql'); -var transactionId = 0; +let transactionId = 0; function MockTransaction(connector, name) { this.connector = connector; @@ -20,11 +20,11 @@ function MockTransaction(connector, name) { } MockTransaction.prototype.commit = function(cb) { - var self = this; + const self = this; // Merge data from this TX to the global data var - for (var m in this.data) { + for (const m in this.data) { self.connector.data[m] = self.connector.data[m] || []; - for (var i = 0, n = this.data[m].length; i < n; i++) { + for (let i = 0, n = this.data[m].length; i < n; i++) { self.connector.data[m].push(this.data[m]); } } @@ -40,7 +40,7 @@ MockTransaction.prototype.rollback = function(cb) { exports.initialize = function initializeDataSource(dataSource, callback) { process.nextTick(function() { if (callback) { - var connector = new TestConnector(dataSource.settings); + const connector = new TestConnector(dataSource.settings); connector.dataSource = dataSource; dataSource.connector = connector; callback(null, connector); @@ -104,7 +104,7 @@ TestConnector.prototype._buildLimit = function(model, limit, offset) { TestConnector.prototype.applyPagination = function(model, stmt, filter) { /* jshint unused:false */ - var limitClause = this._buildLimit(model, filter.limit, + const limitClause = this._buildLimit(model, filter.limit, filter.offset || filter.skip); return stmt.merge(limitClause); }; @@ -157,14 +157,14 @@ TestConnector.prototype._buildLimit = function(model, limit, offset) { TestConnector.prototype.applyPagination = function(model, stmt, filter) { /* jshint unused:false */ - var limitClause = this._buildLimit(model, filter.limit, + const limitClause = this._buildLimit(model, filter.limit, filter.offset || filter.skip); return stmt.merge(limitClause); }; TestConnector.prototype.dropTable = function(model, cb) { - var err; - var exists = model in this._tables; + let err; + const exists = model in this._tables; if (!exists) { err = new Error('Model doesn\'t exist: ' + model); } else { @@ -176,8 +176,8 @@ TestConnector.prototype.dropTable = function(model, cb) { }; TestConnector.prototype.createTable = function(model, cb) { - var err; - var exists = model in this._tables; + let err; + const exists = model in this._tables; if (exists) { err = new Error('Model already exists: ' + model); } else { @@ -197,7 +197,7 @@ TestConnector.prototype.fromColumnValue = function(propertyDef, value) { }; TestConnector.prototype.beginTransaction = function(isolationLevel, cb) { - var name = 'tx_' + transactionId++; + const name = 'tx_' + transactionId++; cb(null, new MockTransaction(this, name)); }; @@ -210,12 +210,12 @@ TestConnector.prototype.rollback = function(tx, cb) { }; TestConnector.prototype.executeSQL = function(sql, params, options, callback) { - var transaction = options.transaction; - var model = options.model; - var useTransaction = transaction && transaction.connector === this && + const transaction = options.transaction; + const model = options.model; + const useTransaction = transaction && transaction.connector === this && transaction.connection; - var data = useTransaction ? transaction.connection.data : this.data; - var name = useTransaction ? transaction.connection.name : undefined; + const data = useTransaction ? transaction.connection.data : this.data; + const name = useTransaction ? transaction.connection.name : undefined; if (sql.indexOf('INSERT') === 0) { data[model] = data[model] || []; data[model].push({sql: sql, params: params}); @@ -223,8 +223,8 @@ TestConnector.prototype.executeSQL = function(sql, params, options, callback) { callback(null, 1); } else { debug('SELECT', data, sql, name); - var instances = data[model] || []; - var result = sql.indexOf('count(*) as "cnt"') !== -1 ? + const instances = data[model] || []; + const result = sql.indexOf('count(*) as "cnt"') !== -1 ? [{cnt: instances.length}] : instances; callback(null, result); } diff --git a/test/json-string-packer.test.js b/test/json-string-packer.test.js index 3162900..170dd5d 100644 --- a/test/json-string-packer.test.js +++ b/test/json-string-packer.test.js @@ -5,11 +5,11 @@ 'use strict'; -var JSONStringPacker = require('../lib/json-string-packer'); -var expect = require('chai').expect; +const JSONStringPacker = require('../lib/json-string-packer'); +const expect = require('chai').expect; describe('JSONStringPacker', function() { - var packer; + let packer; beforeEach(function createPacker() { packer = new JSONStringPacker(); @@ -35,7 +35,7 @@ describe('JSONStringPacker', function() { }); describe('roundtrip', function() { - var TEST_CASES = { + const TEST_CASES = { String: 'a-value', Object: {a: 1, b: 2}, Buffer: new Buffer([1, 2, 3]), @@ -47,7 +47,7 @@ describe('JSONStringPacker', function() { Object.keys(TEST_CASES).forEach(function(tc) { it('works for ' + tc + ' values', function() { - var value = TEST_CASES[tc]; + const value = TEST_CASES[tc]; return encodeAndDecode(value) .then(function(result) { expect(result).to.eql(value); diff --git a/test/model-key-composer.test.js b/test/model-key-composer.test.js index 5ef9195..6f43a62 100644 --- a/test/model-key-composer.test.js +++ b/test/model-key-composer.test.js @@ -5,9 +5,9 @@ 'use strict'; -var composer = require('../lib/model-key-composer'); -var expect = require('chai').expect; -var Promise = require('bluebird'); +const composer = require('../lib/model-key-composer'); +const expect = require('chai').expect; +const Promise = require('bluebird'); describe('ModelKeyComposer', function() { describe('compose()', function() { @@ -66,7 +66,8 @@ describe('ModelKeyComposer', function() { }, function onError(err) { expect(err).to.have.property('code', 'NO_MODEL_PREFIX'); - }); + } + ); }); it('supports invocation with a callback', function(done) { diff --git a/test/smoke.test.js b/test/smoke.test.js index ace4abb..424a709 100644 --- a/test/smoke.test.js +++ b/test/smoke.test.js @@ -4,8 +4,8 @@ // License text available at https://opensource.org/licenses/MIT 'use strict'; -var assert = require('assert'); -var connector = require('../'); +const assert = require('assert'); +const connector = require('../'); describe('loopback-connector', function() { it('exports Connector', function() { diff --git a/test/sql.test.js b/test/sql.test.js index dcb8aed..a3119a3 100644 --- a/test/sql.test.js +++ b/test/sql.test.js @@ -4,19 +4,19 @@ // License text available at https://opensource.org/licenses/MIT 'use strict'; -var expect = require('chai').expect; -var SQLConnector = require('../lib/sql'); -var ParameterizedSQL = SQLConnector.ParameterizedSQL; -var testConnector = require('./connectors/test-sql-connector'); +const expect = require('chai').expect; +const SQLConnector = require('../lib/sql'); +const ParameterizedSQL = SQLConnector.ParameterizedSQL; +const testConnector = require('./connectors/test-sql-connector'); -var juggler = require('loopback-datasource-juggler'); -var ds = new juggler.DataSource({ +const juggler = require('loopback-datasource-juggler'); +const ds = new juggler.DataSource({ connector: testConnector, debug: true, }); /* eslint-disable one-var */ -var connector; -var Customer; +let connector; +let Customer; /* eslint-enable one-var */ describe('sql connector', function() { @@ -61,32 +61,32 @@ describe('sql connector', function() { }); it('should map table name', function() { - var table = connector.table('customer'); + const table = connector.table('customer'); expect(table).to.eql('CUSTOMER'); }); it('should map column name', function() { - var column = connector.column('customer', 'name'); + const column = connector.column('customer', 'name'); expect(column).to.eql('NAME'); }); it('should map column name from name attribute', function() { - var column = connector.column('customer', 'primaryAddress'); + const column = connector.column('customer', 'primaryAddress'); expect(column).to.eql('primary_address'); }); it('prefers database-specific column name over property name', function() { - var column = connector.column('customer', 'lastName'); + const column = connector.column('customer', 'lastName'); expect(column).to.eql('LASTNAME'); }); it('prefers property name when database is different', function() { - var column = connector.column('customer', 'middleName'); + const column = connector.column('customer', 'middleName'); expect(column).to.eql('middle_name'); }); it('should find column metadata', function() { - var column = connector.columnMetadata('customer', 'name'); + const column = connector.columnMetadata('customer', 'name'); expect(column).to.eql({ column: 'NAME', dataType: 'VARCHAR', @@ -95,37 +95,37 @@ describe('sql connector', function() { }); it('should map property name', function() { - var prop = connector.propertyName('customer', 'NAME'); + const prop = connector.propertyName('customer', 'NAME'); expect(prop).to.eql('name'); }); it('should map id column name', function() { - var idCol = connector.idColumn('customer'); + const idCol = connector.idColumn('customer'); expect(idCol).to.eql('NAME'); }); it('should find escaped id column name', function() { - var idCol = connector.idColumnEscaped('customer'); + const idCol = connector.idColumnEscaped('customer'); expect(idCol).to.eql('`NAME`'); }); it('should find escaped table name', function() { - var table = connector.tableEscaped('customer'); + const table = connector.tableEscaped('customer'); expect(table).to.eql('`CUSTOMER`'); }); it('should find escaped column name', function() { - var column = connector.columnEscaped('customer', 'vip'); + const column = connector.columnEscaped('customer', 'vip'); expect(column).to.eql('`VIP`'); }); it('should convert to escaped id column value', function() { - var column = connector.idColumnValue('customer', 'John'); + const column = connector.idColumnValue('customer', 'John'); expect(column).to.eql('John'); }); it('builds where', function() { - var where = connector.buildWhere('customer', {name: 'John'}); + const where = connector.buildWhere('customer', {name: 'John'}); expect(where.toJSON()).to.eql({ sql: 'WHERE `NAME`=?', params: ['John'], @@ -133,7 +133,7 @@ describe('sql connector', function() { }); it('builds where with null', function() { - var where = connector.buildWhere('customer', {name: null}); + const where = connector.buildWhere('customer', {name: null}); expect(where.toJSON()).to.eql({ sql: 'WHERE `NAME` IS NULL', params: [], @@ -141,7 +141,7 @@ describe('sql connector', function() { }); it('builds where with inq', function() { - var where = connector.buildWhere('customer', {name: {inq: ['John', 'Mary']}}); + const where = connector.buildWhere('customer', {name: {inq: ['John', 'Mary']}}); expect(where.toJSON()).to.eql({ sql: 'WHERE `NAME` IN (?,?)', params: ['John', 'Mary'], @@ -149,7 +149,7 @@ describe('sql connector', function() { }); it('builds where with or', function() { - var where = connector.buildWhere('customer', + const where = connector.buildWhere('customer', {or: [{name: 'John'}, {name: 'Mary'}]}); expect(where.toJSON()).to.eql({ sql: 'WHERE (`NAME`=?) OR (`NAME`=?)', @@ -158,7 +158,7 @@ describe('sql connector', function() { }); it('builds where with and', function() { - var where = connector.buildWhere('customer', + const where = connector.buildWhere('customer', {and: [{name: 'John'}, {vip: true}]}); expect(where.toJSON()).to.eql({ sql: 'WHERE (`NAME`=?) AND (`VIP`=?)', @@ -167,7 +167,7 @@ describe('sql connector', function() { }); it('builds where with a regexp string that does not have flags', function() { - var where = connector.buildWhere('customer', { + const where = connector.buildWhere('customer', { name: { regexp: '^J', }, @@ -179,7 +179,7 @@ describe('sql connector', function() { }); it('builds where with a regexp string that has flags', function() { - var where = connector.buildWhere('customer', { + const where = connector.buildWhere('customer', { name: { regexp: '^J/i', }, @@ -191,7 +191,7 @@ describe('sql connector', function() { }); it('builds where with a regexp literal that does not have flags', function() { - var where = connector.buildWhere('customer', { + const where = connector.buildWhere('customer', { name: { regexp: /^J/, }, @@ -203,7 +203,7 @@ describe('sql connector', function() { }); it('builds where with a regexp literal that has flags', function() { - var where = connector.buildWhere('customer', { + const where = connector.buildWhere('customer', { name: { regexp: /^J/i, }, @@ -215,7 +215,7 @@ describe('sql connector', function() { }); it('builds where with a regexp object that does not have flags', function() { - var where = connector.buildWhere('customer', { + const where = connector.buildWhere('customer', { name: { regexp: new RegExp(/^J/), }, @@ -227,7 +227,7 @@ describe('sql connector', function() { }); it('builds where with a regexp object that has flags', function() { - var where = connector.buildWhere('customer', { + const where = connector.buildWhere('customer', { name: { regexp: new RegExp(/^J/i), }, @@ -239,7 +239,7 @@ describe('sql connector', function() { }); it('builds where with nesting and/or', function() { - var where = connector.buildWhere('customer', + const where = connector.buildWhere('customer', {and: [{name: 'John'}, {or: [{vip: true}, {address: null}]}]}); expect(where.toJSON()).to.eql({ sql: 'WHERE (`NAME`=?) AND ((`VIP`=?) OR (`ADDRESS` IS NULL))', @@ -248,32 +248,34 @@ describe('sql connector', function() { }); it('builds order by with one field', function() { - var orderBy = connector.buildOrderBy('customer', 'name'); + const orderBy = connector.buildOrderBy('customer', 'name'); expect(orderBy).to.eql('ORDER BY `NAME`'); }); it('builds order by with two fields', function() { - var orderBy = connector.buildOrderBy('customer', ['name', 'vip']); + const orderBy = connector.buildOrderBy('customer', ['name', 'vip']); expect(orderBy).to.eql('ORDER BY `NAME`,`VIP`'); }); it('builds order by with two fields and dirs', function() { - var orderBy = connector.buildOrderBy('customer', ['name ASC', 'vip DESC']); + const orderBy = connector.buildOrderBy('customer', ['name ASC', 'vip DESC']); expect(orderBy).to.eql('ORDER BY `NAME` ASC,`VIP` DESC'); }); it('builds fields for columns', function() { - var fields = connector.buildFields('customer', + const fields = connector.buildFields('customer', {name: 'John', vip: true, unknown: 'Random'}); expect(fields.names).to.eql(['`NAME`', '`VIP`']); expect(fields.columnValues[0].toJSON()).to.eql( - {sql: '?', params: ['John']}); + {sql: '?', params: ['John']} + ); expect(fields.columnValues[1].toJSON()).to.eql( - {sql: '?', params: [true]}); + {sql: '?', params: [true]} + ); }); it('builds fields for UPDATE without ids', function() { - var fields = connector.buildFieldsForUpdate('customer', + const fields = connector.buildFieldsForUpdate('customer', {name: 'John', vip: true}); expect(fields.toJSON()).to.eql({ sql: 'SET `VIP`=?', @@ -282,7 +284,7 @@ describe('sql connector', function() { }); it('builds fields for UPDATE with ids', function() { - var fields = connector.buildFieldsForUpdate('customer', + const fields = connector.buildFieldsForUpdate('customer', {name: 'John', vip: true}, false); expect(fields.toJSON()).to.eql({ sql: 'SET `NAME`=?,`VIP`=?', @@ -291,18 +293,18 @@ describe('sql connector', function() { }); it('builds column names for SELECT', function() { - var cols = connector.buildColumnNames('customer'); + const cols = connector.buildColumnNames('customer'); expect(cols).to.eql('`NAME`,`middle_name`,`LASTNAME`,`VIP`,' + '`primary_address`,`ADDRESS`'); }); it('builds column names with true fields filter for SELECT', function() { - var cols = connector.buildColumnNames('customer', {fields: {name: true}}); + const cols = connector.buildColumnNames('customer', {fields: {name: true}}); expect(cols).to.eql('`NAME`'); }); it('builds column names with false fields filter for SELECT', function() { - var cols = connector.buildColumnNames('customer', { + const cols = connector.buildColumnNames('customer', { fields: { name: false, primaryAddress: false, @@ -314,12 +316,12 @@ describe('sql connector', function() { }); it('builds column names with array fields filter for SELECT', function() { - var cols = connector.buildColumnNames('customer', {fields: ['name']}); + const cols = connector.buildColumnNames('customer', {fields: ['name']}); expect(cols).to.eql('`NAME`'); }); it('builds DELETE', function() { - var sql = connector.buildDelete('customer', {name: 'John'}); + const sql = connector.buildDelete('customer', {name: 'John'}); expect(sql.toJSON()).to.eql({ sql: 'DELETE FROM `CUSTOMER` WHERE `NAME`=$1', params: ['John'], @@ -327,7 +329,7 @@ describe('sql connector', function() { }); it('builds UPDATE', function() { - var sql = connector.buildUpdate('customer', {name: 'John'}, {vip: false}); + const sql = connector.buildUpdate('customer', {name: 'John'}, {vip: false}); expect(sql.toJSON()).to.eql({ sql: 'UPDATE `CUSTOMER` SET `VIP`=$1 WHERE `NAME`=$2', params: [false, 'John'], @@ -335,7 +337,7 @@ describe('sql connector', function() { }); it('builds SELECT', function() { - var sql = connector.buildSelect('customer', + const sql = connector.buildSelect('customer', {order: 'name', limit: 5, where: {name: 'John'}}); expect(sql.toJSON()).to.eql({ sql: 'SELECT `NAME`,`middle_name`,`LASTNAME`,`VIP`,`primary_address`,`ADDRESS`' + @@ -346,7 +348,7 @@ describe('sql connector', function() { }); it('builds INSERT', function() { - var sql = connector.buildInsert('customer', {name: 'John', vip: true}); + const sql = connector.buildInsert('customer', {name: 'John', vip: true}); expect(sql.toJSON()).to.eql({ sql: 'INSERT INTO `CUSTOMER`(`NAME`,`VIP`) VALUES($1,$2)', params: ['John', true], @@ -354,51 +356,53 @@ describe('sql connector', function() { }); it('normalizes a SQL statement from string', function() { - var sql = 'SELECT * FROM `CUSTOMER`'; - var stmt = new ParameterizedSQL(sql); + const sql = 'SELECT * FROM `CUSTOMER`'; + const stmt = new ParameterizedSQL(sql); expect(stmt.toJSON()).to.eql({sql: sql, params: []}); }); it('normalizes a SQL statement from object without params', function() { - var sql = {sql: 'SELECT * FROM `CUSTOMER`'}; - var stmt = new ParameterizedSQL(sql); + const sql = {sql: 'SELECT * FROM `CUSTOMER`'}; + const stmt = new ParameterizedSQL(sql); expect(stmt.toJSON()).to.eql({sql: sql.sql, params: []}); }); it('normalizes a SQL statement from object with params', function() { - var sql = + const sql = {sql: 'SELECT * FROM `CUSTOMER` WHERE `NAME`=?', params: ['John']}; - var stmt = new ParameterizedSQL(sql); + const stmt = new ParameterizedSQL(sql); expect(stmt.toJSON()).to.eql({sql: sql.sql, params: ['John']}); }); it('should throw if the statement is not a string or object', function() { expect(function() { /* jshint unused:false */ - var stmt = new ParameterizedSQL(true); + const stmt = new ParameterizedSQL(true); }).to.throw('sql must be a string'); }); it('concats SQL statements', function() { - var stmt1 = {sql: 'SELECT * from `CUSTOMER`'}; - var where = {sql: 'WHERE `NAME`=?', params: ['John']}; + let stmt1 = {sql: 'SELECT * from `CUSTOMER`'}; + const where = {sql: 'WHERE `NAME`=?', params: ['John']}; stmt1 = ParameterizedSQL.append(stmt1, where); expect(stmt1.toJSON()).to.eql( - {sql: 'SELECT * from `CUSTOMER` WHERE `NAME`=?', params: ['John']}); + {sql: 'SELECT * from `CUSTOMER` WHERE `NAME`=?', params: ['John']} + ); }); it('concats string SQL statements', function() { - var stmt1 = 'SELECT * from `CUSTOMER`'; - var where = {sql: 'WHERE `NAME`=?', params: ['John']}; + let stmt1 = 'SELECT * from `CUSTOMER`'; + const where = {sql: 'WHERE `NAME`=?', params: ['John']}; stmt1 = ParameterizedSQL.append(stmt1, where); expect(stmt1.toJSON()).to.eql( - {sql: 'SELECT * from `CUSTOMER` WHERE `NAME`=?', params: ['John']}); + {sql: 'SELECT * from `CUSTOMER` WHERE `NAME`=?', params: ['John']} + ); }); it('should throw if params does not match placeholders', function() { expect(function() { - var stmt1 = 'SELECT * from `CUSTOMER`'; - var where = {sql: 'WHERE `NAME`=?', params: ['John', 'Mary']}; + let stmt1 = 'SELECT * from `CUSTOMER`'; + const where = {sql: 'WHERE `NAME`=?', params: ['John', 'Mary']}; stmt1 = ParameterizedSQL.append(stmt1, where); }).to.throw('must match the number of params'); }); @@ -438,7 +442,7 @@ describe('sql connector', function() { }); it('should invoke hooks', function(done) { - var events = []; + const events = []; connector.observe('before execute', function(ctx, next) { expect(ctx.req.sql).be.a('string'); expect(ctx.req.params).be.a('array'); diff --git a/test/transaction.test.js b/test/transaction.test.js index 66d3009..458b968 100644 --- a/test/transaction.test.js +++ b/test/transaction.test.js @@ -4,16 +4,16 @@ // License text available at https://opensource.org/licenses/MIT 'use strict'; -var Transaction = require('../index').Transaction; +const Transaction = require('../index').Transaction; const chai = require('chai'); chai.use(require('chai-as-promised')); const {expect} = chai; const chaiAsPromised = require('chai-as-promised'); -var testConnector = require('./connectors/test-sql-connector'); +const testConnector = require('./connectors/test-sql-connector'); -var juggler = require('loopback-datasource-juggler'); -var db, Post, Review; +const juggler = require('loopback-datasource-juggler'); +let db, Post, Review; describe('transactions', function() { before(function(done) { db = new juggler.DataSource({ @@ -34,8 +34,8 @@ describe('transactions', function() { }); }); - var currentTx; - var hooks = []; + let currentTx; + let hooks = []; // Return an async function to start a transaction and create a post function createPostInTx(post, timeout) { return function(done) { @@ -87,7 +87,7 @@ describe('transactions', function() { // records to equal to the count function expectToFindPosts(where, count, inTx) { return function(done) { - var options = {model: 'Post'}; + const options = {model: 'Post'}; if (inTx) { options.transaction = currentTx; } @@ -119,7 +119,7 @@ describe('transactions', function() { } describe('commit', function() { - var post = {title: 't1', content: 'c1'}; + const post = {title: 't1', content: 'c1'}; before(createPostInTx(post)); it('should not see the uncommitted insert', expectToFindPosts(post, 0)); @@ -150,7 +150,7 @@ describe('transactions', function() { db.connector.data = {}; }); - var post = {title: 't2', content: 'c2'}; + const post = {title: 't2', content: 'c2'}; before(createPostInTx(post)); it('should not see the uncommitted insert', expectToFindPosts(post, 0)); @@ -182,7 +182,7 @@ describe('transactions', function() { db.connector.data = {}; }); - var post = {title: 't3', content: 'c3'}; + const post = {title: 't3', content: 'c3'}; beforeEach(createPostInTx(post, TIMEOUT)); it('should report timeout', function(done) { @@ -219,7 +219,7 @@ describe('transactions', function() { TestTransaction.prototype.foo = true; function beginTransaction(isolationLevel, cb) { return cb(null, new TestTransaction(testConnector, {})); - }; + } it('should do nothing when transaction is like a Transaction', function(done) { testConnector.initialize(db, function(err, resultConnector) { @@ -275,7 +275,8 @@ describe('transactions', function() { return cb(null, 'begun'); }; - return expect(Transaction.begin(connectorObject, '') + return expect( + Transaction.begin(connectorObject, ''), ).to.eventually.be.instanceOf(Transaction); }); });