eslint: autofix linting errors

This commit is contained in:
Miroslav Bajtoš 2018-12-07 17:13:48 +01:00
parent 7eafe12042
commit 481ad566d2
No known key found for this signature in database
GPG Key ID: 6F2304BA9361C7E3
105 changed files with 3535 additions and 3535 deletions

View File

@ -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());

View File

@ -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);

View File

@ -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,

View File

@ -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) {

View File

@ -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];

View File

@ -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'},

View File

@ -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?

View File

@ -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); },
});

View File

@ -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;

View File

@ -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);
};
@ -25,7 +25,7 @@ function KeyValueMemoryConnector(settings, dataSource) {
this._store = Object.create(null);
this._setupRegularCleanup();
};
}
util.inherits(KeyValueMemoryConnector, Connector);
KeyValueMemoryConnector.prototype._setupRegularCleanup = function() {
@ -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();
};

View File

@ -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,19 +266,19 @@ 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() {
callback(err);
});
};
}
self.saveToFile(id, 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
}

View File

@ -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 {

File diff suppressed because it is too large Load Diff

View File

@ -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<Object>} 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);
});
}

View File

@ -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 {
@ -71,7 +71,7 @@ function DateString(value) {
});
this.when = value;
};
}
/**
* Returns the value of DateString in its original form.

View File

@ -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,
@ -38,7 +38,7 @@ exports.nearFilter = function nearFilter(where) {
key: clauseKey,
});
}
};
}
});
}
var nearResults = [];
@ -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];
}

View File

@ -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, ' +

View File

@ -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);
}

View File

@ -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;

View File

@ -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;

View File

@ -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);
}

View File

@ -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) {

View File

@ -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);
});

View File

@ -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

View File

@ -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.

View File

@ -1,7 +1,7 @@
'use strict';
function KeyValueAccessObject() {
};
}
module.exports = KeyValueAccessObject;

View File

@ -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) {

View File

@ -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) {

View File

@ -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.

View File

@ -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

View File

@ -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);
});

View File

@ -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);
}

View File

@ -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: <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);

View File

@ -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;

View File

@ -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

View File

@ -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

View File

@ -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);
});
}

File diff suppressed because it is too large Load Diff

View File

@ -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;

View File

@ -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) {
@ -104,7 +104,7 @@ ScopeDefinition.prototype.related = function(receiver, scopeParams, condOrRefres
// The filter applied on relatedModel
var queryRelated = filter.scope;
delete params.include.scope;
};
}
targetModel.find(params, options, function(err, data) {
if (!err && saveOnCache) {
@ -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);
}

View File

@ -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',
};

View File

@ -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;
}
};

View File

@ -27,11 +27,11 @@ exports.collectTargetIds = collectTargetIds;
exports.idName = idName;
exports.rankArrayElements = rankArrayElements;
var g = require('strong-globalize')();
var traverse = require('traverse');
var assert = require('assert');
var Promise = require('bluebird');
var debug = require('debug')('loopback:juggler:utils');
const g = require('strong-globalize')();
const traverse = require('traverse');
const assert = require('assert');
const Promise = require('bluebird');
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;
@ -610,11 +610,11 @@ function sortObjectsByIds(idName, ids, objects, strict) {
});
return heading.concat(tailing);
};
}
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);
@ -630,15 +630,15 @@ function createPromiseCallback() {
* @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 => item.hasOwnProperty('_bsontype') ? 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]);
}
@ -652,8 +652,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 ' +
@ -666,20 +666,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(''));
}
@ -717,9 +717,9 @@ 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; }
};
}
return -1;
}
@ -731,12 +731,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;

View File

@ -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;

View File

@ -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('<tr><th>' + caption + '</th>');
HOOK_NAMES.forEach(function(h) {
var text = row.hooks[h] ? row.hooks[h].join('<br/>') : '';
const text = row.hooks[h] ? row.hooks[h].join('<br/>') : '';
console.log(' <td>' + text + '</td>');
});
console.log('</tr>');

View File

@ -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);

View File

@ -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]);

View File

@ -4,19 +4,19 @@
// License text available at https://opensource.org/licenses/MIT
'use strict';
var ModelBuilder = require('../').ModelBuilder;
var should = require('./init');
var Promise = require('bluebird');
const ModelBuilder = require('../').ModelBuilder;
const should = require('./init');
const Promise = require('bluebird');
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'));
@ -33,7 +33,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'));
@ -45,7 +45,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'));
@ -57,10 +57,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) {
@ -71,11 +71,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'));
@ -87,10 +87,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) {
@ -101,10 +101,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) {
@ -115,12 +115,12 @@ describe('async observer', function() {
});
it('can remove observers', function(done) {
var notifications = [];
const notifications = [];
function call(ctx, next) {
notifications.push('call');
process.nextTick(next);
};
}
TestModel.observe('event', call);
TestModel.removeObserver('event', call);
@ -133,12 +133,12 @@ describe('async observer', function() {
});
it('can clear all observers', function(done) {
var notifications = [];
const notifications = [];
function call(ctx, next) {
notifications.push('call');
process.nextTick(next);
};
}
TestModel.observe('event', call);
TestModel.observe('event', call);
@ -160,7 +160,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();
@ -168,7 +168,7 @@ describe('async observer', function() {
});
describe('notifyObserversAround', function() {
var notifications;
let notifications;
beforeEach(function() {
notifications = [];
TestModel.observe('before execute',
@ -178,7 +178,7 @@ describe('async observer', function() {
});
it('should notify before/after observers', function(done) {
var context = {};
const context = {};
function work(done) {
process.nextTick(function() {
@ -195,7 +195,7 @@ describe('async observer', function() {
});
it('should allow work with context', function(done) {
var context = {};
const context = {};
function work(context, done) {
process.nextTick(function() {
@ -213,7 +213,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() {
@ -240,7 +240,7 @@ describe('async observer', function() {
TestModel.observe('after invoke',
pushAndNext(notifications, 'after invoke'));
var context = {};
const context = {};
function work(done) {
process.nextTick(function() {
@ -265,7 +265,7 @@ describe('async observer', function() {
next();
});
var context = {};
const context = {};
function work(done) {
process.nextTick(function() {
@ -293,7 +293,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);
});
@ -304,8 +304,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);
@ -313,9 +313,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.');

View File

@ -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,10 +518,10 @@ 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();
};
}
done();
});
});
@ -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);
}

View File

@ -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) {
@ -577,20 +577,20 @@ function testOrm(dataSource) {
function done() {
if (--wait === 0) test.done();
};
}
});
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);

View File

@ -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,

View File

@ -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();

View File

@ -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;

View File

@ -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);
});

View File

@ -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) {
@ -426,7 +426,7 @@ describe('default scope', function() {
exists.should.be.false;
done();
});
};
}
before(function(done) {
db.automigrate(setupProducts.bind(null, ids, done));
@ -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);

View File

@ -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);
});

View File

@ -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'});

View File

@ -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;

View File

@ -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);
});
});

View File

@ -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)

View File

@ -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;
@ -15,10 +15,10 @@ function ContextRecorder(initialValue) {
return new ContextRecorder(initialValue);
}
this.records = initialValue;
};
}
ContextRecorder.prototype.recordAndNext = function(transformFm) {
var self = this;
const self = this;
return function(context, next) {
if (typeof transformFm === 'function') {
transformFm(context);

View File

@ -13,15 +13,15 @@ function HookMonitor(opts) {
this.options = opts || {};
this.names = [];
};
}
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);

View File

@ -5,7 +5,7 @@
'use strict';
var lastId = 0;
let lastId = 0;
exports.next = function() {
lastId++;

View File

@ -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;

View File

@ -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();
});

View File

@ -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]);
});
});

View File

@ -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) {

View File

@ -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();

View File

@ -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"}');

View File

@ -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;

View File

@ -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);
}

View File

@ -1,6 +1,6 @@
'use strict';
var Promise = require('bluebird');
const Promise = require('bluebird');
exports.givenCacheItem = givenCacheItem;
exports.givenKeys = givenKeys;
@ -12,7 +12,7 @@ function givenCacheItem(dataSourceFactory) {
value: 'Any',
};
return givenModel(dataSourceFactory, 'CacheItem', modelProperties);
};
}
function givenModel(dataSourceFactory, modelName,
modelProperties, options) {
@ -21,10 +21,10 @@ function givenModel(dataSourceFactory, modelName,
const p = 'deleteAll' in dataSource.connector ?
Model.deleteAll() : Promise.resolve();
return p.then(() => Model);
};
}
function givenKeys(Model, keys, cb) {
var p = Promise.all(
let p = Promise.all(
keys.map(function(k) {
return Model.set(k, 'value-' + k);
})
@ -33,4 +33,4 @@ function givenKeys(Model, keys, cb) {
p = p.then(function(r) { cb(null, r); }, cb);
}
return p;
};
}

View File

@ -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;

View File

@ -1,19 +1,19 @@
'use strict';
var bdd = require('../helpers/bdd-if');
var should = require('should');
var helpers = require('./_helpers');
var Promise = require('bluebird');
const bdd = require('../helpers/bdd-if');
const should = require('should');
const helpers = require('./_helpers');
const Promise = require('bluebird');
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) {
@ -66,6 +66,6 @@ module.exports = function(dataSourceFactory, connectorCapabilities) {
function setupCacheItem() {
return helpers.givenCacheItem(dataSourceFactory)
.then(ModelCtor => CacheItem = ModelCtor);
};
}
});
};

View File

@ -1,14 +1,14 @@
'use strict';
var should = require('should');
var helpers = require('./_helpers');
var Promise = require('bluebird');
const should = require('should');
const helpers = require('./_helpers');
const Promise = require('bluebird');
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) {
@ -103,6 +103,6 @@ module.exports = function(dataSourceFactory, connectorCapabilities) {
function setupCacheItem() {
return helpers.givenCacheItem(dataSourceFactory)
.then(ModelCtor => CacheItem = ModelCtor);
};
}
});
};

View File

@ -1,23 +1,23 @@
'use strict';
var asyncIterators = require('async-iterators');
var bdd = require('../helpers/bdd-if');
var helpers = require('./_helpers');
var Promise = require('bluebird');
var should = require('should');
var toArray = Promise.promisify(asyncIterators.toArray);
const asyncIterators = require('async-iterators');
const bdd = require('../helpers/bdd-if');
const helpers = require('./_helpers');
const Promise = require('bluebird');
const should = require('should');
const toArray = Promise.promisify(asyncIterators.toArray);
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);
})
@ -28,7 +28,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();
@ -49,6 +49,6 @@ module.exports = function(dataSourceFactory, connectorCapabilities) {
function setupCacheItem() {
return helpers.givenCacheItem(dataSourceFactory)
.then(ModelCtor => CacheItem = ModelCtor);
};
}
});
};

View File

@ -1,12 +1,12 @@
'use strict';
var bdd = require('../helpers/bdd-if');
var helpers = require('./_helpers');
var Promise = require('bluebird');
var should = require('should');
const bdd = require('../helpers/bdd-if');
const helpers = require('./_helpers');
const Promise = require('bluebird');
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;
@ -53,10 +53,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();

View File

@ -1,23 +1,23 @@
'use strict';
var bdd = require('../helpers/bdd-if');
var should = require('should');
var helpers = require('./_helpers');
var Promise = require('bluebird');
const bdd = require('../helpers/bdd-if');
const should = require('should');
const helpers = require('./_helpers');
const Promise = require('bluebird');
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;

View File

@ -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);
});

View File

@ -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() {

File diff suppressed because it is too large Load Diff

View File

@ -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'},

View File

@ -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);

View File

@ -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'});
});

View File

@ -8,7 +8,7 @@
const should = require('./init.js');
const juggler = require('../');
var ModelBuilder = juggler.ModelBuilder;
const ModelBuilder = juggler.ModelBuilder;
describe('ModelBuilder', () => {
describe('define()', () => {

View File

@ -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',

View File

@ -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: [

View File

@ -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',

View File

@ -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);
}

View File

@ -5,27 +5,27 @@
'use strict';
var Promise = require('bluebird');
var ValidationError = require('../..').ValidationError;
const Promise = require('bluebird');
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
@ -48,14 +48,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;
});

View File

@ -5,27 +5,27 @@
'use strict';
var Promise = require('bluebird');
var ValidationError = require('../..').ValidationError;
const Promise = require('bluebird');
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
@ -48,14 +48,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;
});

View File

@ -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);
}

View File

@ -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;
});

View File

@ -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;
});

View File

@ -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);
}

View File

@ -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);
});

View File

@ -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',

File diff suppressed because it is too large Load Diff

View File

@ -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;
});

View File

@ -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();
@ -330,7 +330,7 @@ describe('scope - filtered count, updateAll and destroyAll', function() {
});
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();

Some files were not shown because too many files have changed in this diff Show More