Merge pull request #1674 from strongloop/eslint/use-const-not-var

Refactor: migrate from "var" to "const"
This commit is contained in:
Miroslav Bajtoš 2018-12-07 16:56:45 +01:00 committed by GitHub
commit bd5fd07d27
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
105 changed files with 3575 additions and 3563 deletions

View File

@ -4,6 +4,9 @@
"ecmaVersion": 2017 "ecmaVersion": 2017
}, },
"rules": { "rules": {
// TODO(bajtos) move these two rules to eslint-config-loopback
"no-var": "error",
"prefer-const": "error",
"max-len": ["error", 110, 4, { "max-len": ["error", 110, 4, {
"ignoreComments": true, "ignoreComments": true,
"ignoreUrls": true, "ignoreUrls": true,

View File

@ -5,16 +5,16 @@
'use strict'; 'use strict';
var DataSource = require('../../loopback-datasource-juggler').DataSource; const DataSource = require('../../loopback-datasource-juggler').DataSource;
var ModelBuilder = require('../../loopback-datasource-juggler').ModelBuilder; const ModelBuilder = require('../../loopback-datasource-juggler').ModelBuilder;
var introspectType = require('../lib/introspection')(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 // 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', owner: 'rfeng',
name: 'MyApp1', name: 'MyApp1',
description: 'My first app', description: 'My first app',
@ -47,7 +47,7 @@ Application.create(application, function(err, app1) {
}); });
// Instance JSON document // Instance JSON document
var user = { const user = {
name: 'Joe', name: 'Joe',
age: 30, age: 30,
birthday: new Date(), birthday: new Date(),
@ -68,13 +68,13 @@ var user = {
}; };
// Introspect the JSON document to generate a schema // Introspect the JSON document to generate a schema
var schema = introspectType(user); const schema = introspectType(user);
// Create a model for the generated schema // 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 // Use the model for CRUD
var obj = new User(user); const obj = new User(user);
console.log(obj.toObject()); console.log(obj.toObject());

View File

@ -5,10 +5,10 @@
'use strict'; 'use strict';
var ModelBuilder = require('../../loopback-datasource-juggler').ModelBuilder; const ModelBuilder = require('../../loopback-datasource-juggler').ModelBuilder;
var modelBuilder = new ModelBuilder(); const modelBuilder = new ModelBuilder();
// define models // define models
var Post = modelBuilder.define('Post', { const Post = modelBuilder.define('Post', {
title: {type: String, length: 255}, title: {type: String, length: 255},
content: {type: ModelBuilder.Text}, content: {type: ModelBuilder.Text},
date: {type: Date, default: function() { date: {type: Date, default: function() {
@ -19,7 +19,7 @@ var Post = modelBuilder.define('Post', {
}); });
// simpler way to describe model // simpler way to describe model
var User = modelBuilder.define('User', { const User = modelBuilder.define('User', {
name: String, name: String,
bio: ModelBuilder.Text, bio: ModelBuilder.Text,
approved: Boolean, approved: Boolean,
@ -27,14 +27,14 @@ var User = modelBuilder.define('User', {
age: Number, age: Number,
}); });
var Group = modelBuilder.define('Group', {group: String}); const Group = modelBuilder.define('Group', {group: String});
// define any custom method // define any custom method
User.prototype.getNameAndAge = function() { User.prototype.getNameAndAge = function() {
return this.name + ', ' + this.age; return this.name + ', ' + this.age;
}; };
var user = new User({name: 'Joe'}); let user = new User({name: 'Joe'});
console.log(user); console.log(user);
console.log(modelBuilder.models); console.log(modelBuilder.models);

View File

@ -5,12 +5,12 @@
'use strict'; 'use strict';
var DataSource = require('../../loopback-datasource-juggler').DataSource; const DataSource = require('../../loopback-datasource-juggler').DataSource;
var ModelBuilder = require('../../loopback-datasource-juggler').ModelBuilder; const ModelBuilder = require('../../loopback-datasource-juggler').ModelBuilder;
var ds = new DataSource('memory'); const ds = new DataSource('memory');
// define models // define models
var Post = ds.define('Post', { const Post = ds.define('Post', {
title: {type: String, length: 255}, title: {type: String, length: 255},
content: {type: DataSource.Text}, content: {type: DataSource.Text},
date: {type: Date, default: function() { date: {type: Date, default: function() {
@ -21,7 +21,7 @@ var Post = ds.define('Post', {
}); });
// simplier way to describe model // simplier way to describe model
var User = ds.define('User', { const User = ds.define('User', {
name: String, name: String,
bio: DataSource.Text, bio: DataSource.Text,
approved: Boolean, approved: Boolean,
@ -29,14 +29,14 @@ var User = ds.define('User', {
age: Number, age: Number,
}); });
var Group = ds.define('Group', {name: String}); const Group = ds.define('Group', {name: String});
// define any custom method // define any custom method
User.prototype.getNameAndAge = function() { User.prototype.getNameAndAge = function() {
return this.name + ', ' + this.age; return this.name + ', ' + this.age;
}; };
var user = new User({name: 'Joe'}); const user = new User({name: 'Joe'});
console.log(user); console.log(user);
// console.log(ds.models); // console.log(ds.models);
@ -58,10 +58,10 @@ Post.belongsTo(User, {as: 'author', foreignKey: 'userId'});
User.hasAndBelongsToMany('groups'); User.hasAndBelongsToMany('groups');
var user2 = new User({name: 'Smith', age: 14}); const user2 = new User({name: 'Smith', age: 14});
user2.save(function(err) { user2.save(function(err) {
console.log(user2); console.log(user2);
var post = user2.posts.build({title: 'Hello world'}); const post = user2.posts.build({title: 'Hello world'});
post.save(function(err, data) { post.save(function(err, data) {
console.log(err ? err : data); console.log(err ? err : data);
}); });
@ -77,7 +77,7 @@ User.create({name: 'Jeff', age: 12}, function(err, data) {
return; return;
} }
console.log(data); console.log(data);
var post = data.posts.build({title: 'My Post'}); const post = data.posts.build({title: 'My Post'});
console.log(post); console.log(post);
}); });
@ -90,8 +90,8 @@ User.minors(function(err, kids) {
console.log('Kids: ', kids); console.log('Kids: ', kids);
}); });
var Article = ds.define('Article', {title: String}); const Article = ds.define('Article', {title: String});
var Tag = ds.define('Tag', {name: String}); const Tag = ds.define('Tag', {name: String});
Article.hasAndBelongsToMany('tags'); Article.hasAndBelongsToMany('tags');
Article.create(function(e, article) { 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 // 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', { const Color = modelBuilder.define('Color', {
name: String, name: String,

View File

@ -5,10 +5,10 @@
'use strict'; 'use strict';
var jdb = require('../index'); const jdb = require('../index');
var User, Post, Passport, City, Street, Building; let User, Post, Passport, City, Street, Building;
var nbSchemaRequests = 0; const nbSchemaRequests = 0;
setup(function() { setup(function() {
Passport.find({include: 'owner'}, function(err, passports) { Passport.find({include: 'owner'}, function(err, passports) {
@ -35,7 +35,7 @@ setup(function() {
}); });
function setup(done) { function setup(done) {
var db = new jdb.DataSource({connector: 'memory'}); const db = new jdb.DataSource({connector: 'memory'});
City = db.define('City'); City = db.define('City');
Street = db.define('Street'); Street = db.define('Street');
Building = db.define('Building'); Building = db.define('Building');
@ -56,9 +56,9 @@ function setup(done) {
Post.belongsTo('author', {model: User, foreignKey: 'userId'}); Post.belongsTo('author', {model: User, foreignKey: 'userId'});
db.automigrate(function() { db.automigrate(function() {
var createdUsers = []; let createdUsers = [];
var createdPassports = []; let createdPassports = [];
var createdPosts = []; let createdPosts = [];
createUsers(); createUsers();
function createUsers() { function createUsers() {
clearAndCreate( clearAndCreate(
@ -112,12 +112,12 @@ function setup(done) {
} }
function clearAndCreate(model, data, callback) { function clearAndCreate(model, data, callback) {
var createdItems = []; const createdItems = [];
model.destroyAll(function() { model.destroyAll(function() {
nextItem(null, null); nextItem(null, null);
}); });
var itemIndex = 0; let itemIndex = 0;
function nextItem(err, lastItem) { function nextItem(err, lastItem) {
if (lastItem !== null) { if (lastItem !== null) {

View File

@ -5,7 +5,7 @@
'use strict'; 'use strict';
var path = require('path'), const path = require('path'),
fs = require('fs'), fs = require('fs'),
DataSource = require('../lib/datasource').DataSource; DataSource = require('../lib/datasource').DataSource;
@ -21,12 +21,12 @@ function loadSchemasSync(schemaFile, dataSource) {
} }
// Read the dataSource JSON file // Read the dataSource JSON file
var schemas = JSON.parse(fs.readFileSync(schemaFile)); const schemas = JSON.parse(fs.readFileSync(schemaFile));
return dataSource.buildModels(schemas); 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) { for (const s in models) {
const m = models[s]; const m = models[s];

View File

@ -5,11 +5,11 @@
'use strict'; 'use strict';
var ModelBuilder = require('../../loopback-datasource-juggler').ModelBuilder; const ModelBuilder = require('../../loopback-datasource-juggler').ModelBuilder;
var modelBuilder = new ModelBuilder(); const modelBuilder = new ModelBuilder();
// simplier way to describe model // simplier way to describe model
var User = modelBuilder.define('User', { const User = modelBuilder.define('User', {
name: String, name: String,
bio: ModelBuilder.Text, bio: ModelBuilder.Text,
approved: Boolean, approved: Boolean,
@ -31,7 +31,7 @@ var User = modelBuilder.define('User', {
friends: [String], friends: [String],
}); });
var user = new User({ const user = new User({
name: 'Joe', name: 'Joe',
age: 20, age: 20,
address: {street: '123 Main St', 'city': 'San Jose', state: 'CA'}, address: {street: '123 Main St', 'city': 'San Jose', state: 'CA'},

View File

@ -5,22 +5,22 @@
'use strict'; 'use strict';
var DataSource = require('../index').DataSource; const DataSource = require('../index').DataSource;
var ds = new DataSource('memory'); const ds = new DataSource('memory');
var Order = ds.createModel('Order', { const Order = ds.createModel('Order', {
items: [String], items: [String],
orderDate: Date, orderDate: Date,
qty: Number, qty: Number,
}); });
var Customer = ds.createModel('Customer', { const Customer = ds.createModel('Customer', {
name: String, name: String,
}); });
Order.belongsTo(Customer); Order.belongsTo(Customer);
var order1, order2, order3; let order1, order2, order3;
Customer.create({name: 'John'}, function(err, customer) { Customer.create({name: 'John'}, function(err, customer) {
Order.create({customerId: customer.id, orderDate: new Date(), items: ['Book']}, function(err, order) { 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); 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, name: String,
}); });
var Patient = ds.createModel('Patient', { const Patient = ds.createModel('Patient', {
name: String, name: String,
}); });
var Appointment = ds.createModel('Appointment', { const Appointment = ds.createModel('Appointment', {
physicianId: Number, physicianId: Number,
patientId: Number, patientId: Number,
appointmentDate: Date, appointmentDate: Date,
@ -102,7 +102,7 @@ Physician.create({name: 'Dr John'}, function(err, physician1) {
patient1.physicians(console.log); patient1.physicians(console.log);
// Build an appointment? // 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); console.log('Physician 3: ', patient3, patient3.constructor.modelName);
// Create a physician? // 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, name: String,
}); });
var Part = ds.createModel('Part', { const Part = ds.createModel('Part', {
partNumber: String, partNumber: String,
}); });
@ -137,7 +137,7 @@ Assembly.create({name: 'car'}, function(err, assembly) {
}); });
// Build an part? // Build an part?
var part3 = assembly.parts.build({partNumber: 'door'}); const part3 = assembly.parts.build({partNumber: 'door'});
console.log('Part3: ', part3, part3.constructor.modelName); console.log('Part3: ', part3, part3.constructor.modelName);
// Create a part? // Create a part?

View File

@ -4,7 +4,7 @@
// License text available at https://opensource.org/licenses/MIT // License text available at https://opensource.org/licenses/MIT
'use strict'; 'use strict';
var SG = require('strong-globalize'); const SG = require('strong-globalize');
SG.SetRootDir(__dirname); SG.SetRootDir(__dirname);
exports.ModelBuilder = exports.LDL = require('./lib/model-builder.js').ModelBuilder; 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; }, get: function() { return require('./package.json').version; },
}); });
var commonTest = './test/common_test'; const commonTest = './test/common_test';
Object.defineProperty(exports, 'test', { Object.defineProperty(exports, 'test', {
get: function() { return require(commonTest); }, get: function() { return require(commonTest); },
}); });

View File

@ -7,7 +7,7 @@
// A lightweight alternative to "depd" that works in the browser // A lightweight alternative to "depd" that works in the browser
module.exports = function depd(namespace) { module.exports = function depd(namespace) {
var warned = {}; const warned = {};
return function deprecate(message) { return function deprecate(message) {
if (warned[message]) return; if (warned[message]) return;
warned[message] = true; warned[message] = true;

View File

@ -1,15 +1,15 @@
'use strict'; 'use strict';
var g = require('strong-globalize')(); const g = require('strong-globalize')();
var assert = require('assert'); const assert = require('assert');
var Connector = require('loopback-connector').Connector; const Connector = require('loopback-connector').Connector;
var debug = require('debug')('loopback:connector:kv-memory'); const debug = require('debug')('loopback:connector:kv-memory');
var minimatch = require('minimatch'); const minimatch = require('minimatch');
var util = require('util'); const util = require('util');
exports.initialize = function initializeDataSource(dataSource, cb) { exports.initialize = function initializeDataSource(dataSource, cb) {
var settings = dataSource.settings; const settings = dataSource.settings;
dataSource.connector = new KeyValueMemoryConnector(settings, dataSource); dataSource.connector = new KeyValueMemoryConnector(settings, dataSource);
if (cb) process.nextTick(cb); if (cb) process.nextTick(cb);
}; };
@ -33,14 +33,13 @@ KeyValueMemoryConnector.prototype._setupRegularCleanup = function() {
// in order to release memory. Note that GET operation checks // in order to release memory. Note that GET operation checks
// key expiration too, the scheduled cleanup is merely a performance // key expiration too, the scheduled cleanup is merely a performance
// optimization. // optimization.
var self = this; this._cleanupTimer = setInterval(
var timer = this._cleanupTimer = setInterval( () => {
function() { if (this && this._removeExpiredItems) {
if (self && self._removeExpiredItems) { this._removeExpiredItems();
self._removeExpiredItems();
} else { } else {
// The datasource/connector was destroyed - cancel the timer // The datasource/connector was destroyed - cancel the timer
clearInterval(timer); clearInterval(this._cleanupTimer);
} }
}, },
1000 1000
@ -50,9 +49,9 @@ KeyValueMemoryConnector.prototype._setupRegularCleanup = function() {
KeyValueMemoryConnector._removeExpiredItems = function() { KeyValueMemoryConnector._removeExpiredItems = function() {
debug('Running scheduled cleanup of expired items.'); debug('Running scheduled cleanup of expired items.');
for (var modelName in this._store) { for (const modelName in this._store) {
var modelStore = this._store[modelName]; const modelStore = this._store[modelName];
for (var key in modelStore) { for (const key in modelStore) {
if (modelStore[key].isExpired()) { if (modelStore[key].isExpired()) {
debug('Removing expired key', key); debug('Removing expired key', key);
delete modelStore[key]; delete modelStore[key];
@ -69,8 +68,8 @@ KeyValueMemoryConnector.prototype._getStoreForModel = function(modelName) {
}; };
KeyValueMemoryConnector.prototype._removeIfExpired = function(modelName, key) { KeyValueMemoryConnector.prototype._removeIfExpired = function(modelName, key) {
var store = this._getStoreForModel(modelName); const store = this._getStoreForModel(modelName);
var item = store[key]; let item = store[key];
if (item && item.isExpired()) { if (item && item.isExpired()) {
debug('Removing expired key', key); debug('Removing expired key', key);
delete store[key]; delete store[key];
@ -84,9 +83,9 @@ KeyValueMemoryConnector.prototype.get =
function(modelName, key, options, callback) { function(modelName, key, options, callback) {
this._removeIfExpired(modelName, key); this._removeIfExpired(modelName, key);
var store = this._getStoreForModel(modelName); const store = this._getStoreForModel(modelName);
var item = store[key]; const item = store[key];
var value = item ? item.value : null; let value = item ? item.value : null;
debug('GET %j %j -> %s', modelName, key, value); debug('GET %j %j -> %s', modelName, key, value);
if (/^buffer:/.test(value)) { if (/^buffer:/.test(value)) {
@ -104,7 +103,7 @@ function(modelName, key, options, callback) {
KeyValueMemoryConnector.prototype.set = KeyValueMemoryConnector.prototype.set =
function(modelName, key, value, options, callback) { function(modelName, key, value, options, callback) {
var store = this._getStoreForModel(modelName); const store = this._getStoreForModel(modelName);
if (Buffer.isBuffer(value)) { if (Buffer.isBuffer(value)) {
value = 'buffer:' + value.toString('base64'); value = 'buffer:' + value.toString('base64');
} else if (value instanceof Date) { } else if (value instanceof Date) {
@ -123,11 +122,11 @@ KeyValueMemoryConnector.prototype.expire =
function(modelName, key, ttl, options, callback) { function(modelName, key, ttl, options, callback) {
this._removeIfExpired(modelName, key); this._removeIfExpired(modelName, key);
var store = this._getStoreForModel(modelName); const store = this._getStoreForModel(modelName);
if (!(key in store)) { if (!(key in store)) {
return process.nextTick(function() { 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; err.statusCode = 404;
callback(err); callback(err);
}); });
@ -142,18 +141,18 @@ KeyValueMemoryConnector.prototype.ttl =
function(modelName, key, options, callback) { function(modelName, key, options, callback) {
this._removeIfExpired(modelName, key); this._removeIfExpired(modelName, key);
var store = this._getStoreForModel(modelName); const store = this._getStoreForModel(modelName);
// key is unknown // key is unknown
if (!(key in store)) { if (!(key in store)) {
return process.nextTick(function() { 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; err.statusCode = 404;
callback(err); callback(err);
}); });
} }
var ttl = store[key].getTtl(); const ttl = store[key].getTtl();
debug('TTL %j %j -> %s', modelName, key, ttl); debug('TTL %j %j -> %s', modelName, key, ttl);
process.nextTick(function() { process.nextTick(function() {
@ -163,20 +162,20 @@ function(modelName, key, options, callback) {
KeyValueMemoryConnector.prototype.iterateKeys = KeyValueMemoryConnector.prototype.iterateKeys =
function(modelName, filter, options, callback) { function(modelName, filter, options, callback) {
var store = this._getStoreForModel(modelName); const store = this._getStoreForModel(modelName);
var self = this; const self = this;
var checkFilter = createMatcher(filter.match); 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); return !self._removeIfExpired(modelName, key) && checkFilter(key);
}); });
debug('ITERATE KEYS %j -> %s keys', modelName, keys.length); debug('ITERATE KEYS %j -> %s keys', modelName, keys.length);
var ix = 0; let ix = 0;
return { return {
next: function(cb) { next: function(cb) {
var value = ix < keys.length ? keys[ix++] : undefined; const value = ix < keys.length ? keys[ix++] : undefined;
setImmediate(function() { cb(null, value); }); setImmediate(function() { cb(null, value); });
}, },
}; };
@ -203,15 +202,15 @@ KeyValueMemoryConnector.prototype.disconnect = function(callback) {
KeyValueMemoryConnector.prototype.delete = KeyValueMemoryConnector.prototype.delete =
function(modelName, key, options, callback) { function(modelName, key, options, callback) {
var store = this._getStoreForModel(modelName); const store = this._getStoreForModel(modelName);
delete store[key]; delete store[key];
callback(); callback();
}; };
KeyValueMemoryConnector.prototype.deleteAll = KeyValueMemoryConnector.prototype.deleteAll =
function(modelName, options, callback) { function(modelName, options, callback) {
var modelStore = this._getStoreForModel(modelName); const modelStore = this._getStoreForModel(modelName);
for (var key in modelStore) for (const key in modelStore)
delete modelStore[key]; delete modelStore[key];
callback(); callback();
}; };

View File

@ -6,14 +6,14 @@
'use strict'; 'use strict';
/* global window:false */ /* global window:false */
var g = require('strong-globalize')(); const g = require('strong-globalize')();
var util = require('util'); const util = require('util');
var Connector = require('loopback-connector').Connector; const Connector = require('loopback-connector').Connector;
var geo = require('../geo'); const geo = require('../geo');
var utils = require('../utils'); const utils = require('../utils');
var fs = require('fs'); const fs = require('fs');
var async = require('async'); const async = require('async');
var debug = require('debug')('loopback:connector:memory'); const debug = require('debug')('loopback:connector:memory');
/** /**
* Initialize the Memory connector against the given data source * Initialize the Memory connector against the given data source
@ -82,7 +82,7 @@ function deserialize(dbObj) {
} }
Memory.prototype.getCollection = function(model) { Memory.prototype.getCollection = function(model) {
var modelClass = this._models[model]; const modelClass = this._models[model];
if (modelClass && modelClass.settings.memory) { if (modelClass && modelClass.settings.memory) {
model = modelClass.settings.memory.collection || model; model = modelClass.settings.memory.collection || model;
} }
@ -111,15 +111,15 @@ Memory.prototype.collectionSeq = function(model, val) {
* @returns {*} The file operation queue * @returns {*} The file operation queue
*/ */
Memory.prototype.setupFileQueue = function() { Memory.prototype.setupFileQueue = function() {
var self = this; const self = this;
if (!this.fileQueue) { if (!this.fileQueue) {
// Create a queue for writes // Create a queue for writes
this.fileQueue = async.queue(function(task, done) { this.fileQueue = async.queue(function(task, done) {
var callback = task.callback || function() {}; const callback = task.callback || function() {};
var file = self.settings.file; const file = self.settings.file;
if (task.operation === 'write') { if (task.operation === 'write') {
// Flush out the models/ids // Flush out the models/ids
var data = JSON.stringify({ const data = JSON.stringify({
ids: self.ids, ids: self.ids,
models: self.cache, models: self.cache,
}, null, ' '); }, null, ' ');
@ -130,7 +130,7 @@ Memory.prototype.setupFileQueue = function() {
callback(err, task.data); callback(err, task.data);
}); });
} else if (task.operation === 'read') { } else if (task.operation === 'read') {
debug('Reading cache from %s: %s', file, data); debug('Reading cache from %s', file);
fs.readFile(file, { fs.readFile(file, {
encoding: 'utf8', encoding: 'utf8',
flag: 'r', flag: 'r',
@ -147,7 +147,7 @@ Memory.prototype.setupFileQueue = function() {
} }
}); });
} else { } else {
var err = new Error('Unknown type of task'); const err = new Error('Unknown type of task');
done(err); done(err);
callback(err); callback(err);
} }
@ -176,8 +176,8 @@ Memory.prototype.parseAndLoad = function(data, callback) {
}; };
Memory.prototype.loadFromFile = function(callback) { Memory.prototype.loadFromFile = function(callback) {
var hasLocalStorage = typeof window !== 'undefined' && window.localStorage; const hasLocalStorage = typeof window !== 'undefined' && window.localStorage;
var localStorage = hasLocalStorage && this.settings.localStorage; const localStorage = hasLocalStorage && this.settings.localStorage;
if (this.settings.file) { if (this.settings.file) {
debug('Queueing read %s', this.settings.file); debug('Queueing read %s', this.settings.file);
@ -186,7 +186,7 @@ Memory.prototype.loadFromFile = function(callback) {
callback: callback, callback: callback,
}); });
} else if (localStorage) { } else if (localStorage) {
var data = window.localStorage.getItem(localStorage); let data = window.localStorage.getItem(localStorage);
data = data || '{}'; data = data || '{}';
this.parseAndLoad(data, callback); this.parseAndLoad(data, callback);
} else { } else {
@ -199,9 +199,9 @@ Memory.prototype.loadFromFile = function(callback) {
* @param {Function} callback * @param {Function} callback
*/ */
Memory.prototype.saveToFile = function(result, callback) { Memory.prototype.saveToFile = function(result, callback) {
var file = this.settings.file; const file = this.settings.file;
var hasLocalStorage = typeof window !== 'undefined' && window.localStorage; const hasLocalStorage = typeof window !== 'undefined' && window.localStorage;
var localStorage = hasLocalStorage && this.settings.localStorage; const localStorage = hasLocalStorage && this.settings.localStorage;
if (file) { if (file) {
debug('Queueing write %s', this.settings.file); debug('Queueing write %s', this.settings.file);
// Enqueue the write // Enqueue the write
@ -212,7 +212,7 @@ Memory.prototype.saveToFile = function(result, callback) {
}); });
} else if (localStorage) { } else if (localStorage) {
// Flush out the models/ids // Flush out the models/ids
var data = JSON.stringify({ const data = JSON.stringify({
ids: this.ids, ids: this.ids,
models: this.cache, models: this.cache,
}, null, ' '); }, null, ' ');
@ -229,26 +229,26 @@ Memory.prototype.saveToFile = function(result, callback) {
Memory.prototype.define = function defineModel(definition) { Memory.prototype.define = function defineModel(definition) {
this.constructor.super_.prototype.define.apply(this, [].slice.call(arguments)); 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); if (!this.collection(m)) this.initCollection(m);
}; };
Memory.prototype._createSync = function(model, data, fn) { Memory.prototype._createSync = function(model, data, fn) {
// FIXME: [rfeng] We need to generate unique ids based on the id type // FIXME: [rfeng] We need to generate unique ids based on the id type
// FIXME: [rfeng] We don't support composite ids yet // FIXME: [rfeng] We don't support composite ids yet
var currentId = this.collectionSeq(model); let currentId = this.collectionSeq(model);
if (currentId === undefined) { // First time if (currentId === undefined) { // First time
currentId = this.collectionSeq(model, 1); currentId = this.collectionSeq(model, 1);
} }
var id = this.getIdValue(model, data) || currentId; let id = this.getIdValue(model, data) || currentId;
if (id > currentId) { if (id > currentId) {
// If the id is passed in and the value is greater than the current id // If the id is passed in and the value is greater than the current id
currentId = id; currentId = id;
} }
this.collectionSeq(model, Number(currentId) + 1); this.collectionSeq(model, Number(currentId) + 1);
var props = this._models[model].properties; const props = this._models[model].properties;
var idName = this.idName(model); const idName = this.idName(model);
id = (props[idName] && props[idName].type && props[idName].type(id)) || id; id = (props[idName] && props[idName].type && props[idName].type(id)) || id;
this.setIdValue(model, data, id); this.setIdValue(model, data, id);
if (!this.collection(model)) { if (!this.collection(model)) {
@ -256,7 +256,7 @@ Memory.prototype._createSync = function(model, data, fn) {
} }
if (this.collection(model)[id]) { 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; error.statusCode = error.status = 409;
return fn(error); return fn(error);
} }
@ -266,7 +266,7 @@ Memory.prototype._createSync = function(model, data, fn) {
}; };
Memory.prototype.create = function create(model, data, options, callback) { Memory.prototype.create = function create(model, data, options, callback) {
var self = this; const self = this;
this._createSync(model, data, function(err, id) { this._createSync(model, data, function(err, id) {
if (err) { if (err) {
return process.nextTick(function() { return process.nextTick(function() {
@ -278,7 +278,7 @@ Memory.prototype.create = function create(model, data, options, callback) {
}; };
Memory.prototype.updateOrCreate = function(model, data, options, callback) { 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) { this.exists(model, self.getIdValue(model, data), options, function(err, exists) {
if (exists) { if (exists) {
self.save(model, data, options, function(err, data) { 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.patchOrCreateWithWhere =
Memory.prototype.upsertWithWhere = function(model, where, data, options, callback) { Memory.prototype.upsertWithWhere = function(model, where, data, options, callback) {
var self = this; const self = this;
var primaryKey = this.idName(model); const primaryKey = this.idName(model);
var filter = {where: where}; const filter = {where: where};
var nodes = self._findAllSkippingIncludes(model, filter); const nodes = self._findAllSkippingIncludes(model, filter);
if (nodes.length === 0) { if (nodes.length === 0) {
return self._createSync(model, data, function(err, id) { return self._createSync(model, data, function(err, id) {
if (err) return process.nextTick(function() { callback(err); }); 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) { if (nodes.length === 1) {
var primaryKeyValue = nodes[0][primaryKey]; const primaryKeyValue = nodes[0][primaryKey];
self.updateAttributes(model, primaryKeyValue, data, options, function(err, data) { self.updateAttributes(model, primaryKeyValue, data, options, function(err, data) {
callback(err, data, {isNewInstance: false}); callback(err, data, {isNewInstance: false});
}); });
} else { } else {
process.nextTick(function() { 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!'); 'Upsert Operation will not be performed!');
error.statusCode = 400; error.statusCode = 400;
callback(error); callback(error);
@ -324,9 +324,9 @@ Memory.prototype.upsertWithWhere = function(model, where, data, options, callbac
}; };
Memory.prototype.findOrCreate = function(model, filter, data, options, callback) { Memory.prototype.findOrCreate = function(model, filter, data, options, callback) {
var self = this; const self = this;
var nodes = self._findAllSkippingIncludes(model, filter); const nodes = self._findAllSkippingIncludes(model, filter);
var found = nodes[0]; const found = nodes[0];
if (!found) { if (!found) {
// Calling _createSync to update the collection in a sync way and to guarantee to create it in the same turn of even loop // 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) { Memory.prototype.save = function save(model, data, options, callback) {
var self = this; const self = this;
var id = this.getIdValue(model, data); const id = this.getIdValue(model, data);
var cachedModels = this.collection(model); const cachedModels = this.collection(model);
var modelData = cachedModels && this.collection(model)[id]; let modelData = cachedModels && this.collection(model)[id];
modelData = modelData && deserialize(modelData); modelData = modelData && deserialize(modelData);
if (modelData) { if (modelData) {
data = merge(modelData, data); 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) { 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]; delete this.collection(model)[id];
this.saveToFile({count: exists ? 1 : 0}, callback); 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) { Memory.prototype.fromDb = function(model, data) {
if (!data) return null; if (!data) return null;
data = deserialize(data); data = deserialize(data);
var props = this._models[model].properties; const props = this._models[model].properties;
for (var key in data) { for (const key in data) {
var val = data[key]; let val = data[key];
if (val === undefined || val === null) { if (val === undefined || val === null) {
continue; continue;
} }
@ -417,9 +417,9 @@ function getValue(obj, path) {
if (obj == null) { if (obj == null) {
return undefined; return undefined;
} }
var keys = path.split('.'); const keys = path.split('.');
var val = obj; let val = obj;
for (var i = 0, n = keys.length; i < n; i++) { for (let i = 0, n = keys.length; i < n; i++) {
val = val[keys[i]]; val = val[keys[i]];
if (val == null) { if (val == null) {
return val; return val;
@ -429,26 +429,26 @@ function getValue(obj, path) {
} }
Memory.prototype._findAllSkippingIncludes = function(model, filter) { 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]); return this.fromDb(model, this.collection(model)[key]);
}.bind(this)); }.bind(this));
if (filter) { if (filter) {
if (!filter.order) { if (!filter.order) {
var idNames = this.idNames(model); const idNames = this.idNames(model);
if (idNames && idNames.length) { if (idNames && idNames.length) {
filter.order = idNames; filter.order = idNames;
} }
} }
// do we need some sorting? // do we need some sorting?
if (filter.order) { if (filter.order) {
var orders = filter.order; let orders = filter.order;
if (typeof filter.order === 'string') { if (typeof filter.order === 'string') {
orders = [filter.order]; orders = [filter.order];
} }
orders.forEach(function(key, i) { orders.forEach(function(key, i) {
var reverse = 1; let reverse = 1;
var m = key.match(/\s+(A|DE)SC$/i); const m = key.match(/\s+(A|DE)SC$/i);
if (m) { if (m) {
key = key.replace(/\s+(A|DE)SC/i, ''); key = key.replace(/\s+(A|DE)SC/i, '');
if (m[1].toLowerCase() === 'de') reverse = -1; if (m[1].toLowerCase() === 'de') reverse = -1;
@ -458,7 +458,7 @@ Memory.prototype._findAllSkippingIncludes = function(model, filter) {
nodes = nodes.sort(sorting.bind(orders)); nodes = nodes.sort(sorting.bind(orders));
} }
var nearFilter = geo.nearFilter(filter.where); const nearFilter = geo.nearFilter(filter.where);
// geo sorting // geo sorting
if (nearFilter) { if (nearFilter) {
@ -475,18 +475,18 @@ Memory.prototype._findAllSkippingIncludes = function(model, filter) {
} }
// limit/skip // limit/skip
var skip = filter.skip || filter.offset || 0; const skip = filter.skip || filter.offset || 0;
var limit = filter.limit || nodes.length; const limit = filter.limit || nodes.length;
nodes = nodes.slice(skip, skip + limit); nodes = nodes.slice(skip, skip + limit);
} }
return nodes; return nodes;
function sorting(a, b) { function sorting(a, b) {
var undefinedA, undefinedB; let undefinedA, undefinedB;
for (var i = 0, l = this.length; i < l; i++) { for (let i = 0, l = this.length; i < l; i++) {
var aVal = getValue(a, this[i].key); const aVal = getValue(a, this[i].key);
var bVal = getValue(b, this[i].key); const bVal = getValue(b, this[i].key);
undefinedB = bVal === undefined && aVal !== undefined; undefinedB = bVal === undefined && aVal !== undefined;
undefinedA = aVal === undefined && bVal !== 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) { Memory.prototype.all = function all(model, filter, options, callback) {
var self = this; const self = this;
var nodes = self._findAllSkippingIncludes(model, filter); const nodes = self._findAllSkippingIncludes(model, filter);
process.nextTick(function() { process.nextTick(function() {
if (filter && filter.include) { if (filter && filter.include) {
@ -515,11 +515,11 @@ Memory.prototype.all = function all(model, filter, options, callback) {
}; };
function applyFilter(filter) { function applyFilter(filter) {
var where = filter.where; const where = filter.where;
if (typeof where === 'function') { if (typeof where === 'function') {
return where; return where;
} }
var keys = Object.keys(where); const keys = Object.keys(where);
return function(obj) { return function(obj) {
return keys.every(function(key) { return keys.every(function(key) {
if (key === 'and' || key === 'or') { 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 // Support referencesMany and other embedded relations
// Also support array types. Mongo, possibly PostgreSQL // Also support array types. Mongo, possibly PostgreSQL
if (Array.isArray(value)) { if (Array.isArray(value)) {
var matcher = where[key]; const matcher = where[key];
// The following condition is for the case where we are querying with // The following condition is for the case where we are querying with
// a neq filter, and when the value is an empty array ([]). // a neq filter, and when the value is an empty array ([]).
if (matcher.neq !== undefined && value.length <= 0) { if (matcher.neq !== undefined && value.length <= 0) {
return true; return true;
} }
return value.some(function(v, i) { return value.some(function(v, i) {
var filter = {where: {}}; const filter = {where: {}};
filter.where[i] = matcher; filter.where[i] = matcher;
return applyFilter(filter)(value); 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 // 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 // then, we attempt to emulate mongo db matching. Helps for embedded relations
var dotIndex = key.indexOf('.'); const dotIndex = key.indexOf('.');
var subValue = obj[key.substring(0, dotIndex)]; const subValue = obj[key.substring(0, dotIndex)];
if (dotIndex !== -1) { if (dotIndex !== -1) {
var subFilter = {where: {}}; const subFilter = {where: {}};
var subKey = key.substring(dotIndex + 1); const subKey = key.substring(dotIndex + 1);
subFilter.where[subKey] = where[key]; subFilter.where[subKey] = where[key];
if (Array.isArray(subValue)) { if (Array.isArray(subValue)) {
return subValue.some(applyFilter(subFilter)); return subValue.some(applyFilter(subFilter));
@ -581,12 +581,12 @@ function applyFilter(filter) {
if (pattern instanceof RegExp) { if (pattern instanceof RegExp) {
return pattern; return pattern;
} }
var regex = ''; let regex = '';
// Escaping user input to be treated as a literal string within a regular expression // 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 // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions#Writing_a_Regular_Expression_Pattern
pattern = pattern.replace(/([.*+?^=!:${}()|\[\]\/\\])/g, '\\$1'); pattern = pattern.replace(/([.*+?^=!:${}()|\[\]\/\\])/g, '\\$1');
for (var i = 0, n = pattern.length; i < n; i++) { for (let i = 0, n = pattern.length; i < n; i++) {
var char = pattern.charAt(i); const char = pattern.charAt(i);
if (char === '\\') { if (char === '\\') {
i++; // Skip to next char i++; // Skip to next char
if (i < n) { if (i < n) {
@ -627,7 +627,7 @@ function applyFilter(filter) {
return true; return true;
} }
var i; let i;
if (example.inq) { if (example.inq) {
// if (!value) return false; // if (!value) return false;
for (i = 0; i < example.inq.length; i++) { for (i = 0; i < example.inq.length; i++) {
@ -657,7 +657,7 @@ function applyFilter(filter) {
} }
if (example.like || example.nlike || example.ilike || example.nilike) { 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') { if (typeof like === 'string') {
like = toRegExp(like); like = toRegExp(like);
} }
@ -709,7 +709,7 @@ function applyFilter(filter) {
return val1 - val2; return val1 - val2;
} }
if (val1 instanceof Date) { if (val1 instanceof Date) {
var result = val1 - val2; const result = val1 - val2;
return result; return result;
} }
// Return NaN if we don't know how to compare // 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) { Memory.prototype.destroyAll = function destroyAll(model, where, options, callback) {
var cache = this.collection(model); const cache = this.collection(model);
var filter = null; let filter = null;
var count = 0; let count = 0;
if (where) { if (where) {
filter = applyFilter({where: where}); filter = applyFilter({where: where});
Object.keys(cache).forEach(function(id) { 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) { Memory.prototype.count = function count(model, where, options, callback) {
var cache = this.collection(model); const cache = this.collection(model);
var data = Object.keys(cache); let data = Object.keys(cache);
if (where) { if (where) {
var filter = {where: where}; const filter = {where: where};
data = data.map(function(id) { data = data.map(function(id) {
return this.fromDb(model, cache[id]); return this.fromDb(model, cache[id]);
}.bind(this)); }.bind(this));
@ -769,16 +769,16 @@ Memory.prototype.count = function count(model, where, options, callback) {
Memory.prototype.update = Memory.prototype.update =
Memory.prototype.updateAll = function updateAll(model, where, data, options, cb) { Memory.prototype.updateAll = function updateAll(model, where, data, options, cb) {
var self = this; const self = this;
var cache = this.collection(model); const cache = this.collection(model);
var filter = null; let filter = null;
where = where || {}; where = where || {};
filter = applyFilter({where: where}); filter = applyFilter({where: where});
var ids = Object.keys(cache); const ids = Object.keys(cache);
var count = 0; let count = 0;
async.each(ids, function(id, done) { async.each(ids, function(id, done) {
var inst = self.fromDb(model, cache[id]); const inst = self.fromDb(model, cache[id]);
if (!filter || filter(inst)) { if (!filter || filter(inst)) {
count++; count++;
// The id value from the cache is string // 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) { Memory.prototype.updateAttributes = function updateAttributes(model, id, data, options, cb) {
if (!id) { 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) { if (cb) {
return cb(err); return cb(err);
} else { } else {
@ -809,40 +809,40 @@ Memory.prototype.updateAttributes = function updateAttributes(model, id, data, o
this.setIdValue(model, data, id); this.setIdValue(model, data, id);
var cachedModels = this.collection(model); const cachedModels = this.collection(model);
var modelData = cachedModels && this.collection(model)[id]; const modelData = cachedModels && this.collection(model)[id];
if (modelData) { if (modelData) {
this.save(model, data, options, cb); this.save(model, data, options, cb);
} else { } else {
var msg = g.f('Could not update attributes. {{Object}} with {{id}} %s does not exist!', id); const msg = g.f('Could not update attributes. {{Object}} with {{id}} %s does not exist!', id);
var error = new Error(msg); const error = new Error(msg);
error.statusCode = error.status = 404; error.statusCode = error.status = 404;
cb(error); cb(error);
} }
}; };
Memory.prototype.replaceById = function(model, id, data, options, cb) { Memory.prototype.replaceById = function(model, id, data, options, cb) {
var self = this; const self = this;
if (!id) { 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); }); return process.nextTick(function() { cb(err); });
} }
// Do not modify the data object passed in arguments // Do not modify the data object passed in arguments
data = Object.create(data); data = Object.create(data);
this.setIdValue(model, data, id); this.setIdValue(model, data, id);
var cachedModels = this.collection(model); const cachedModels = this.collection(model);
var modelData = cachedModels && this.collection(model)[id]; const modelData = cachedModels && this.collection(model)[id];
if (!modelData) { if (!modelData) {
var msg = 'Could not replace. Object with id ' + id + ' does not exist!'; const msg = 'Could not replace. Object with id ' + id + ' does not exist!';
var error = new Error(msg); const error = new Error(msg);
error.statusCode = error.status = 404; error.statusCode = error.status = 404;
return process.nextTick(function() { cb(error); }); return process.nextTick(function() { cb(error); });
} }
var newModelData = {}; const newModelData = {};
for (var key in data) { for (const key in data) {
var val = data[key]; const val = data[key];
if (typeof val === 'function') { if (typeof val === 'function') {
continue; // Skip methods continue; // Skip methods
} }
@ -856,13 +856,13 @@ Memory.prototype.replaceById = function(model, id, data, options, cb) {
}; };
Memory.prototype.replaceOrCreate = function(model, data, options, callback) { Memory.prototype.replaceOrCreate = function(model, data, options, callback) {
var self = this; const self = this;
var idName = self.idNames(model)[0]; const idName = self.idNames(model)[0];
var idValue = self.getIdValue(model, data); const idValue = self.getIdValue(model, data);
var filter = {where: {}}; const filter = {where: {}};
filter.where[idName] = idValue; filter.where[idName] = idValue;
var nodes = self._findAllSkippingIncludes(model, filter); const nodes = self._findAllSkippingIncludes(model, filter);
var found = nodes[0]; const found = nodes[0];
if (!found) { if (!found) {
// Calling _createSync to update the collection in a sync way and // 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.collection(model)[id] = serialize(data);
self.saveToFile(data, function(err) { self.saveToFile(data, function(err) {
callback(err, self.fromDb(model, data), {isNewInstance: false}); callback(err, self.fromDb(model, data), {isNewInstance: false});
@ -896,7 +896,7 @@ Memory.prototype.buildNearFilter = function(filter) {
}; };
Memory.prototype.automigrate = function(models, cb) { Memory.prototype.automigrate = function(models, cb) {
var self = this; const self = this;
if ((!cb) && ('function' === typeof models)) { if ((!cb) && ('function' === typeof models)) {
cb = models; cb = models;
@ -912,7 +912,7 @@ Memory.prototype.automigrate = function(models, cb) {
return process.nextTick(cb); return process.nextTick(cb);
} }
var invalidModels = models.filter(function(m) { const invalidModels = models.filter(function(m) {
return !(m in self._models); 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 // 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 // class as the properties are defined at the ModelClass.prototype level
for (var key in update) { for (const key in update) {
var val = update[key]; const val = update[key];
if (typeof val === 'function') { if (typeof val === 'function') {
continue; // Skip methods continue; // Skip methods
} }

View File

@ -5,11 +5,11 @@
'use strict'; 'use strict';
var g = require('strong-globalize')(); const g = require('strong-globalize')();
var util = require('util'); const util = require('util');
var Connector = require('loopback-connector').Connector; const Connector = require('loopback-connector').Connector;
var utils = require('../utils'); const utils = require('../utils');
var crypto = require('crypto'); const crypto = require('crypto');
/** /**
* Initialize the Transient connector against the given data source * 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) { Transient.prototype.generateId = function(model, data, idName) {
var idType; let idType;
var props = this._models[model].properties; const props = this._models[model].properties;
if (idName) idType = props[idName] && props[idName].type; if (idName) idType = props[idName] && props[idName].type;
idType = idType || this.getDefaultIdType(); idType = idType || this.getDefaultIdType();
if (idType === Number) { if (idType === Number) {
@ -89,10 +89,11 @@ Transient.prototype.count = function count(model, callback, where) {
}; };
Transient.prototype.create = function create(model, data, callback) { Transient.prototype.create = function create(model, data, callback) {
var props = this._models[model].properties; const props = this._models[model].properties;
var idName = this.idName(model); const idName = this.idName(model);
let id = undefined;
if (idName && props[idName]) { if (idName && props[idName]) {
var id = this.getIdValue(model, data) || this.generateId(model, data, idName); id = this.getIdValue(model, data) || this.generateId(model, data, idName);
id = (props[idName] && props[idName].type && props[idName].type(id)) || id; id = (props[idName] && props[idName].type && props[idName].type(id)) || id;
this.setIdValue(model, data, id); this.setIdValue(model, data, id);
} }
@ -105,13 +106,13 @@ Transient.prototype.save = function save(model, data, callback) {
Transient.prototype.update = Transient.prototype.update =
Transient.prototype.updateAll = function updateAll(model, where, data, cb) { Transient.prototype.updateAll = function updateAll(model, where, data, cb) {
var count = 0; const count = 0;
this.flush('update', {count: count}, cb); this.flush('update', {count: count}, cb);
}; };
Transient.prototype.updateAttributes = function updateAttributes(model, id, data, cb) { Transient.prototype.updateAttributes = function updateAttributes(model, id, data, cb) {
if (!id) { 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) { if (cb) {
return cb(err); return cb(err);
} else { } else {

File diff suppressed because it is too large Load Diff

View File

@ -10,30 +10,30 @@
/*! /*!
* Module dependencies * Module dependencies
*/ */
var ModelBuilder = require('./model-builder.js').ModelBuilder; const ModelBuilder = require('./model-builder.js').ModelBuilder;
var ModelDefinition = require('./model-definition.js'); const ModelDefinition = require('./model-definition.js');
var RelationDefinition = require('./relation-definition.js'); const RelationDefinition = require('./relation-definition.js');
var OberserverMixin = require('./observer'); const OberserverMixin = require('./observer');
var jutil = require('./jutil'); const jutil = require('./jutil');
var utils = require('./utils'); const utils = require('./utils');
var ModelBaseClass = require('./model.js'); const ModelBaseClass = require('./model.js');
var DataAccessObject = require('./dao.js'); const DataAccessObject = require('./dao.js');
var defineScope = require('./scope.js').defineScope; const defineScope = require('./scope.js').defineScope;
var EventEmitter = require('events').EventEmitter; const EventEmitter = require('events').EventEmitter;
var util = require('util'); const util = require('util');
var assert = require('assert'); const assert = require('assert');
var async = require('async'); const async = require('async');
var traverse = require('traverse'); const traverse = require('traverse');
var g = require('strong-globalize')(); const g = require('strong-globalize')();
var juggler = require('..'); const juggler = require('..');
var deprecated = require('depd')('loopback-datasource-juggler'); const deprecated = require('depd')('loopback-datasource-juggler');
var Transaction = require('loopback-connector').Transaction; const Transaction = require('loopback-connector').Transaction;
if (process.env.DEBUG === 'loopback') { if (process.env.DEBUG === 'loopback') {
// For back-compatibility // For back-compatibility
process.env.DEBUG = 'loopback:*'; process.env.DEBUG = 'loopback:*';
} }
var debug = require('debug')('loopback:datasource'); const debug = require('debug')('loopback:datasource');
/*! /*!
* Export public API * Export public API
@ -43,7 +43,7 @@ exports.DataSource = DataSource;
/*! /*!
* Helpers * Helpers
*/ */
var slice = Array.prototype.slice; const slice = Array.prototype.slice;
/** /**
* LoopBack models can manipulate data via the DataSource object. * LoopBack models can manipulate data via the DataSource object.
@ -140,16 +140,16 @@ function DataSource(name, settings, modelBuilder) {
this._setupConnector(); this._setupConnector();
// connector // connector
var connector = this.connector; const connector = this.connector;
// DataAccessObject - connector defined or supply the default // 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() { this.DataAccessObject = function() {
}; };
// define DataAccessObject methods // define DataAccessObject methods
Object.keys(dao).forEach(function(name) { Object.keys(dao).forEach(function(name) {
var fn = dao[name]; const fn = dao[name];
this.DataAccessObject[name] = fn; this.DataAccessObject[name] = fn;
if (typeof fn === 'function') { if (typeof fn === 'function') {
@ -166,7 +166,7 @@ function DataSource(name, settings, modelBuilder) {
// define DataAccessObject.prototype methods // define DataAccessObject.prototype methods
Object.keys(dao.prototype || []).forEach(function(name) { Object.keys(dao.prototype || []).forEach(function(name) {
var fn = dao.prototype[name]; const fn = dao.prototype[name];
this.DataAccessObject.prototype[name] = fn; this.DataAccessObject.prototype[name] = fn;
if (typeof fn === 'function') { if (typeof fn === 'function') {
this.defineOperation(name, { this.defineOperation(name, {
@ -199,14 +199,14 @@ DataSource.prototype._setupConnector = function() {
// Set up the dataSource if the connector doesn't do so // Set up the dataSource if the connector doesn't do so
this.connector.dataSource = this; this.connector.dataSource = this;
} }
var dataSource = this; const dataSource = this;
this.connector.log = function(query, start) { this.connector.log = function(query, start) {
dataSource.log(query, start); dataSource.log(query, start);
}; };
this.connector.logger = function(query) { this.connector.logger = function(query) {
var t1 = Date.now(); const t1 = Date.now();
var log = this.log; const log = this.log;
return function(q) { return function(q) {
log(q || query, t1); log(q || query, t1);
}; };
@ -218,7 +218,7 @@ DataSource.prototype._setupConnector = function() {
// List possible connector module names // List possible connector module names
function connectorModuleNames(name) { function connectorModuleNames(name) {
var names = []; // Check the name as is const names = []; // Check the name as is
if (!name.match(/^\//)) { if (!name.match(/^\//)) {
names.push('./connectors/' + name); // Check built-in connectors names.push('./connectors/' + name); // Check built-in connectors
if (name.indexOf('loopback-connector-') !== 0) { if (name.indexOf('loopback-connector-') !== 0) {
@ -235,13 +235,13 @@ function connectorModuleNames(name) {
// testable with DI // testable with DI
function tryModules(names, loader) { function tryModules(names, loader) {
var mod; let mod;
loader = loader || require; loader = loader || require;
for (var m = 0; m < names.length; m++) { for (let m = 0; m < names.length; m++) {
try { try {
mod = loader(names[m]); mod = loader(names[m]);
} catch (e) { } catch (e) {
var notFound = e.code === 'MODULE_NOT_FOUND' && const notFound = e.code === 'MODULE_NOT_FOUND' &&
e.message && e.message.indexOf(names[m]) > 0; e.message && e.message.indexOf(names[m]) > 0;
if (notFound) { if (notFound) {
@ -266,9 +266,9 @@ function tryModules(names, loader) {
* @private * @private
*/ */
DataSource._resolveConnector = function(name, loader) { DataSource._resolveConnector = function(name, loader) {
var names = connectorModuleNames(name); const names = connectorModuleNames(name);
var connector = tryModules(names, loader); const connector = tryModules(names, loader);
var error = null; let error = null;
if (!connector) { if (!connector) {
error = g.f('\nWARNING: {{LoopBack}} connector "%s" is not installed ' + 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', '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) { DataSource.prototype.connect = function(callback) {
callback = callback || utils.createPromiseCallback(); callback = callback || utils.createPromiseCallback();
var self = this; const self = this;
if (this.connected) { if (this.connected) {
// The data source is already connected, return immediately // The data source is already connected, return immediately
process.nextTick(callback); process.nextTick(callback);
@ -317,7 +317,7 @@ DataSource.prototype.connect = function(callback) {
this.connector.connect(function(err, result) { this.connector.connect(function(err, result) {
self.connecting = false; self.connecting = false;
if (!err) self.connected = true; if (!err) self.connected = true;
var cbs = self.pendingConnectCallbacks; const cbs = self.pendingConnectCallbacks;
self.pendingConnectCallbacks = []; self.pendingConnectCallbacks = [];
if (!err) { if (!err) {
self.emit('connected'); self.emit('connected');
@ -362,8 +362,8 @@ DataSource.prototype.connect = function(callback) {
* @private * @private
*/ */
DataSource.prototype.setup = function(dsName, settings) { DataSource.prototype.setup = function(dsName, settings) {
var dataSource = this; const dataSource = this;
var connector; let connector;
// First argument is an `object` // First argument is an `object`
if (dsName && typeof dsName === '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); this.name = dsName || (typeof this.settings.name === 'string' && this.settings.name);
var connectorName; let connectorName;
if (typeof connector === 'string') { if (typeof connector === 'string') {
// Connector needs to be resolved by name // Connector needs to be resolved by name
connectorName = connector; connectorName = connector;
@ -441,7 +441,7 @@ DataSource.prototype.setup = function(dsName, settings) {
if ((!connector) && connectorName) { if ((!connector) && connectorName) {
// The connector has not been resolved // The connector has not been resolved
var result = DataSource._resolveConnector(connectorName); const result = DataSource._resolveConnector(connectorName);
connector = result.connector; connector = result.connector;
if (!connector) { if (!connector) {
console.error(result.error); console.error(result.error);
@ -451,7 +451,7 @@ DataSource.prototype.setup = function(dsName, settings) {
} }
if (connector) { if (connector) {
var postInit = function postInit(err, result) { const postInit = function postInit(err, result) {
this._setupConnector(); this._setupConnector();
// we have an connector now? // we have an connector now?
if (!this.connector) { if (!this.connector) {
@ -532,7 +532,7 @@ function isModelDataSourceAttached(model) {
*/ */
DataSource.prototype.defineScopes = function(modelClass, scopes) { DataSource.prototype.defineScopes = function(modelClass, scopes) {
if (scopes) { if (scopes) {
for (var s in scopes) { for (const s in scopes) {
defineScope(modelClass, modelClass, s, scopes[s], {}, scopes[s].options); defineScope(modelClass, modelClass, s, scopes[s], {}, scopes[s].options);
} }
} }
@ -547,16 +547,16 @@ DataSource.prototype.defineScopes = function(modelClass, scopes) {
* object definitions. * object definitions.
*/ */
DataSource.prototype.defineRelations = function(modelClass, relations) { 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 // 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)) { if (!isModelDataSourceAttached(targetModel)) {
targetModel.once('dataAccessConfigured', function(targetModel) { targetModel.once('dataAccessConfigured', function(targetModel) {
// Check if the through model doesn't exist or resolved // Check if the through model doesn't exist or resolved
if (!throughModel || isModelDataSourceAttached(throughModel)) { if (!throughModel || isModelDataSourceAttached(throughModel)) {
// The target model is resolved // The target model is resolved
var params = traverse(relation).clone(); const params = traverse(relation).clone();
params.as = relationName; params.as = relationName;
params.model = targetModel; params.model = targetModel;
if (throughModel) { if (throughModel) {
@ -572,7 +572,7 @@ DataSource.prototype.defineRelations = function(modelClass, relations) {
throughModel.once('dataAccessConfigured', function(throughModel) { throughModel.once('dataAccessConfigured', function(throughModel) {
if (isModelDataSourceAttached(targetModel)) { if (isModelDataSourceAttached(targetModel)) {
// The target model is resolved // The target model is resolved
var params = traverse(relation).clone(); const params = traverse(relation).clone();
params.as = relationName; params.as = relationName;
params.model = targetModel; params.model = targetModel;
params.through = throughModel; params.through = throughModel;
@ -585,8 +585,8 @@ DataSource.prototype.defineRelations = function(modelClass, relations) {
// Set up the relations // Set up the relations
if (relations) { if (relations) {
Object.keys(relations).forEach(function(relationName) { Object.keys(relations).forEach(function(relationName) {
var targetModel; let targetModel;
var r = relations[relationName]; const r = relations[relationName];
validateRelation(relationName, r); validateRelation(relationName, r);
@ -594,7 +594,7 @@ DataSource.prototype.defineRelations = function(modelClass, relations) {
targetModel = isModelClass(r.model) ? r.model : self.getModel(r.model, true); targetModel = isModelClass(r.model) ? r.model : self.getModel(r.model, true);
} }
var throughModel = null; let throughModel = null;
if (r.through) { if (r.through) {
throughModel = isModelClass(r.through) ? r.through : self.getModel(r.through, true); 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); deferRelationSetup(relationName, r, targetModel, throughModel);
} else { } else {
// The target model is resolved // The target model is resolved
var params = traverse(r).clone(); const params = traverse(r).clone();
params.as = relationName; params.as = relationName;
params.model = targetModel; params.model = targetModel;
if (throughModel) { if (throughModel) {
@ -618,9 +618,9 @@ DataSource.prototype.defineRelations = function(modelClass, relations) {
}; };
function validateRelation(relationName, relation) { function validateRelation(relationName, relation) {
var rn = relationName; const rn = relationName;
var r = relation; const r = relation;
var msg, code; let msg, code;
assert(DataSource.relationTypes.indexOf(r.type) !== -1, 'Invalid relation type: ' + r.type); assert(DataSource.relationTypes.indexOf(r.type) !== -1, 'Invalid relation type: ' + r.type);
assert(isValidRelationName(rn), 'Invalid relation name: ' + rn); assert(isValidRelationName(rn), 'Invalid relation name: ' + rn);
@ -668,7 +668,7 @@ function validateRelation(relationName, relation) {
} }
if (msg) { if (msg) {
var error = new Error(msg); const error = new Error(msg);
error.details = {code: code, rType: r.type, rName: rn}; error.details = {code: code, rType: r.type, rName: rn};
throw error; throw error;
} }
@ -683,7 +683,7 @@ function validateRelation(relationName, relation) {
} }
function isValidRelationName(relationName) { function isValidRelationName(relationName) {
var invalidRelationNames = ['trigger']; const invalidRelationNames = ['trigger'];
return invalidRelationNames.indexOf(relationName) === -1; return invalidRelationNames.indexOf(relationName) === -1;
} }
@ -697,11 +697,11 @@ function isValidRelationName(relationName) {
DataSource.prototype.setupDataAccess = function(modelClass, settings) { DataSource.prototype.setupDataAccess = function(modelClass, settings) {
if (this.connector) { if (this.connector) {
// Check if the id property should be generated // Check if the id property should be generated
var idName = modelClass.definition.idName(); const idName = modelClass.definition.idName();
var idProp = modelClass.definition.rawProperties[idName]; const idProp = modelClass.definition.rawProperties[idName];
if (idProp && idProp.generated && this.connector.getDefaultIdType) { if (idProp && idProp.generated && this.connector.getDefaultIdType) {
// Set the default id type from connector's ability // Set the default id type from connector's ability
var idType = this.connector.getDefaultIdType() || String; const idType = this.connector.getDefaultIdType() || String;
idProp.type = idType; idProp.type = idType;
modelClass.definition.rawProperties[idName].type = idType; modelClass.definition.rawProperties[idName].type = idType;
modelClass.definition.properties[idName].type = idType; modelClass.definition.properties[idName].type = idType;
@ -720,7 +720,7 @@ DataSource.prototype.setupDataAccess = function(modelClass, settings) {
this.mixin(modelClass); this.mixin(modelClass);
// define relations from LDL (options.relations) // define relations from LDL (options.relations)
var relations = settings.relationships || settings.relations; const relations = settings.relationships || settings.relations;
this.defineRelations(modelClass, relations); this.defineRelations(modelClass, relations);
// Emit the dataAccessConfigured event to indicate all the methods for data // 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); modelClass.emit('dataAccessConfigured', modelClass);
// define scopes from LDL (options.relations) // define scopes from LDL (options.relations)
var scopes = settings.scopes || {}; const scopes = settings.scopes || {};
this.defineScopes(modelClass, scopes); this.defineScopes(modelClass, scopes);
}; };
@ -783,7 +783,7 @@ DataSource.prototype.setupDataAccess = function(modelClass, settings) {
DataSource.prototype.createModel = DataSource.prototype.createModel =
DataSource.prototype.define = function defineClass(className, properties, settings) { DataSource.prototype.define = function defineClass(className, properties, settings) {
var args = slice.call(arguments); const args = slice.call(arguments);
if (!className) { if (!className) {
throw new Error(g.f('Class name required')); 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; modelClass.dataSource = this;
if (settings.unresolved) { if (settings.unresolved) {
@ -841,16 +841,16 @@ DataSource.prototype.deleteModelByName = function(modelName) {
*/ */
DataSource.prototype.mixin = function(ModelCtor) { DataSource.prototype.mixin = function(ModelCtor) {
var ops = this.operations(); const ops = this.operations();
var DAO = this.DataAccessObject; const DAO = this.DataAccessObject;
// mixin DAO // mixin DAO
jutil.mixin(ModelCtor, DAO, {proxyFunctions: true, override: true}); jutil.mixin(ModelCtor, DAO, {proxyFunctions: true, override: true});
// decorate operations as alias functions // decorate operations as alias functions
Object.keys(ops).forEach(function(name) { Object.keys(ops).forEach(function(name) {
var op = ops[name]; const op = ops[name];
var scope; let scope;
if (op.enabled) { if (op.enabled) {
scope = op.prototype ? ModelCtor.prototype : ModelCtor; scope = op.prototype ? ModelCtor.prototype : ModelCtor;
@ -908,8 +908,8 @@ DataSource.prototype.getModelDefinition = function(name) {
* no subtype. * no subtype.
*/ */
DataSource.prototype.getTypes = function() { DataSource.prototype.getTypes = function() {
var getTypes = this.connector && this.connector.getTypes; const getTypes = this.connector && this.connector.getTypes;
var types = getTypes && getTypes() || []; let types = getTypes && getTypes() || [];
if (typeof types === 'string') { if (typeof types === 'string') {
types = types.split(/[\s,\/]+/); types = types.split(/[\s,\/]+/);
} }
@ -922,10 +922,10 @@ DataSource.prototype.getTypes = function() {
* @returns {Boolean} true if all types are supported by the data source * @returns {Boolean} true if all types are supported by the data source
*/ */
DataSource.prototype.supportTypes = function(types) { DataSource.prototype.supportTypes = function(types) {
var supportedTypes = this.getTypes(); const supportedTypes = this.getTypes();
if (Array.isArray(types)) { if (Array.isArray(types)) {
// Check each of the 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) { if (supportedTypes.indexOf(types[i]) === -1) {
// Not supported // Not supported
return false; return false;
@ -983,7 +983,7 @@ DataSource.prototype.attach = function(modelClass) {
DataSource.prototype.defineProperty = function(model, prop, params) { DataSource.prototype.defineProperty = function(model, prop, params) {
this.modelBuilder.defineProperty(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) { if (this.connector && this.connector.defineProperty) {
this.connector.defineProperty(model, prop, resolvedProp); this.connector.defineProperty(model, prop, resolvedProp);
} }
@ -1024,7 +1024,7 @@ DataSource.prototype.automigrate = function(models, cb) {
models = [models]; models = [models];
} }
var attachedModels = this.connector._models; const attachedModels = this.connector._models;
if (attachedModels && typeof attachedModels === 'object') { if (attachedModels && typeof attachedModels === 'object') {
models = models || Object.keys(attachedModels); models = models || Object.keys(attachedModels);
@ -1034,7 +1034,7 @@ DataSource.prototype.automigrate = function(models, cb) {
return cb.promise; return cb.promise;
} }
var invalidModels = models.filter(function(m) { const invalidModels = models.filter(function(m) {
return !(m in attachedModels); return !(m in attachedModels);
}); });
@ -1085,7 +1085,7 @@ DataSource.prototype.autoupdate = function(models, cb) {
models = [models]; models = [models];
} }
var attachedModels = this.connector._models; const attachedModels = this.connector._models;
if (attachedModels && typeof attachedModels === 'object') { if (attachedModels && typeof attachedModels === 'object') {
models = models || Object.keys(attachedModels); models = models || Object.keys(attachedModels);
@ -1095,7 +1095,7 @@ DataSource.prototype.autoupdate = function(models, cb) {
return cb.promise; return cb.promise;
} }
var invalidModels = models.filter(function(m) { const invalidModels = models.filter(function(m) {
return !(m in attachedModels); return !(m in attachedModels);
}); });
@ -1406,10 +1406,10 @@ function fromDBName(dbName, camelCase) {
if (!dbName) { if (!dbName) {
return dbName; return dbName;
} }
var parts = dbName.split(/-|_/); const parts = dbName.split(/-|_/);
parts[0] = camelCase ? parts[0].toLowerCase() : capitalize(parts[0]); 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]); parts[i] = capitalize(parts[i]);
} }
return parts.join(''); return parts.join('');
@ -1492,7 +1492,7 @@ DataSource.prototype.discoverSchema = function(tableName, options, cb) {
cb && cb(err, schemas); cb && cb(err, schemas);
return; return;
} }
for (var s in schemas) { for (const s in schemas) {
cb && cb(null, schemas[s]); cb && cb(null, schemas[s]);
return; return;
} }
@ -1522,10 +1522,10 @@ DataSource.prototype.discoverSchemas = function(tableName, options, cb) {
cb = cb || utils.createPromiseCallback(); cb = cb || utils.createPromiseCallback();
var self = this; const self = this;
var dbType = this.connector.name; const dbType = this.connector.name;
var nameMapper; let nameMapper;
if (options.nameMapper === null) { if (options.nameMapper === null) {
// No mapping // No mapping
nameMapper = function(type, name) { nameMapper = function(type, name) {
@ -1553,11 +1553,11 @@ DataSource.prototype.discoverSchemas = function(tableName, options, cb) {
return cb.promise; return cb.promise;
} }
var tasks = [ const tasks = [
this.discoverModelProperties.bind(this, tableName, options), this.discoverModelProperties.bind(this, tableName, options),
this.discoverPrimaryKeys.bind(this, tableName, options)]; this.discoverPrimaryKeys.bind(this, tableName, options)];
var followingRelations = options.associations || options.relations; const followingRelations = options.associations || options.relations;
if (followingRelations) { if (followingRelations) {
tasks.push(this.discoverForeignKeys.bind(this, tableName, options)); tasks.push(this.discoverForeignKeys.bind(this, tableName, options));
} }
@ -1568,15 +1568,15 @@ DataSource.prototype.discoverSchemas = function(tableName, options, cb) {
return cb.promise; return cb.promise;
} }
var columns = results[0]; const columns = results[0];
if (!columns || columns.length === 0) { if (!columns || columns.length === 0) {
cb(new Error(g.f('Table \'%s\' does not exist.', tableName))); cb(new Error(g.f('Table \'%s\' does not exist.', tableName)));
return cb.promise; return cb.promise;
} }
// Handle primary keys // Handle primary keys
var primaryKeys = results[1] || []; const primaryKeys = results[1] || [];
var pks = {}; const pks = {};
primaryKeys.forEach(function(pk) { primaryKeys.forEach(function(pk) {
pks[pk.columnName] = pk.keySeq; pks[pk.columnName] = pk.keySeq;
}); });
@ -1585,7 +1585,7 @@ DataSource.prototype.discoverSchemas = function(tableName, options, cb) {
debug('Primary keys: ', pks); debug('Primary keys: ', pks);
} }
var schema = { const schema = {
name: nameMapper('table', tableName), name: nameMapper('table', tableName),
options: { options: {
idInjection: false, // DO NOT add id property idInjection: false, // DO NOT add id property
@ -1599,7 +1599,7 @@ DataSource.prototype.discoverSchemas = function(tableName, options, cb) {
}; };
columns.forEach(function(item) { columns.forEach(function(item) {
var propName = nameMapper('column', item.columnName); const propName = nameMapper('column', item.columnName);
schema.properties[propName] = { schema.properties[propName] = {
type: item.type, type: item.type,
required: (item.nullable === 'N' || item.nullable === 'NO' || required: (item.nullable === 'N' || item.nullable === 'NO' ||
@ -1612,7 +1612,7 @@ DataSource.prototype.discoverSchemas = function(tableName, options, cb) {
if (pks[item.columnName]) { if (pks[item.columnName]) {
schema.properties[propName].id = 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, columnName: item.columnName,
dataType: item.dataType, dataType: item.dataType,
dataLength: item.dataLength, dataLength: item.dataLength,
@ -1622,7 +1622,7 @@ DataSource.prototype.discoverSchemas = function(tableName, options, cb) {
}; };
// merge connector-specific properties // merge connector-specific properties
if (item[dbType]) { if (item[dbType]) {
for (var k in item[dbType]) { for (const k in item[dbType]) {
dbSpecific[k] = item[dbType][k]; dbSpecific[k] = item[dbType][k];
} }
} }
@ -1630,7 +1630,7 @@ DataSource.prototype.discoverSchemas = function(tableName, options, cb) {
// Add current modelName to the visited tables // Add current modelName to the visited tables
options.visited = options.visited || {}; options.visited = options.visited || {};
var schemaKey = columns[0].owner + '.' + tableName; const schemaKey = columns[0].owner + '.' + tableName;
if (!options.visited.hasOwnProperty(schemaKey)) { if (!options.visited.hasOwnProperty(schemaKey)) {
if (self.settings.debug) { if (self.settings.debug) {
debug('Adding schema for ' + schemaKey); debug('Adding schema for ' + schemaKey);
@ -1638,13 +1638,13 @@ DataSource.prototype.discoverSchemas = function(tableName, options, cb) {
options.visited[schemaKey] = schema; options.visited[schemaKey] = schema;
} }
var otherTables = {}; const otherTables = {};
if (followingRelations) { if (followingRelations) {
// Handle foreign keys // Handle foreign keys
var fks = {}; const fks = {};
var foreignKeys = results[2] || []; const foreignKeys = results[2] || [];
foreignKeys.forEach(function(fk) { foreignKeys.forEach(function(fk) {
var fkInfo = { const fkInfo = {
keySeq: fk.keySeq, keySeq: fk.keySeq,
owner: fk.pkOwner, owner: fk.pkOwner,
tableName: fk.pkTableName, tableName: fk.pkTableName,
@ -1663,14 +1663,14 @@ DataSource.prototype.discoverSchemas = function(tableName, options, cb) {
schema.options.relations = {}; schema.options.relations = {};
foreignKeys.forEach(function(fk) { foreignKeys.forEach(function(fk) {
var propName = nameMapper('fk', (fk.fkName || fk.pkTableName)); const propName = nameMapper('fk', (fk.fkName || fk.pkTableName));
schema.options.relations[propName] = { schema.options.relations[propName] = {
model: nameMapper('table', fk.pkTableName), model: nameMapper('table', fk.pkTableName),
type: 'belongsTo', type: 'belongsTo',
foreignKey: nameMapper('column', fk.fkColumnName), 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)) { if (!options.visited.hasOwnProperty(key) && !otherTables.hasOwnProperty(key)) {
otherTables[key] = {owner: fk.pkOwner, tableName: fk.pkTableName}; 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) { if (Object.keys(otherTables).length === 0) {
cb(null, options.visited); cb(null, options.visited);
} else { } else {
var moreTasks = []; const moreTasks = [];
for (var t in otherTables) { for (const t in otherTables) {
if (self.settings.debug) { if (self.settings.debug) {
debug('Discovering related schema for ' + schemaKey); debug('Discovering related schema for ' + schemaKey);
} }
var newOptions = {}; const newOptions = {};
for (var key in options) { for (const key in options) {
newOptions[key] = options[key]; newOptions[key] = options[key];
} }
newOptions.owner = otherTables[t].owner; 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)); moreTasks.push(DataSource.prototype.discoverSchemas.bind(self, otherTables[t].tableName, newOptions));
} }
async.parallel(moreTasks, function(err, results) { async.parallel(moreTasks, function(err, results) {
var result = results && results[0]; const result = results && results[0];
cb(err, result); cb(err, result);
}); });
} }
@ -1715,15 +1715,15 @@ DataSource.prototype.discoverSchemas = function(tableName, options, cb) {
* @returns {Array<Object>} An array of schema definition objects. * @returns {Array<Object>} An array of schema definition objects.
*/ */
DataSource.prototype.discoverSchemasSync = function(modelName, options) { DataSource.prototype.discoverSchemasSync = function(modelName, options) {
var self = this; const self = this;
var dbType = this.connector.name; const dbType = this.connector.name;
var columns = this.discoverModelPropertiesSync(modelName, options); const columns = this.discoverModelPropertiesSync(modelName, options);
if (!columns || columns.length === 0) { if (!columns || columns.length === 0) {
return []; return [];
} }
var nameMapper = options.nameMapper || function mapName(type, name) { const nameMapper = options.nameMapper || function mapName(type, name) {
if (type === 'table' || type === 'model') { if (type === 'table' || type === 'model') {
return fromDBName(name, false); return fromDBName(name, false);
} else { } else {
@ -1732,8 +1732,8 @@ DataSource.prototype.discoverSchemasSync = function(modelName, options) {
}; };
// Handle primary keys // Handle primary keys
var primaryKeys = this.discoverPrimaryKeysSync(modelName, options); const primaryKeys = this.discoverPrimaryKeysSync(modelName, options);
var pks = {}; const pks = {};
primaryKeys.forEach(function(pk) { primaryKeys.forEach(function(pk) {
pks[pk.columnName] = pk.keySeq; pks[pk.columnName] = pk.keySeq;
}); });
@ -1742,7 +1742,7 @@ DataSource.prototype.discoverSchemasSync = function(modelName, options) {
debug('Primary keys: ', pks); debug('Primary keys: ', pks);
} }
var schema = { const schema = {
name: nameMapper('table', modelName), name: nameMapper('table', modelName),
options: { options: {
idInjection: false, // DO NOT add id property idInjection: false, // DO NOT add id property
@ -1756,9 +1756,9 @@ DataSource.prototype.discoverSchemasSync = function(modelName, options) {
}; };
columns.forEach(function(item) { 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] = { schema.properties[propName] = {
type: item.type, type: item.type,
required: (item.nullable === 'N'), required: (item.nullable === 'N'),
@ -1782,7 +1782,7 @@ DataSource.prototype.discoverSchemasSync = function(modelName, options) {
// Add current modelName to the visited tables // Add current modelName to the visited tables
options.visited = options.visited || {}; options.visited = options.visited || {};
var schemaKey = columns[0].owner + '.' + modelName; const schemaKey = columns[0].owner + '.' + modelName;
if (!options.visited.hasOwnProperty(schemaKey)) { if (!options.visited.hasOwnProperty(schemaKey)) {
if (self.settings.debug) { if (self.settings.debug) {
debug('Adding schema for ' + schemaKey); debug('Adding schema for ' + schemaKey);
@ -1790,14 +1790,14 @@ DataSource.prototype.discoverSchemasSync = function(modelName, options) {
options.visited[schemaKey] = schema; options.visited[schemaKey] = schema;
} }
var otherTables = {}; const otherTables = {};
var followingRelations = options.associations || options.relations; const followingRelations = options.associations || options.relations;
if (followingRelations) { if (followingRelations) {
// Handle foreign keys // Handle foreign keys
var fks = {}; const fks = {};
var foreignKeys = this.discoverForeignKeysSync(modelName, options); const foreignKeys = this.discoverForeignKeysSync(modelName, options);
foreignKeys.forEach(function(fk) { foreignKeys.forEach(function(fk) {
var fkInfo = { const fkInfo = {
keySeq: fk.keySeq, keySeq: fk.keySeq,
owner: fk.pkOwner, owner: fk.pkOwner,
tableName: fk.pkTableName, tableName: fk.pkTableName,
@ -1816,14 +1816,14 @@ DataSource.prototype.discoverSchemasSync = function(modelName, options) {
schema.options.relations = {}; schema.options.relations = {};
foreignKeys.forEach(function(fk) { foreignKeys.forEach(function(fk) {
var propName = nameMapper('column', fk.pkTableName); const propName = nameMapper('column', fk.pkTableName);
schema.options.relations[propName] = { schema.options.relations[propName] = {
model: nameMapper('table', fk.pkTableName), model: nameMapper('table', fk.pkTableName),
type: 'belongsTo', type: 'belongsTo',
foreignKey: nameMapper('column', fk.fkColumnName), 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)) { if (!options.visited.hasOwnProperty(key) && !otherTables.hasOwnProperty(key)) {
otherTables[key] = {owner: fk.pkOwner, tableName: fk.pkTableName}; otherTables[key] = {owner: fk.pkOwner, tableName: fk.pkTableName};
} }
@ -1833,13 +1833,13 @@ DataSource.prototype.discoverSchemasSync = function(modelName, options) {
if (Object.keys(otherTables).length === 0) { if (Object.keys(otherTables).length === 0) {
return options.visited; return options.visited;
} else { } else {
var moreTasks = []; const moreTasks = [];
for (var t in otherTables) { for (const t in otherTables) {
if (self.settings.debug) { if (self.settings.debug) {
debug('Discovering related schema for ' + schemaKey); debug('Discovering related schema for ' + schemaKey);
} }
var newOptions = {}; const newOptions = {};
for (var key in options) { for (const key in options) {
newOptions[key] = options[key]; newOptions[key] = options[key];
} }
newOptions.owner = otherTables[t].owner; newOptions.owner = otherTables[t].owner;
@ -1863,7 +1863,7 @@ DataSource.prototype.discoverSchemasSync = function(modelName, options) {
* constructors, keyed by model name * constructors, keyed by model name
*/ */
DataSource.prototype.discoverAndBuildModels = function(modelName, options, cb) { DataSource.prototype.discoverAndBuildModels = function(modelName, options, cb) {
var self = this; const self = this;
options = options || {}; options = options || {};
this.discoverSchemas(modelName, options, function(err, schemas) { this.discoverSchemas(modelName, options, function(err, schemas) {
if (err) { if (err) {
@ -1871,9 +1871,9 @@ DataSource.prototype.discoverAndBuildModels = function(modelName, options, cb) {
return; return;
} }
var schemaList = []; const schemaList = [];
for (var s in schemas) { for (const s in schemas) {
var schema = schemas[s]; const schema = schemas[s];
if (options.base) { if (options.base) {
schema.options = schema.options || {}; schema.options = schema.options || {};
schema.options.base = options.base; schema.options.base = options.base;
@ -1881,7 +1881,7 @@ DataSource.prototype.discoverAndBuildModels = function(modelName, options, cb) {
schemaList.push(schema); schemaList.push(schema);
} }
var models = self.modelBuilder.buildModels(schemaList, const models = self.modelBuilder.buildModels(schemaList,
self.createModel.bind(self)); self.createModel.bind(self));
cb && cb(err, models); cb && cb(err, models);
@ -1905,11 +1905,11 @@ DataSource.prototype.discoverAndBuildModels = function(modelName, options, cb) {
*/ */
DataSource.prototype.discoverAndBuildModelsSync = function(modelName, options) { DataSource.prototype.discoverAndBuildModelsSync = function(modelName, options) {
options = options || {}; options = options || {};
var schemas = this.discoverSchemasSync(modelName, options); const schemas = this.discoverSchemasSync(modelName, options);
var schemaList = []; const schemaList = [];
for (var s in schemas) { for (const s in schemas) {
var schema = schemas[s]; const schema = schemas[s];
if (options.base) { if (options.base) {
schema.options = schema.options || {}; schema.options = schema.options || {};
schema.options.base = options.base; schema.options.base = options.base;
@ -1917,7 +1917,7 @@ DataSource.prototype.discoverAndBuildModelsSync = function(modelName, options) {
schemaList.push(schema); schemaList.push(schema);
} }
var models = this.modelBuilder.buildModels(schemaList, const models = this.modelBuilder.buildModels(schemaList,
this.createModel.bind(this)); this.createModel.bind(this));
return models; return models;
@ -1932,7 +1932,7 @@ DataSource.prototype.discoverAndBuildModelsSync = function(modelName, options) {
*/ */
DataSource.prototype.buildModelFromInstance = function(name, json, options) { DataSource.prototype.buildModelFromInstance = function(name, json, options) {
// Introspect the JSON document to generate a schema // 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 // Create a model for the generated schema
return this.createModel(name, schema, options); return this.createModel(name, schema, options);
@ -2063,8 +2063,8 @@ DataSource.prototype.idNames = function(modelName) {
* @returns {Object} The id property definition * @returns {Object} The id property definition
*/ */
DataSource.prototype.idProperty = function(modelName) { DataSource.prototype.idProperty = function(modelName) {
var def = this.getModelDefinition(modelName); const def = this.getModelDefinition(modelName);
var idProps = def && def.ids(); const idProps = def && def.ids();
return idProps && idProps[0] && idProps[0].property; 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 * @param {String} pkName (optional) primary key used for foreignKey
*/ */
DataSource.prototype.defineForeignKey = function defineForeignKey(className, key, foreignClassName, pkName) { DataSource.prototype.defineForeignKey = function defineForeignKey(className, key, foreignClassName, pkName) {
var pkType = null; let pkType = null;
var foreignModel = this.getModelDefinition(foreignClassName); const foreignModel = this.getModelDefinition(foreignClassName);
pkName = pkName || foreignModel && foreignModel.idName(); pkName = pkName || foreignModel && foreignModel.idName();
if (pkName) { if (pkName) {
pkType = foreignModel.properties[pkName].type; pkType = foreignModel.properties[pkName].type;
} }
var model = this.getModelDefinition(className); const model = this.getModelDefinition(className);
if (model.properties[key]) { if (model.properties[key]) {
if (pkType) { if (pkType) {
// Reset the type of the foreign key // Reset the type of the foreign key
@ -2091,8 +2091,8 @@ DataSource.prototype.defineForeignKey = function defineForeignKey(className, key
return; return;
} }
var fkDef = {type: pkType}; const fkDef = {type: pkType};
var foreignMeta = this.columnMetadata(foreignClassName, pkName); const foreignMeta = this.columnMetadata(foreignClassName, pkName);
if (foreignMeta && (foreignMeta.dataType || foreignMeta.dataLength)) { if (foreignMeta && (foreignMeta.dataType || foreignMeta.dataLength)) {
fkDef[this.connector.name] = {}; fkDef[this.connector.name] = {};
if (foreignMeta.dataType) { if (foreignMeta.dataType) {
@ -2103,7 +2103,7 @@ DataSource.prototype.defineForeignKey = function defineForeignKey(className, key
} }
} }
if (this.connector.defineForeignKey) { if (this.connector.defineForeignKey) {
var cb = function(err, keyType) { const cb = function(err, keyType) {
if (err) throw err; if (err) throw err;
fkDef.type = keyType || pkType; fkDef.type = keyType || pkType;
// Add the foreign key property to the data source _models // 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) { DataSource.prototype.disconnect = function disconnect(cb) {
cb = cb || utils.createPromiseCallback(); cb = cb || utils.createPromiseCallback();
var self = this; const self = this;
if (this.connected && (typeof this.connector.disconnect === 'function')) { if (this.connected && (typeof this.connector.disconnect === 'function')) {
this.connector.disconnect(function(err, result) { this.connector.disconnect(function(err, result) {
self.connected = false; self.connected = false;
@ -2153,10 +2153,10 @@ DataSource.prototype.disconnect = function disconnect(cb) {
* @private * @private
*/ */
DataSource.prototype.copyModel = function copyModel(Master) { DataSource.prototype.copyModel = function copyModel(Master) {
var dataSource = this; const dataSource = this;
var className = Master.modelName; const className = Master.modelName;
var md = Master.modelBuilder.getModelDefinition(className); const md = Master.modelBuilder.getModelDefinition(className);
var Slave = function SlaveModel() { const Slave = function SlaveModel() {
Master.apply(this, [].slice.call(arguments)); Master.apply(this, [].slice.call(arguments));
}; };
@ -2234,10 +2234,10 @@ DataSource.prototype.transaction = function(execute, options, cb) {
options = options || {}; options = options || {};
} }
var dataSource = this; const dataSource = this;
var transaction = new EventEmitter(); const transaction = new EventEmitter();
for (var p in dataSource) { for (const p in dataSource) {
transaction[p] = dataSource[p]; 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. // Create a blank pool for the slave models bound to this transaction.
var modelBuilder = new ModelBuilder(); const modelBuilder = new ModelBuilder();
var slaveModels = modelBuilder.models; const slaveModels = modelBuilder.models;
transaction.modelBuilder = modelBuilder; transaction.modelBuilder = modelBuilder;
transaction.models = slaveModels; transaction.models = slaveModels;
transaction.definitions = modelBuilder.definitions; 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 performance reasons, use a getter per model and only call copyModel()
// for the models that are actually used. These getters are then replaced // for the models that are actually used. These getters are then replaced
// with the actual values on first use. // with the actual values on first use.
var masterModels = dataSource.modelBuilder.models; const masterModels = dataSource.modelBuilder.models;
Object.keys(masterModels).forEach(function(name) { Object.keys(masterModels).forEach(function(name) {
Object.defineProperty(slaveModels, name, { Object.defineProperty(slaveModels, name, {
enumerable: true, enumerable: true,
@ -2275,7 +2275,7 @@ DataSource.prototype.transaction = function(execute, options, cb) {
}); });
}); });
var done = function(err) { let done = function(err) {
if (err) { if (err) {
transaction.rollback(function(error) { transaction.rollback(function(error) {
cb(err || error); cb(err || error);
@ -2292,7 +2292,7 @@ DataSource.prototype.transaction = function(execute, options, cb) {
if (execute) { if (execute) {
cb = cb || utils.createPromiseCallback(); cb = cb || utils.createPromiseCallback();
try { try {
var result = execute(slaveModels, done); const result = execute(slaveModels, done);
if (result && typeof result.then === 'function') { if (result && typeof result.then === 'function') {
result.then(function() { done(); }, done); result.then(function() { done(); }, done);
} }
@ -2347,7 +2347,7 @@ DataSource.prototype.transaction = function(execute, options, cb) {
return transaction; return transaction;
} }
var connector = dataSource.connector; const connector = dataSource.connector;
if (connector.transaction) { if (connector.transaction) {
// Create a transient or memory source transaction. // Create a transient or memory source transaction.
transaction.connector = connector.transaction(); transaction.connector = connector.transaction();
@ -2385,7 +2385,7 @@ DataSource.prototype.transaction = function(execute, options, cb) {
*/ */
DataSource.prototype.enableRemote = function(operation) { DataSource.prototype.enableRemote = function(operation) {
var op = this.getOperation(operation); const op = this.getOperation(operation);
if (op) { if (op) {
op.remoteEnabled = true; op.remoteEnabled = true;
} else { } else {
@ -2414,7 +2414,7 @@ DataSource.prototype.enableRemote = function(operation) {
*/ */
DataSource.prototype.disableRemote = function(operation) { DataSource.prototype.disableRemote = function(operation) {
var op = this.getOperation(operation); const op = this.getOperation(operation);
if (op) { if (op) {
op.remoteEnabled = false; op.remoteEnabled = false;
} else { } else {
@ -2428,11 +2428,11 @@ DataSource.prototype.disableRemote = function(operation) {
*/ */
DataSource.prototype.getOperation = function(operation) { DataSource.prototype.getOperation = function(operation) {
var ops = this.operations(); const ops = this.operations();
var opKeys = Object.keys(ops); const opKeys = Object.keys(ops);
for (var i = 0; i < opKeys.length; i++) { for (let i = 0; i < opKeys.length; i++) {
var op = ops[opKeys[i]]; const op = ops[opKeys[i]];
if (op.name === operation) { if (op.name === operation) {
return op; return op;
@ -2500,7 +2500,7 @@ DataSource.prototype.isRelational = function() {
*/ */
DataSource.prototype.queueInvocation = DataSource.prototype.ready = DataSource.prototype.queueInvocation = DataSource.prototype.ready =
function(obj, args) { function(obj, args) {
var self = this; const self = this;
debug('Datasource %s: connected=%s connecting=%s', this.name, debug('Datasource %s: connected=%s connecting=%s', this.name,
this.connected, this.connecting); this.connected, this.connecting);
if (this.connected) { if (this.connected) {
@ -2508,10 +2508,10 @@ function(obj, args) {
return false; return false;
} }
var method = args.callee; const method = args.callee;
// Set up a callback after the connection is established to continue the method call // 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() { onConnected = function() {
debug('Datasource %s is now connected - executing method %s', self.name, method.name); debug('Datasource %s is now connected - executing method %s', self.name, method.name);
// Remove the error handler // Remove the error handler
@ -2519,12 +2519,12 @@ function(obj, args) {
if (timeoutHandle) { if (timeoutHandle) {
clearTimeout(timeoutHandle); clearTimeout(timeoutHandle);
} }
var params = [].slice.call(args); const params = [].slice.call(args);
try { try {
method.apply(obj, params); method.apply(obj, params);
} catch (err) { } catch (err) {
// Catch the exception and report it via callback // Catch the exception and report it via callback
var cb = params.pop(); const cb = params.pop();
if (typeof cb === 'function') { if (typeof cb === 'function') {
process.nextTick(function() { process.nextTick(function() {
cb(err); cb(err);
@ -2541,8 +2541,8 @@ function(obj, args) {
if (timeoutHandle) { if (timeoutHandle) {
clearTimeout(timeoutHandle); clearTimeout(timeoutHandle);
} }
var params = [].slice.call(args); const params = [].slice.call(args);
var cb = params.pop(); const cb = params.pop();
if (typeof cb === 'function') { if (typeof cb === 'function') {
process.nextTick(function() { process.nextTick(function() {
cb(err); cb(err);
@ -2553,15 +2553,15 @@ function(obj, args) {
this.once('error', onError); this.once('error', onError);
// Set up a timeout to cancel the invocation // Set up a timeout to cancel the invocation
var timeout = this.settings.connectionTimeout || 5000; const timeout = this.settings.connectionTimeout || 5000;
timeoutHandle = setTimeout(function() { timeoutHandle = setTimeout(function() {
debug('Datasource %s fails to connect due to timeout - aborting method %s', debug('Datasource %s fails to connect due to timeout - aborting method %s',
self.name, method.name); self.name, method.name);
self.connecting = false; self.connecting = false;
self.removeListener('error', onError); self.removeListener('error', onError);
self.removeListener('connected', onConnected); self.removeListener('connected', onConnected);
var params = [].slice.call(args); const params = [].slice.call(args);
var cb = params.pop(); const cb = params.pop();
if (typeof cb === 'function') { if (typeof cb === 'function') {
cb(new Error(g.f('Timeout in connecting after %s ms', timeout))); cb(new Error(g.f('Timeout in connecting after %s ms', timeout)));
} }
@ -2580,14 +2580,14 @@ function(obj, args) {
*/ */
DataSource.prototype.ping = function(cb) { DataSource.prototype.ping = function(cb) {
cb = cb || utils.createPromiseCallback(); cb = cb || utils.createPromiseCallback();
var self = this; const self = this;
if (self.connector.ping) { if (self.connector.ping) {
this.connector.ping(cb); this.connector.ping(cb);
} else if (self.connector.discoverModelProperties) { } else if (self.connector.discoverModelProperties) {
self.discoverModelProperties('dummy', {}, cb); self.discoverModelProperties('dummy', {}, cb);
} else { } else {
process.nextTick(function() { 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); cb(err);
}); });
} }

View File

@ -5,7 +5,7 @@
'use strict'; 'use strict';
var inspect = require('util').inspect; const inspect = require('util').inspect;
module.exports = DateString; module.exports = DateString;
@ -60,7 +60,7 @@ function DateString(value) {
Object.defineProperty(this, 'when', { Object.defineProperty(this, 'when', {
get: () => { return this._when; }, get: () => { return this._when; },
set: (val) => { set: (val) => {
var d = new Date(val); const d = new Date(val);
if (isNaN(d.getTime())) { if (isNaN(d.getTime())) {
throw new Error('Invalid date'); throw new Error('Invalid date');
} else { } else {

View File

@ -5,13 +5,17 @@
'use strict'; 'use strict';
var assert = require('assert'); const assert = require('assert');
/*! /*!
* Get a near filter from a given where object. For connector use only. * Get a near filter from a given where object. For connector use only.
*/ */
exports.nearFilter = function nearFilter(where) { exports.nearFilter = function nearFilter(where) {
const nearResults = [];
nearSearch(where);
return (!nearResults.length ? false : nearResults);
function nearSearch(clause, parentKeys) { function nearSearch(clause, parentKeys) {
if (typeof clause !== 'object') { if (typeof clause !== 'object') {
return false; return false;
@ -22,12 +26,12 @@ exports.nearFilter = function nearFilter(where) {
if (typeof clause[clauseKey] !== 'object' || !clause[clauseKey]) return; if (typeof clause[clauseKey] !== 'object' || !clause[clauseKey]) return;
if (Array.isArray(clause[clauseKey])) { if (Array.isArray(clause[clauseKey])) {
clause[clauseKey].forEach(function(el, index) { 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; if (ret) return ret;
}); });
} else { } else {
if (clause[clauseKey].hasOwnProperty('near')) { if (clause[clauseKey].hasOwnProperty('near')) {
var result = clause[clauseKey]; const result = clause[clauseKey];
nearResults.push({ nearResults.push({
near: result.near, near: result.near,
maxDistance: result.maxDistance, maxDistance: result.maxDistance,
@ -41,10 +45,6 @@ exports.nearFilter = function nearFilter(where) {
} }
}); });
} }
var nearResults = [];
nearSearch(where);
return (!nearResults.length ? false : nearResults);
}; };
/*! /*!
@ -68,19 +68,19 @@ exports.nearFilter = function nearFilter(where) {
*/ */
exports.filter = function(rawResults, filters) { exports.filter = function(rawResults, filters) {
var distances = {}; const distances = {};
var results = []; const results = [];
filters.forEach(function(filter) { filters.forEach(function(filter) {
var origin = filter.near; const origin = filter.near;
var max = filter.maxDistance > 0 ? filter.maxDistance : false; const max = filter.maxDistance > 0 ? filter.maxDistance : false;
var min = filter.minDistance > 0 ? filter.minDistance : false; const min = filter.minDistance > 0 ? filter.minDistance : false;
var unit = filter.unit; const unit = filter.unit;
var key = filter.key; const key = filter.key;
// create distance index // create distance index
rawResults.forEach(function(result) { rawResults.forEach(function(result) {
var loc = result[key]; let loc = result[key];
// filter out results without locations // filter out results without locations
if (!loc) return; if (!loc) return;
@ -90,7 +90,7 @@ exports.filter = function(rawResults, filters) {
if (typeof loc.lat !== 'number') return; if (typeof loc.lat !== 'number') return;
if (typeof loc.lng !== '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 // filter result if distance is either < minDistance or > maxDistance
if ((min && d < min) || (max && d > max)) return; if ((min && d < min) || (max && d > max)) return;
@ -100,12 +100,12 @@ exports.filter = function(rawResults, filters) {
}); });
results.sort(function(resA, resB) { results.sort(function(resA, resB) {
var a = resA[key]; const a = resA[key];
var b = resB[key]; const b = resB[key];
if (a && b) { if (a && b) {
var da = distances[resA.id]; const da = distances[resA.id];
var db = distances[resB.id]; const db = distances[resB.id];
if (db === da) return 0; if (db === da) return 0;
return da > db ? 1 : -1; return da > db ? 1 : -1;
@ -231,11 +231,11 @@ GeoPoint.distanceBetween = function distanceBetween(a, b, options) {
b = GeoPoint(b); b = GeoPoint(b);
} }
var x1 = a.lat; const x1 = a.lat;
var y1 = a.lng; const y1 = a.lng;
var x2 = b.lat; const x2 = b.lat;
var y2 = b.lng; const y2 = b.lng;
return geoDistance(x1, y1, x2, y2, options); return geoDistance(x1, y1, x2, y2, options);
}; };
@ -283,13 +283,13 @@ GeoPoint.prototype.toString = function() {
*/ */
// factor to convert degrees to radians // factor to convert degrees to radians
var DEG2RAD = 0.01745329252; const DEG2RAD = 0.01745329252;
// factor to convert radians degrees to degrees // factor to convert radians degrees to degrees
var RAD2DEG = 57.29577951308; const RAD2DEG = 57.29577951308;
// radius of the earth // radius of the earth
var EARTH_RADIUS = { const EARTH_RADIUS = {
kilometers: 6370.99056, kilometers: 6370.99056,
meters: 6370990.56, meters: 6370990.56,
miles: 3958.75, miles: 3958.75,
@ -299,7 +299,7 @@ var EARTH_RADIUS = {
}; };
function geoDistance(x1, y1, x2, y2, options) { function geoDistance(x1, y1, x2, y2, options) {
var type = (options && options.type) || 'miles'; const type = (options && options.type) || 'miles';
// Convert to radians // Convert to radians
x1 = x1 * DEG2RAD; 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. // use the haversine formula to calculate distance for any 2 points on a sphere.
// ref http://en.wikipedia.org/wiki/Haversine_formula // 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); 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]; return 2 * Math.asin(f) * EARTH_RADIUS[type];
} }

View File

@ -5,8 +5,8 @@
'use strict'; 'use strict';
var deprecated = require('depd')('loopback-datasource-juggler'); const deprecated = require('depd')('loopback-datasource-juggler');
var g = require('strong-globalize')(); const g = require('strong-globalize')();
/*! /*!
* Module exports * Module exports
@ -48,16 +48,16 @@ Hookable.afterDestroy = null;
* @param {Function} callback * @param {Function} callback
*/ */
Hookable.prototype.trigger = function trigger(actionName, work, data, callback) { Hookable.prototype.trigger = function trigger(actionName, work, data, callback) {
var capitalizedName = capitalize(actionName); const capitalizedName = capitalize(actionName);
var beforeHook = this.constructor['before' + capitalizedName] || let beforeHook = this.constructor['before' + capitalizedName] ||
this.constructor['pre' + capitalizedName]; this.constructor['pre' + capitalizedName];
var afterHook = this.constructor['after' + capitalizedName] || let afterHook = this.constructor['after' + capitalizedName] ||
this.constructor['post' + capitalizedName]; this.constructor['post' + capitalizedName];
if (actionName === 'validate') { if (actionName === 'validate') {
beforeHook = beforeHook || this.constructor.beforeValidation; beforeHook = beforeHook || this.constructor.beforeValidation;
afterHook = afterHook || this.constructor.afterValidation; afterHook = afterHook || this.constructor.afterValidation;
} }
var inst = this; const inst = this;
if (actionName !== 'initialize') { if (actionName !== 'initialize') {
if (beforeHook) if (beforeHook)
@ -100,11 +100,11 @@ function capitalize(string) {
} }
function deprecateHook(ctor, prefixes, capitalizedName) { 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') if (capitalizedName === 'Validate')
candidateNames.push(prefixes[0] + 'Validation'); 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 (!hookName) return; // just to be sure, this should never happen
if (ctor.modelName) hookName = ctor.modelName + '.' + hookName; if (ctor.modelName) hookName = ctor.modelName + '.' + hookName;
deprecated(g.f('Model hook "%s" is deprecated, ' + deprecated(g.f('Model hook "%s" is deprecated, ' +

View File

@ -5,16 +5,16 @@
'use strict'; 'use strict';
var async = require('async'); const async = require('async');
var g = require('strong-globalize')(); const g = require('strong-globalize')();
var utils = require('./utils'); const utils = require('./utils');
var List = require('./list'); const List = require('./list');
var includeUtils = require('./include_utils'); const includeUtils = require('./include_utils');
var isPlainObject = utils.isPlainObject; const isPlainObject = utils.isPlainObject;
var defineCachedRelations = utils.defineCachedRelations; const defineCachedRelations = utils.defineCachedRelations;
var uniq = utils.uniq; const uniq = utils.uniq;
var idName = utils.idName; const idName = utils.idName;
var debug = require('debug')('loopback:include'); const debug = require('debug')('loopback:include');
/*! /*!
* Normalize the include to be an array * Normalize the include to be an array
@ -22,19 +22,19 @@ var debug = require('debug')('loopback:include');
* @returns {*} * @returns {*}
*/ */
function normalizeInclude(include) { function normalizeInclude(include) {
var newInclude; let newInclude;
if (typeof include === 'string') { if (typeof include === 'string') {
return [include]; return [include];
} else if (isPlainObject(include)) { } else if (isPlainObject(include)) {
// Build an array of key/value pairs // Build an array of key/value pairs
newInclude = []; newInclude = [];
var rel = include.rel || include.relation; const rel = include.rel || include.relation;
var obj = {}; const obj = {};
if (typeof rel === 'string') { if (typeof rel === 'string') {
obj[rel] = new IncludeScope(include.scope); obj[rel] = new IncludeScope(include.scope);
newInclude.push(obj); newInclude.push(obj);
} else { } else {
for (var key in include) { for (const key in include) {
obj[key] = include[key]; obj[key] = include[key];
newInclude.push(obj); newInclude.push(obj);
} }
@ -42,8 +42,8 @@ function normalizeInclude(include) {
return newInclude; return newInclude;
} else if (Array.isArray(include)) { } else if (Array.isArray(include)) {
newInclude = []; newInclude = [];
for (var i = 0, n = include.length; i < n; i++) { for (let i = 0, n = include.length; i < n; i++) {
var subIncludes = normalizeInclude(include[i]); const subIncludes = normalizeInclude(include[i]);
newInclude = newInclude.concat(subIncludes); newInclude = newInclude.concat(subIncludes);
} }
return newInclude; return newInclude;
@ -80,8 +80,8 @@ function lookupModel(models, modelName) {
if (models[modelName]) { if (models[modelName]) {
return models[modelName]; return models[modelName];
} }
var lookupClassName = modelName.toLowerCase(); const lookupClassName = modelName.toLowerCase();
for (var name in models) { for (const name in models) {
if (name.toLowerCase() === lookupClassName) { if (name.toLowerCase() === lookupClassName) {
return models[name]; return models[name];
} }
@ -161,7 +161,7 @@ Inclusion.include = function(objects, include, options, cb) {
cb = options; cb = options;
options = {}; options = {};
} }
var self = this; const self = this;
if (!include || (Array.isArray(include) && include.length === 0) || if (!include || (Array.isArray(include) && include.length === 0) ||
(Array.isArray(objects) && objects.length === 0) || (Array.isArray(objects) && objects.length === 0) ||
@ -176,7 +176,7 @@ Inclusion.include = function(objects, include, options, cb) {
debug('include: %j', include); debug('include: %j', include);
// Find the limit of items for `inq` // Find the limit of items for `inq`
var inqLimit = 256; let inqLimit = 256;
if (self.dataSource && self.dataSource.settings && if (self.dataSource && self.dataSource.settings &&
self.dataSource.settings.inqLimit) { self.dataSource.settings.inqLimit) {
inqLimit = self.dataSource.settings.inqLimit; inqLimit = self.dataSource.settings.inqLimit;
@ -212,13 +212,13 @@ Inclusion.include = function(objects, include, options, cb) {
return cb(e); return cb(e);
} }
var foreignKeys = []; let foreignKeys = [];
if (filter.where[fkName]) { if (filter.where[fkName]) {
foreignKeys = filter.where[fkName].inq; foreignKeys = filter.where[fkName].inq;
} else if (filter.where.and) { } else if (filter.where.and) {
// The inq can be embedded inside 'and: []'. No or: [] is needed as // 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. // 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] && if (filter.where.and[j][fkName] &&
Array.isArray(filter.where.and[j][fkName].inq)) { Array.isArray(filter.where.and[j][fkName].inq)) {
foreignKeys = 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 // Force the find to be performed per FK to honor the pagination
pageSize = 1; pageSize = 1;
} }
var size = foreignKeys.length; const size = foreignKeys.length;
if (size > inqLimit && pageSize <= 0) { if (size > inqLimit && pageSize <= 0) {
pageSize = inqLimit; pageSize = inqLimit;
} }
@ -241,29 +241,29 @@ Inclusion.include = function(objects, include, options, cb) {
return model.find(filter, options, cb); return model.find(filter, options, cb);
} }
var listOfFKs = []; let listOfFKs = [];
for (var i = 0; i < size; i += pageSize) { for (let i = 0; i < size; i += pageSize) {
var end = i + pageSize; let end = i + pageSize;
if (end > size) { if (end > size) {
end = size; end = size;
} }
listOfFKs.push(foreignKeys.slice(i, end)); listOfFKs.push(foreignKeys.slice(i, end));
} }
var items = []; let items = [];
// Optimization: no need to resolve keys that are an empty array // Optimization: no need to resolve keys that are an empty array
listOfFKs = listOfFKs.filter(function(keys) { listOfFKs = listOfFKs.filter(function(keys) {
return keys.length > 0; return keys.length > 0;
}); });
async.each(listOfFKs, function(foreignKeys, done) { async.each(listOfFKs, function(foreignKeys, done) {
var newFilter = {}; const newFilter = {};
for (var f in filter) { for (const f in filter) {
newFilter[f] = filter[f]; newFilter[f] = filter[f];
} }
if (filter.where) { if (filter.where) {
newFilter.where = {}; newFilter.where = {};
for (var w in filter.where) { for (const w in filter.where) {
newFilter.where[w] = filter.where[w]; newFilter.where[w] = filter.where[w];
} }
} }
@ -282,10 +282,10 @@ Inclusion.include = function(objects, include, options, cb) {
} }
function processIncludeItem(objs, include, options, cb) { function processIncludeItem(objs, include, options, cb) {
var relations = self.relations; const relations = self.relations;
var relationName; let relationName;
var subInclude = null, scope = null; let subInclude = null, scope = null;
if (isPlainObject(include)) { if (isPlainObject(include)) {
relationName = Object.keys(include)[0]; relationName = Object.keys(include)[0];
@ -304,13 +304,13 @@ Inclusion.include = function(objects, include, options, cb) {
subInclude = null; subInclude = null;
} }
var relation = relations[relationName]; const relation = relations[relationName];
if (!relation) { if (!relation) {
cb(new Error(g.f('Relation "%s" is not defined for %s model', relationName, self.modelName))); cb(new Error(g.f('Relation "%s" is not defined for %s model', relationName, self.modelName)));
return; return;
} }
debug('Relation: %j', relation); debug('Relation: %j', relation);
var polymorphic = relation.polymorphic; const polymorphic = relation.polymorphic;
// if (polymorphic && !polymorphic.discriminator) { // if (polymorphic && !polymorphic.discriminator) {
// cb(new Error('Relation "' + relationName + '" is polymorphic but ' + // cb(new Error('Relation "' + relationName + '" is polymorphic but ' +
// 'discriminator is not present')); // 'discriminator is not present'));
@ -330,15 +330,15 @@ Inclusion.include = function(objects, include, options, cb) {
return cb(); return cb();
} }
// prepare filter and fields for making DB Call // 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) { if ((relation.multiple || relation.type === 'belongsTo') && scope) {
var includeScope = {}; const includeScope = {};
// make sure not to miss any fields for sub includes // make sure not to miss any fields for sub includes
if (filter.fields && Array.isArray(subInclude) && if (filter.fields && Array.isArray(subInclude) &&
relation.modelTo.relations) { relation.modelTo.relations) {
includeScope.fields = []; includeScope.fields = [];
subInclude.forEach(function(name) { subInclude.forEach(function(name) {
var rel = relation.modelTo.relations[name]; const rel = relation.modelTo.relations[name];
if (rel && rel.type === 'belongsTo') { if (rel && rel.type === 'belongsTo') {
includeScope.fields.push(rel.keyFrom); includeScope.fields.push(rel.keyFrom);
} }
@ -349,7 +349,7 @@ Inclusion.include = function(objects, include, options, cb) {
// Let's add a placeholder where query // Let's add a placeholder where query
filter.where = filter.where || {}; filter.where = filter.where || {};
// if fields are specified, make sure target foreign key is present // if fields are specified, make sure target foreign key is present
var fields = filter.fields; let fields = filter.fields;
if (typeof fields === 'string') { if (typeof fields === 'string') {
// transform string into array containing this string // transform string into array containing this string
filter.fields = fields = [fields]; filter.fields = fields = [fields];
@ -405,14 +405,14 @@ Inclusion.include = function(objects, include, options, cb) {
* @param callback * @param callback
*/ */
function includeHasManyThrough(callback) { function includeHasManyThrough(callback) {
var sourceIds = []; const sourceIds = [];
// Map for Indexing objects by their id for faster retrieval // Map for Indexing objects by their id for faster retrieval
var objIdMap = {}; const objIdMap = {};
for (var i = 0; i < objs.length; i++) { for (let i = 0; i < objs.length; i++) {
var obj = objs[i]; const obj = objs[i];
// one-to-many: foreign key reference is modelTo -> modelFrom. // one-to-many: foreign key reference is modelTo -> modelFrom.
// use modelFrom.keyFrom in where filter later // use modelFrom.keyFrom in where filter later
var sourceId = obj[relation.keyFrom]; const sourceId = obj[relation.keyFrom];
if (sourceId) { if (sourceId) {
sourceIds.push(sourceId); sourceIds.push(sourceId);
objIdMap[sourceId.toString()] = obj; 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 // default filters are not applicable on through model. should be applied
// on modelTo later in 2nd DB call. // on modelTo later in 2nd DB call.
var throughFilter = { const throughFilter = {
where: {}, where: {},
}; };
throughFilter.where[relation.keyTo] = { throughFilter.where[relation.keyTo] = {
@ -451,25 +451,25 @@ Inclusion.include = function(objects, include, options, cb) {
return callback(err); return callback(err);
} }
// start preparing for 2nd DB call. // start preparing for 2nd DB call.
var targetIds = []; const targetIds = [];
var targetObjsMap = {}; const targetObjsMap = {};
for (var i = 0; i < throughObjs.length; i++) { for (let i = 0; i < throughObjs.length; i++) {
var throughObj = throughObjs[i]; const throughObj = throughObjs[i];
var targetId = throughObj[relation.keyThrough]; const targetId = throughObj[relation.keyThrough];
if (targetId) { if (targetId) {
// save targetIds for 2nd DB Call // save targetIds for 2nd DB Call
targetIds.push(targetId); targetIds.push(targetId);
var sourceObj = objIdMap[throughObj[relation.keyTo]]; const sourceObj = objIdMap[throughObj[relation.keyTo]];
var targetIdStr = targetId.toString(); const targetIdStr = targetId.toString();
// Since targetId can be duplicates, multiple source objs are put // Since targetId can be duplicates, multiple source objs are put
// into buckets. // into buckets.
var objList = targetObjsMap[targetIdStr] = const objList = targetObjsMap[targetIdStr] =
targetObjsMap[targetIdStr] || []; targetObjsMap[targetIdStr] || [];
objList.push(sourceObj); objList.push(sourceObj);
} }
} }
// Polymorphic relation does not have idKey of modelTo. Find it manually // Polymorphic relation does not have idKey of modelTo. Find it manually
var modelToIdName = idName(relation.modelTo); const modelToIdName = idName(relation.modelTo);
filter.where[modelToIdName] = { filter.where[modelToIdName] = {
inq: uniq(targetIds), inq: uniq(targetIds),
}; };
@ -490,7 +490,7 @@ Inclusion.include = function(objects, include, options, cb) {
if (err) { if (err) {
return callback(err); return callback(err);
} }
var tasks = []; const tasks = [];
// simultaneously process subIncludes. Call it first as it is an async // simultaneously process subIncludes. Call it first as it is an async
// process. // process.
if (subInclude && targets) { if (subInclude && targets) {
@ -503,13 +503,15 @@ Inclusion.include = function(objects, include, options, cb) {
function targetLinkingTask(next) { function targetLinkingTask(next) {
async.each(targets, linkManyToMany, next); async.each(targets, linkManyToMany, next);
function linkManyToMany(target, next) { function linkManyToMany(target, next) {
var targetId = target[modelToIdName]; const targetId = target[modelToIdName];
if (!targetId) { if (!targetId) {
var err = new Error(g.f('LinkManyToMany received target that doesn\'t contain required "%s"', const err = new Error(g.f(
modelToIdName)); 'LinkManyToMany received target that doesn\'t contain required "%s"',
modelToIdName
));
return next(err); return next(err);
} }
var objList = targetObjsMap[targetId.toString()]; const objList = targetObjsMap[targetId.toString()];
async.each(objList, function(obj, next) { async.each(objList, function(obj, next) {
if (!obj) return next(); if (!obj) return next();
obj.__cachedRelations[relationName].push(target); obj.__cachedRelations[relationName].push(target);
@ -528,15 +530,15 @@ Inclusion.include = function(objects, include, options, cb) {
* @param callback * @param callback
*/ */
function includeReferencesMany(callback) { function includeReferencesMany(callback) {
var modelToIdName = idName(relation.modelTo); const modelToIdName = idName(relation.modelTo);
var allTargetIds = []; let allTargetIds = [];
// Map for Indexing objects by their id for faster retrieval // Map for Indexing objects by their id for faster retrieval
var targetObjsMap = {}; const targetObjsMap = {};
for (var i = 0; i < objs.length; i++) { for (let i = 0; i < objs.length; i++) {
var obj = objs[i]; const obj = objs[i];
// one-to-many: foreign key reference is modelTo -> modelFrom. // one-to-many: foreign key reference is modelTo -> modelFrom.
// use modelFrom.keyFrom in where filter later // use modelFrom.keyFrom in where filter later
var targetIds = obj[relation.keyFrom]; let targetIds = obj[relation.keyFrom];
if (targetIds) { if (targetIds) {
if (typeof targetIds === 'string') { if (typeof targetIds === 'string') {
// For relational DBs, the array is stored as stringified json // For relational DBs, the array is stored as stringified json
@ -546,10 +548,10 @@ Inclusion.include = function(objects, include, options, cb) {
// referencesMany has multiple targetIds per obj. We need to concat // referencesMany has multiple targetIds per obj. We need to concat
// them into allTargetIds before DB Call // them into allTargetIds before DB Call
allTargetIds = allTargetIds.concat(targetIds); allTargetIds = allTargetIds.concat(targetIds);
for (var j = 0; j < targetIds.length; j++) { for (let j = 0; j < targetIds.length; j++) {
var targetId = targetIds[j]; const targetId = targetIds[j];
var targetIdStr = targetId.toString(); const targetIdStr = targetId.toString();
var objList = targetObjsMap[targetIdStr] = const objList = targetObjsMap[targetIdStr] =
targetObjsMap[targetIdStr] || []; targetObjsMap[targetIdStr] || [];
objList.push(obj); objList.push(obj);
} }
@ -577,7 +579,7 @@ Inclusion.include = function(objects, include, options, cb) {
if (err) { if (err) {
return callback(err); return callback(err);
} }
var tasks = []; const tasks = [];
// simultaneously process subIncludes // simultaneously process subIncludes
if (subInclude && targets) { if (subInclude && targets) {
tasks.push(function subIncludesTask(next) { tasks.push(function subIncludesTask(next) {
@ -590,7 +592,7 @@ Inclusion.include = function(objects, include, options, cb) {
function targetLinkingTask(next) { function targetLinkingTask(next) {
async.each(targets, linkManyToMany, next); async.each(targets, linkManyToMany, next);
function linkManyToMany(target, 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) { async.each(objList, function(obj, next) {
if (!obj) return next(); if (!obj) return next();
obj.__cachedRelations[relationName].push(target); obj.__cachedRelations[relationName].push(target);
@ -609,7 +611,7 @@ Inclusion.include = function(objects, include, options, cb) {
*/ */
function includeHasManySimple(callback) { function includeHasManySimple(callback) {
// Map for Indexing objects by their id for faster retrieval // 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] = { filter.where[relation.keyTo] = {
inq: uniq(objIdMap2.getKeys()), inq: uniq(objIdMap2.getKeys()),
@ -624,7 +626,7 @@ Inclusion.include = function(objects, include, options, cb) {
if (err) { if (err) {
return callback(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) { includeUtils.join(objIdMap2, targetsIdMap, function(obj1, valueToMergeIn) {
defineCachedRelations(obj1); defineCachedRelations(obj1);
obj1.__cachedRelations[relationName] = valueToMergeIn; obj1.__cachedRelations[relationName] = valueToMergeIn;
@ -639,14 +641,14 @@ Inclusion.include = function(objects, include, options, cb) {
* @param callback * @param callback
*/ */
function includeHasMany(callback) { function includeHasMany(callback) {
var sourceIds = []; const sourceIds = [];
// Map for Indexing objects by their id for faster retrieval // Map for Indexing objects by their id for faster retrieval
var objIdMap = {}; const objIdMap = {};
for (var i = 0; i < objs.length; i++) { for (let i = 0; i < objs.length; i++) {
var obj = objs[i]; const obj = objs[i];
// one-to-many: foreign key reference is modelTo -> modelFrom. // one-to-many: foreign key reference is modelTo -> modelFrom.
// use modelFrom.keyFrom in where filter later // use modelFrom.keyFrom in where filter later
var sourceId = obj[relation.keyFrom]; const sourceId = obj[relation.keyFrom];
if (sourceId) { if (sourceId) {
sourceIds.push(sourceId); sourceIds.push(sourceId);
objIdMap[sourceId.toString()] = obj; objIdMap[sourceId.toString()] = obj;
@ -674,7 +676,7 @@ Inclusion.include = function(objects, include, options, cb) {
if (err) { if (err) {
return callback(err); return callback(err);
} }
var tasks = []; const tasks = [];
// simultaneously process subIncludes // simultaneously process subIncludes
if (subInclude && targets) { if (subInclude && targets) {
tasks.push(function subIncludesTask(next) { tasks.push(function subIncludesTask(next) {
@ -693,9 +695,9 @@ Inclusion.include = function(objects, include, options, cb) {
async.each(targets, linkManyToOne, next); async.each(targets, linkManyToOne, next);
function linkManyToOne(target, next) { function linkManyToOne(target, next) {
// fix for bug in hasMany with referencesMany // 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) { async.each(targetIds, function(targetId, next) {
var obj = objIdMap[targetId.toString()]; const obj = objIdMap[targetId.toString()];
if (!obj) return next(); if (!obj) return next();
obj.__cachedRelations[relationName].push(target); obj.__cachedRelations[relationName].push(target);
processTargetObj(obj, next); processTargetObj(obj, next);
@ -704,7 +706,7 @@ Inclusion.include = function(objects, include, options, cb) {
return next(err); return next(err);
} }
var objsWithEmptyRelation = objs.filter(function(obj) { const objsWithEmptyRelation = objs.filter(function(obj) {
return obj.__cachedRelations[relationName].length === 0; return obj.__cachedRelations[relationName].length === 0;
}); });
async.each(objsWithEmptyRelation, function(obj, next) { async.each(objsWithEmptyRelation, function(obj, next) {
@ -725,22 +727,22 @@ Inclusion.include = function(objects, include, options, cb) {
* @param callback * @param callback
*/ */
function includePolymorphicBelongsTo(callback) { function includePolymorphicBelongsTo(callback) {
var targetIdsByType = {}; const targetIdsByType = {};
// Map for Indexing objects by their type and targetId for faster retrieval // Map for Indexing objects by their type and targetId for faster retrieval
var targetObjMapByType = {}; const targetObjMapByType = {};
for (var i = 0; i < objs.length; i++) { for (let i = 0; i < objs.length; i++) {
var obj = objs[i]; const obj = objs[i];
var discriminator = polymorphic.discriminator; const discriminator = polymorphic.discriminator;
var modelType = obj[discriminator]; const modelType = obj[discriminator];
if (modelType) { if (modelType) {
targetIdsByType[modelType] = targetIdsByType[modelType] || []; targetIdsByType[modelType] = targetIdsByType[modelType] || [];
targetObjMapByType[modelType] = targetObjMapByType[modelType] || {}; targetObjMapByType[modelType] = targetObjMapByType[modelType] || {};
var targetIds = targetIdsByType[modelType]; const targetIds = targetIdsByType[modelType];
var targetObjsMap = targetObjMapByType[modelType]; const targetObjsMap = targetObjMapByType[modelType];
var targetId = obj[relation.keyFrom]; const targetId = obj[relation.keyFrom];
if (targetId) { if (targetId) {
targetIds.push(targetId); targetIds.push(targetId);
var targetIdStr = targetId.toString(); const targetIdStr = targetId.toString();
targetObjsMap[targetIdStr] = targetObjsMap[targetIdStr] || []; targetObjsMap[targetIdStr] = targetObjsMap[targetIdStr] || [];
// Is belongsTo. Multiple objects can have the same // Is belongsTo. Multiple objects can have the same
// targetId and therefore map value is an array // targetId and therefore map value is an array
@ -758,13 +760,13 @@ Inclusion.include = function(objects, include, options, cb) {
* @param callback * @param callback
*/ */
function processPolymorphicType(modelType, callback) { function processPolymorphicType(modelType, callback) {
var typeFilter = {where: {}}; const typeFilter = {where: {}};
utils.mergeQuery(typeFilter, filter); utils.mergeQuery(typeFilter, filter);
var targetIds = targetIdsByType[modelType]; const targetIds = targetIdsByType[modelType];
typeFilter.where[relation.keyTo] = { typeFilter.where[relation.keyTo] = {
inq: uniq(targetIds), inq: uniq(targetIds),
}; };
var Model = lookupModel(relation.modelFrom.dataSource.modelBuilder. const Model = lookupModel(relation.modelFrom.dataSource.modelBuilder.
models, modelType); models, modelType);
if (!Model) { if (!Model) {
callback(new Error(g.f('Discriminator type %s specified but no model exists with such name', callback(new Error(g.f('Discriminator type %s specified but no model exists with such name',
@ -786,7 +788,7 @@ Inclusion.include = function(objects, include, options, cb) {
if (err) { if (err) {
return callback(err); return callback(err);
} }
var tasks = []; const tasks = [];
// simultaneously process subIncludes // simultaneously process subIncludes
if (subInclude && targets) { if (subInclude && targets) {
@ -797,10 +799,10 @@ Inclusion.include = function(objects, include, options, cb) {
// process each target object // process each target object
tasks.push(targetLinkingTask); tasks.push(targetLinkingTask);
function targetLinkingTask(next) { function targetLinkingTask(next) {
var targetObjsMap = targetObjMapByType[modelType]; const targetObjsMap = targetObjMapByType[modelType];
async.each(targets, linkOneToMany, next); async.each(targets, linkOneToMany, next);
function linkOneToMany(target, 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) { async.each(objList, function(obj, next) {
if (!obj) return next(); if (!obj) return next();
obj.__cachedRelations[relationName] = target; obj.__cachedRelations[relationName] = target;
@ -819,14 +821,14 @@ Inclusion.include = function(objects, include, options, cb) {
* @param callback * @param callback
*/ */
function includePolymorphicHasOne(callback) { function includePolymorphicHasOne(callback) {
var sourceIds = []; const sourceIds = [];
// Map for Indexing objects by their id for faster retrieval // Map for Indexing objects by their id for faster retrieval
var objIdMap = {}; const objIdMap = {};
for (var i = 0; i < objs.length; i++) { for (let i = 0; i < objs.length; i++) {
var obj = objs[i]; const obj = objs[i];
// one-to-one: foreign key reference is modelTo -> modelFrom. // one-to-one: foreign key reference is modelTo -> modelFrom.
// use modelFrom.keyFrom in where filter later // use modelFrom.keyFrom in where filter later
var sourceId = obj[relation.keyFrom]; const sourceId = obj[relation.keyFrom];
if (sourceId) { if (sourceId) {
sourceIds.push(sourceId); sourceIds.push(sourceId);
objIdMap[sourceId.toString()] = obj; objIdMap[sourceId.toString()] = obj;
@ -853,7 +855,7 @@ Inclusion.include = function(objects, include, options, cb) {
if (err) { if (err) {
return callback(err); return callback(err);
} }
var tasks = []; const tasks = [];
// simultaneously process subIncludes // simultaneously process subIncludes
if (subInclude && targets) { if (subInclude && targets) {
tasks.push(function subIncludesTask(next) { tasks.push(function subIncludesTask(next) {
@ -865,9 +867,9 @@ Inclusion.include = function(objects, include, options, cb) {
function targetLinkingTask(next) { function targetLinkingTask(next) {
async.each(targets, linkOneToOne, next); async.each(targets, linkOneToOne, next);
function linkOneToOne(target, next) { function linkOneToOne(target, next) {
var sourceId = target[relation.keyTo]; const sourceId = target[relation.keyTo];
if (!sourceId) return next(); if (!sourceId) return next();
var obj = objIdMap[sourceId.toString()]; const obj = objIdMap[sourceId.toString()];
if (!obj) return next(); if (!obj) return next();
obj.__cachedRelations[relationName] = target; obj.__cachedRelations[relationName] = target;
processTargetObj(obj, next); processTargetObj(obj, next);
@ -883,10 +885,10 @@ Inclusion.include = function(objects, include, options, cb) {
* @param callback * @param callback
*/ */
function includeOneToOne(callback) { function includeOneToOne(callback) {
var targetIds = []; const targetIds = [];
var objTargetIdMap = {}; const objTargetIdMap = {};
for (var i = 0; i < objs.length; i++) { for (let i = 0; i < objs.length; i++) {
var obj = objs[i]; const obj = objs[i];
if (relation.type === 'belongsTo') { if (relation.type === 'belongsTo') {
if (obj[relation.keyFrom] == null) { if (obj[relation.keyFrom] == null) {
defineCachedRelations(obj); defineCachedRelations(obj);
@ -895,10 +897,10 @@ Inclusion.include = function(objects, include, options, cb) {
continue; continue;
} }
} }
var targetId = obj[relation.keyFrom]; const targetId = obj[relation.keyFrom];
if (targetId) { if (targetId) {
targetIds.push(targetId); targetIds.push(targetId);
var targetIdStr = targetId.toString(); const targetIdStr = targetId.toString();
objTargetIdMap[targetIdStr] = objTargetIdMap[targetIdStr] || []; objTargetIdMap[targetIdStr] = objTargetIdMap[targetIdStr] || [];
objTargetIdMap[targetIdStr].push(obj); objTargetIdMap[targetIdStr].push(obj);
} else { } else {
@ -925,7 +927,7 @@ Inclusion.include = function(objects, include, options, cb) {
if (err) { if (err) {
return callback(err); return callback(err);
} }
var tasks = []; const tasks = [];
// simultaneously process subIncludes // simultaneously process subIncludes
if (subInclude && targets) { if (subInclude && targets) {
tasks.push(function subIncludesTask(next) { tasks.push(function subIncludesTask(next) {
@ -937,8 +939,8 @@ Inclusion.include = function(objects, include, options, cb) {
function targetLinkingTask(next) { function targetLinkingTask(next) {
async.each(targets, linkOneToMany, next); async.each(targets, linkOneToMany, next);
function linkOneToMany(target, next) { function linkOneToMany(target, next) {
var targetId = target[relation.keyTo]; const targetId = target[relation.keyTo];
var objList = objTargetIdMap[targetId.toString()]; const objList = objTargetIdMap[targetId.toString()];
async.each(objList, function(obj, next) { async.each(objList, function(obj, next) {
if (!obj) return next(); if (!obj) return next();
obj.__cachedRelations[relationName] = target; obj.__cachedRelations[relationName] = target;
@ -973,7 +975,7 @@ Inclusion.include = function(objects, include, options, cb) {
* @returns {*} * @returns {*}
*/ */
function processTargetObj(obj, callback) { function processTargetObj(obj, callback) {
var isInst = obj instanceof self; const isInst = obj instanceof self;
// Calling the relation method on the instance // Calling the relation method on the instance
if (relation.type === 'belongsTo') { if (relation.type === 'belongsTo') {
@ -1015,21 +1017,21 @@ Inclusion.include = function(objects, include, options, cb) {
callback); 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 // If related objects are not cached by include Handlers, directly call
// related accessor function even though it is not very efficient // 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) { if ((relation.multiple || relation.type === 'belongsTo') && scope) {
var includeScope = {}; const includeScope = {};
var filter = scope.conditions(); const filter = scope.conditions();
// make sure not to miss any fields for sub includes // make sure not to miss any fields for sub includes
if (filter.fields && Array.isArray(subInclude) && relation.modelTo.relations) { if (filter.fields && Array.isArray(subInclude) && relation.modelTo.relations) {
includeScope.fields = []; includeScope.fields = [];
subInclude.forEach(function(name) { subInclude.forEach(function(name) {
var rel = relation.modelTo.relations[name]; const rel = relation.modelTo.relations[name];
if (rel && rel.type === 'belongsTo') { if (rel && rel.type === 'belongsTo') {
includeScope.fields.push(rel.keyFrom); includeScope.fields.push(rel.keyFrom);
} }

View File

@ -5,7 +5,7 @@
'use strict'; 'use strict';
var g = require('strong-globalize')(); const g = require('strong-globalize')();
module.exports.buildOneToOneIdentityMapWithOrigKeys = buildOneToOneIdentityMapWithOrigKeys; module.exports.buildOneToOneIdentityMapWithOrigKeys = buildOneToOneIdentityMapWithOrigKeys;
module.exports.buildOneToManyIdentityMapWithOrigKeys = buildOneToManyIdentityMapWithOrigKeys; module.exports.buildOneToManyIdentityMapWithOrigKeys = buildOneToManyIdentityMapWithOrigKeys;
@ -15,7 +15,7 @@ module.exports.KVMap = KVMap;
const util = require('util'); const util = require('util');
function getId(obj, idName) { function getId(obj, idName) {
var id = obj && obj[idName]; const id = obj && obj[idName];
if (id == null) { if (id == null) {
const msg = g.f('ID property "%s" is missing for included item: %j. ' + 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`', '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 * @returns {} object where keys are ids and values are objects itself
*/ */
function buildOneToOneIdentityMapWithOrigKeys(objs, idName) { function buildOneToOneIdentityMapWithOrigKeys(objs, idName) {
var kvMap = new KVMap(); const kvMap = new KVMap();
for (var i = 0; i < objs.length; i++) { for (let i = 0; i < objs.length; i++) {
var obj = objs[i]; const obj = objs[i];
var id = getId(obj, idName); const id = getId(obj, idName);
kvMap.set(id, obj); kvMap.set(id, obj);
} }
return kvMap; return kvMap;
} }
function buildOneToManyIdentityMapWithOrigKeys(objs, idName) { function buildOneToManyIdentityMapWithOrigKeys(objs, idName) {
var kvMap = new KVMap(); const kvMap = new KVMap();
for (var i = 0; i < objs.length; i++) { for (let i = 0; i < objs.length; i++) {
var obj = objs[i]; const obj = objs[i];
var id = getId(obj, idName); const id = getId(obj, idName);
var value = kvMap.get(id) || []; const value = kvMap.get(id) || [];
value.push(obj); value.push(obj);
kvMap.set(id, value); kvMap.set(id, value);
} }
@ -64,11 +64,11 @@ function buildOneToManyIdentityMapWithOrigKeys(objs, idName) {
* @param mergeF function(obj, objectsToMergeIn) * @param mergeF function(obj, objectsToMergeIn)
*/ */
function join(oneToOneIdMap, oneToManyIdMap, mergeF) { function join(oneToOneIdMap, oneToManyIdMap, mergeF) {
var ids = oneToOneIdMap.getKeys(); const ids = oneToOneIdMap.getKeys();
for (var i = 0; i < ids.length; i++) { for (let i = 0; i < ids.length; i++) {
var id = ids[i]; const id = ids[i];
var obj = oneToOneIdMap.get(id); const obj = oneToOneIdMap.get(id);
var objectsToMergeIn = oneToManyIdMap.get(id) || []; const objectsToMergeIn = oneToManyIdMap.get(id) || [];
mergeF(obj, objectsToMergeIn); mergeF(obj, objectsToMergeIn);
} }
} }
@ -79,20 +79,20 @@ function join(oneToOneIdMap, oneToManyIdMap, mergeF) {
* @constructor * @constructor
*/ */
function KVMap() { function KVMap() {
var _originalKeyFieldName = 'originalKey'; const _originalKeyFieldName = 'originalKey';
var _valueKeyFieldName = 'value'; const _valueKeyFieldName = 'value';
var _dict = {}; const _dict = {};
var keyToString = function(key) { return key.toString(); }; const keyToString = function(key) { return key.toString(); };
var mapImpl = { const mapImpl = {
set: function(key, value) { set: function(key, value) {
var recordObj = {}; const recordObj = {};
recordObj[_originalKeyFieldName] = key; recordObj[_originalKeyFieldName] = key;
recordObj[_valueKeyFieldName] = value; recordObj[_valueKeyFieldName] = value;
_dict[keyToString(key)] = recordObj; _dict[keyToString(key)] = recordObj;
return true; return true;
}, },
get: function(key) { get: function(key) {
var storeObj = _dict[keyToString(key)]; const storeObj = _dict[keyToString(key)];
if (storeObj) { if (storeObj) {
return storeObj[_valueKeyFieldName]; return storeObj[_valueKeyFieldName];
} else { } else {
@ -104,12 +104,12 @@ function KVMap() {
return true; return true;
}, },
exist: function(key) { exist: function(key) {
var result = _dict.hasOwnProperty(keyToString(key)); const result = _dict.hasOwnProperty(keyToString(key));
return result; return result;
}, },
getKeys: function() { getKeys: function() {
var result = []; const result = [];
for (var key in _dict) { for (const key in _dict) {
result.push(_dict[key][_originalKeyFieldName]); result.push(_dict[key][_originalKeyFieldName]);
} }
return result; return result;

View File

@ -13,14 +13,14 @@ module.exports = function getIntrospector(ModelBuilder) {
} }
// Check registered schemaTypes // Check registered schemaTypes
for (var t in ModelBuilder.schemaTypes) { for (const t in ModelBuilder.schemaTypes) {
var st = ModelBuilder.schemaTypes[t]; const st = ModelBuilder.schemaTypes[t];
if (st !== Object && st !== Array && (value instanceof st)) { if (st !== Object && st !== Array && (value instanceof st)) {
return t; return t;
} }
} }
var type = typeof value; const type = typeof value;
if (type === 'string' || type === 'number' || type === 'boolean') { if (type === 'string' || type === 'number' || type === 'boolean') {
return type; return type;
} }
@ -29,9 +29,9 @@ module.exports = function getIntrospector(ModelBuilder) {
return 'date'; return 'date';
} }
var itemType; let itemType;
if (Array.isArray(value)) { 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) { if (value[i] === null || value[i] === undefined) {
continue; continue;
} }
@ -47,8 +47,8 @@ module.exports = function getIntrospector(ModelBuilder) {
return value.constructor.name; return value.constructor.name;
} }
var properties = {}; const properties = {};
for (var p in value) { for (const p in value) {
itemType = introspectType(value[p]); itemType = introspectType(value[p]);
if (itemType) { if (itemType) {
properties[p] = itemType; properties[p] = itemType;

View File

@ -5,7 +5,7 @@
'use strict'; '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) { Object.keys(baseClass).forEach(function(classProp) {
if (classProp !== 'super_' && (!newClass.hasOwnProperty(classProp) || if (classProp !== 'super_' && (!newClass.hasOwnProperty(classProp) ||
options.override)) { options.override)) {
var pd = Object.getOwnPropertyDescriptor(baseClass, classProp); const pd = Object.getOwnPropertyDescriptor(baseClass, classProp);
Object.defineProperty(newClass, classProp, pd); Object.defineProperty(newClass, classProp, pd);
} }
}); });
@ -75,13 +75,13 @@ exports.mixin = function(newClass, mixinClass, options) {
function mixInto(sourceScope, targetScope, options) { function mixInto(sourceScope, targetScope, options) {
Object.keys(sourceScope).forEach(function(propertyName) { Object.keys(sourceScope).forEach(function(propertyName) {
var targetPropertyExists = targetScope.hasOwnProperty(propertyName); const targetPropertyExists = targetScope.hasOwnProperty(propertyName);
var sourceProperty = Object.getOwnPropertyDescriptor(sourceScope, propertyName); const sourceProperty = Object.getOwnPropertyDescriptor(sourceScope, propertyName);
var targetProperty = targetPropertyExists && Object.getOwnPropertyDescriptor(targetScope, propertyName); const targetProperty = targetPropertyExists && Object.getOwnPropertyDescriptor(targetScope, propertyName);
var sourceIsFunc = typeof sourceProperty.value === 'function'; const sourceIsFunc = typeof sourceProperty.value === 'function';
var isFunc = targetPropertyExists && typeof targetProperty.value === 'function'; const isFunc = targetPropertyExists && typeof targetProperty.value === 'function';
var isDelegate = isFunc && targetProperty.value._delegate; const isDelegate = isFunc && targetProperty.value._delegate;
var shouldOverride = options.override || !targetPropertyExists || isDelegate; const shouldOverride = options.override || !targetPropertyExists || isDelegate;
if (propertyName == '_mixins') { if (propertyName == '_mixins') {
mergeMixins(sourceScope._mixins, targetScope._mixins); mergeMixins(sourceScope._mixins, targetScope._mixins);
@ -96,8 +96,8 @@ function mixInto(sourceScope, targetScope, options) {
function mergeMixins(source, target) { function mergeMixins(source, target) {
// hand-written equivalent of lodash.union() // hand-written equivalent of lodash.union()
for (var ix in source) { for (const ix in source) {
var mx = source[ix]; const mx = source[ix];
if (target.indexOf(mx) === -1) if (target.indexOf(mx) === -1)
target.push(mx); target.push(mx);
} }

View File

@ -1,9 +1,9 @@
'use strict'; 'use strict';
var assert = require('assert'); const assert = require('assert');
var async = require('async'); const async = require('async');
var debug = require('debug')('loopback:kvao:delete-all'); const debug = require('debug')('loopback:kvao:delete-all');
var utils = require('../utils'); const utils = require('../utils');
/** /**
* Delete all keys (and values) associated to the current model. * Delete all keys (and values) associated to the current model.
@ -27,17 +27,17 @@ module.exports = function deleteAll(options, callback) {
callback = callback || utils.createPromiseCallback(); callback = callback || utils.createPromiseCallback();
var connector = this.getConnector(); const connector = this.getConnector();
if (typeof connector.deleteAll === 'function') { if (typeof connector.deleteAll === 'function') {
connector.deleteAll(this.modelName, options, callback); connector.deleteAll(this.modelName, options, callback);
} else if (typeof connector.delete === 'function') { } else if (typeof connector.delete === 'function') {
debug('Falling back to unoptimized key-value pair deletion'); debug('Falling back to unoptimized key-value pair deletion');
iterateAndDelete(connector, this.modelName, options, callback); iterateAndDelete(connector, this.modelName, options, callback);
} else { } else {
var errMsg = 'Connector does not support key-value pair deletion'; const errMsg = 'Connector does not support key-value pair deletion';
debug(errMsg); debug(errMsg);
process.nextTick(function() { process.nextTick(function() {
var err = new Error(errMsg); const err = new Error(errMsg);
err.statusCode = 501; err.statusCode = 501;
callback(err); callback(err);
}); });
@ -46,8 +46,8 @@ module.exports = function deleteAll(options, callback) {
}; };
function iterateAndDelete(connector, modelName, options, callback) { function iterateAndDelete(connector, modelName, options, callback) {
var iter = connector.iterateKeys(modelName, {}); const iter = connector.iterateKeys(modelName, {});
var keys = []; const keys = [];
iter.next(onNextKey); iter.next(onNextKey);
function onNextKey(err, key) { function onNextKey(err, key) {

View File

@ -1,8 +1,8 @@
'use strict'; 'use strict';
var assert = require('assert'); const assert = require('assert');
var debug = require('debug')('loopback:kvao:delete'); const debug = require('debug')('loopback:kvao:delete');
var utils = require('../utils'); const utils = require('../utils');
/** /**
* Delete the key-value pair associated to the given key. * 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(); callback = callback || utils.createPromiseCallback();
var connector = this.getConnector(); const connector = this.getConnector();
if (typeof connector.delete === 'function') { if (typeof connector.delete === 'function') {
connector.delete(this.modelName, key, options, callback); connector.delete(this.modelName, key, options, callback);
} else { } else {
var errMsg = 'Connector does not support key-value pair deletion'; const errMsg = 'Connector does not support key-value pair deletion';
debug(errMsg); debug(errMsg);
process.nextTick(function() { process.nextTick(function() {
var err = new Error(errMsg); const err = new Error(errMsg);
err.statusCode = 501; err.statusCode = 501;
callback(err); callback(err);
}); });

View File

@ -1,7 +1,7 @@
'use strict'; 'use strict';
var assert = require('assert'); const assert = require('assert');
var utils = require('../utils'); const utils = require('../utils');
/** /**
* Set the TTL (time to live) in ms (milliseconds) for a given key. TTL is the * Set the TTL (time to live) in ms (milliseconds) for a given key. TTL is the

View File

@ -1,7 +1,7 @@
'use strict'; 'use strict';
var assert = require('assert'); const assert = require('assert');
var utils = require('../utils'); const utils = require('../utils');
/** /**
* Return the value associated with a given key. * Return the value associated with a given key.

View File

@ -1,7 +1,7 @@
'use strict'; 'use strict';
var assert = require('assert'); const assert = require('assert');
var utils = require('../utils'); const utils = require('../utils');
/** /**
* Asynchronously iterate all keys in the database. Similar to `.keys()` but * 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 filter === 'object', 'filter must be an object');
assert(typeof options === 'object', 'options 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 // promisify the returned iterator
return { return {
next: function(callback) { next: function(callback) {

View File

@ -1,7 +1,7 @@
'use strict'; 'use strict';
var assert = require('assert'); const assert = require('assert');
var utils = require('../utils'); const utils = require('../utils');
/** /**
* Return all keys in the database. * Return all keys in the database.
@ -41,8 +41,8 @@ module.exports = function keyValueKeys(filter, options, callback) {
callback = callback || utils.createPromiseCallback(); callback = callback || utils.createPromiseCallback();
var iter = this.iterateKeys(filter, options); const iter = this.iterateKeys(filter, options);
var keys = []; const keys = [];
iter.next(onNextKey); iter.next(onNextKey);
function onNextKey(err, key) { function onNextKey(err, key) {

View File

@ -1,7 +1,7 @@
'use strict'; 'use strict';
var assert = require('assert'); const assert = require('assert');
var utils = require('../utils'); const utils = require('../utils');
/** /**
* Persist a value and associate it with the given key. * Persist a value and associate it with the given key.

View File

@ -1,7 +1,7 @@
'use strict'; 'use strict';
var assert = require('assert'); const assert = require('assert');
var utils = require('../utils'); const utils = require('../utils');
/** /**
* Return the TTL (time to live) for a given key. TTL is the remaining time * Return the TTL (time to live) for a given key. TTL is the remaining time

View File

@ -5,14 +5,14 @@
'use strict'; 'use strict';
var g = require('strong-globalize')(); const g = require('strong-globalize')();
var util = require('util'); const util = require('util');
var Any = require('./types').Types.Any; const Any = require('./types').Types.Any;
module.exports = List; module.exports = List;
function List(items, itemType, parent) { function List(items, itemType, parent) {
var list = this; const list = this;
if (!(list instanceof List)) { if (!(list instanceof List)) {
return new List(items, itemType, parent); return new List(items, itemType, parent);
} }
@ -27,7 +27,7 @@ function List(items, itemType, parent) {
} }
} }
var arr = []; const arr = [];
arr.__proto__ = List.prototype; arr.__proto__ = List.prototype;
items = items || []; items = items || [];
@ -80,16 +80,16 @@ function List(items, itemType, parent) {
util.inherits(List, Array); util.inherits(List, Array);
var _push = List.prototype.push; const _push = List.prototype.push;
List.prototype.push = function(obj) { 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); _push.call(this, item);
return item; return item;
}; };
List.prototype.toObject = function(onlySchema, removeHidden, removeProtected) { List.prototype.toObject = function(onlySchema, removeHidden, removeProtected) {
var items = []; const items = [];
this.forEach(function(item) { this.forEach(function(item) {
if (item && typeof item === 'object' && item.toObject) { if (item && typeof item === 'object' && item.toObject) {
items.push(item.toObject(onlySchema, removeHidden, removeProtected)); 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 * Some modules such as `should` checks prototype for comparison
*/ */
List.prototype.toArray = function() { List.prototype.toArray = function() {
var items = []; const items = [];
this.forEach(function(item) { this.forEach(function(item) {
items.push(item); items.push(item);
}); });

View File

@ -4,9 +4,9 @@
// License text available at https://opensource.org/licenses/MIT // License text available at https://opensource.org/licenses/MIT
'use strict'; 'use strict';
var debug = require('debug')('loopback:mixin'); const debug = require('debug')('loopback:mixin');
var assert = require('assert'); const assert = require('assert');
var DefaultModelBaseClass = require('./model.js'); const DefaultModelBaseClass = require('./model.js');
function isModelClass(cls) { function isModelClass(cls) {
if (!cls) { if (!cls) {
@ -29,7 +29,7 @@ function MixinProvider(modelBuilder) {
* @param {Object} options * @param {Object} options
*/ */
MixinProvider.prototype.applyMixin = function applyMixin(modelClass, name, options) { MixinProvider.prototype.applyMixin = function applyMixin(modelClass, name, options) {
var fn = this.mixins[name]; const fn = this.mixins[name];
if (typeof fn === 'function') { if (typeof fn === 'function') {
if (modelClass.dataSource) { if (modelClass.dataSource) {
fn(modelClass, options || {}); fn(modelClass, options || {});
@ -40,12 +40,12 @@ MixinProvider.prototype.applyMixin = function applyMixin(modelClass, name, optio
} }
} else { } else {
// Try model name // Try model name
var model = this.modelBuilder.getModel(name); const model = this.modelBuilder.getModel(name);
if (model) { if (model) {
debug('Mixin is resolved to a model: %s', name); debug('Mixin is resolved to a model: %s', name);
modelClass.mixin(model, options); modelClass.mixin(model, options);
} else { } else {
var errMsg = 'Model "' + modelClass.modelName + '" uses unknown mixin: ' + name; const errMsg = 'Model "' + modelClass.modelName + '" uses unknown mixin: ' + name;
debug(errMsg); debug(errMsg);
throw new Error(errMsg); throw new Error(errMsg);
} }

View File

@ -8,24 +8,24 @@
* Module dependencies * Module dependencies
*/ */
var g = require('strong-globalize')(); const g = require('strong-globalize')();
var inflection = require('inflection'); const inflection = require('inflection');
var EventEmitter = require('events').EventEmitter; const EventEmitter = require('events').EventEmitter;
var util = require('util'); const util = require('util');
var assert = require('assert'); const assert = require('assert');
var deprecated = require('depd')('loopback-datasource-juggler'); const deprecated = require('depd')('loopback-datasource-juggler');
var DefaultModelBaseClass = require('./model.js'); const DefaultModelBaseClass = require('./model.js');
var List = require('./list.js'); const List = require('./list.js');
var ModelDefinition = require('./model-definition.js'); const ModelDefinition = require('./model-definition.js');
var deepMerge = require('./utils').deepMerge; const deepMerge = require('./utils').deepMerge;
var deepMergeProperty = require('./utils').deepMergeProperty; const deepMergeProperty = require('./utils').deepMergeProperty;
var rankArrayElements = require('./utils').rankArrayElements; const rankArrayElements = require('./utils').rankArrayElements;
var MixinProvider = require('./mixins'); const MixinProvider = require('./mixins');
// Set up types // Set up types
require('./types')(ModelBuilder); require('./types')(ModelBuilder);
var introspect = require('./introspection')(ModelBuilder); const introspect = require('./introspection')(ModelBuilder);
/*! /*!
* Export public API * Export public API
@ -35,7 +35,7 @@ exports.ModelBuilder = exports.Schema = ModelBuilder;
/*! /*!
* Helpers * Helpers
*/ */
var slice = Array.prototype.slice; const slice = Array.prototype.slice;
/** /**
* ModelBuilder - A builder to define data models. * ModelBuilder - A builder to define data models.
@ -74,7 +74,7 @@ function isModelClass(cls) {
* @returns {ModelClass} The model class * @returns {ModelClass} The model class
*/ */
ModelBuilder.prototype.getModel = function(name, forceCreate) { ModelBuilder.prototype.getModel = function(name, forceCreate) {
var model = this.models[name]; let model = this.models[name];
if (!model && forceCreate) { if (!model && forceCreate) {
model = this.define(name, {}, {unresolved: true}); model = this.define(name, {}, {unresolved: true});
} }
@ -120,13 +120,13 @@ ModelBuilder.prototype.getModelDefinition = function(name) {
* *
*/ */
ModelBuilder.prototype.define = function defineClass(className, properties, settings, parent) { ModelBuilder.prototype.define = function defineClass(className, properties, settings, parent) {
var modelBuilder = this; const modelBuilder = this;
var args = slice.call(arguments); const args = slice.call(arguments);
var pluralName = (settings && settings.plural) || const pluralName = (settings && settings.plural) ||
inflection.pluralize(className); inflection.pluralize(className);
var httpOptions = (settings && settings.http) || {}; const httpOptions = (settings && settings.http) || {};
var pathName = httpOptions.path || pluralName; let pathName = httpOptions.path || pluralName;
if (!className) { if (!className) {
throw new Error(g.f('Class name required')); 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 // Set up the base model class
var ModelBaseClass = parent || this.defaultModelBaseClass; let ModelBaseClass = parent || this.defaultModelBaseClass;
var baseClass = settings.base || settings['super']; const baseClass = settings.base || settings['super'];
if (baseClass) { if (baseClass) {
// Normalize base model property // Normalize base model property
settings.base = baseClass; 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 // 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) // 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. // 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); ModelClass = createModelClassCtor(className, ModelBaseClass);
// mix in EventEmitter (don't inherit from) // 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 // The model can have more than 10 listeners for lazy relationship setup
// See https://github.com/strongloop/loopback/issues/404 // See https://github.com/strongloop/loopback/issues/404
events.setMaxListeners(32); events.setMaxListeners(32);
for (var f in EventEmitter.prototype) { for (const f in EventEmitter.prototype) {
if (typeof EventEmitter.prototype[f] === 'function') { if (typeof EventEmitter.prototype[f] === 'function') {
ModelClass[f] = EventEmitter.prototype[f].bind(events); ModelClass[f] = EventEmitter.prototype[f].bind(events);
} }
@ -229,7 +229,7 @@ ModelBuilder.prototype.define = function defineClass(className, properties, sett
hiddenProperty(ModelClass, '_warned', {}); hiddenProperty(ModelClass, '_warned', {});
// inherit ModelBaseClass static methods // inherit ModelBaseClass static methods
for (var i in ModelBaseClass) { for (const i in ModelBaseClass) {
// We need to skip properties that are already in the subclass, for example, the event emitter methods // We need to skip properties that are already in the subclass, for example, the event emitter methods
if (i !== '_mixins' && !(i in ModelClass)) { if (i !== '_mixins' && !(i in ModelClass)) {
ModelClass[i] = ModelBaseClass[i]; ModelClass[i] = ModelBaseClass[i];
@ -239,7 +239,7 @@ ModelBuilder.prototype.define = function defineClass(className, properties, sett
// Load and inject the model classes // Load and inject the model classes
if (settings.models) { if (settings.models) {
Object.keys(settings.models).forEach(function(m) { 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; 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.getter = {};
ModelClass.setter = {}; 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. // 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 // 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 // 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 // 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. // 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. // 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 // Remove properties that reverted by the subclass of the property from excludePropertyList
if (properties[p] === null || properties[p] === false || if (properties[p] === null || properties[p] === false ||
(excludePropertyList != null && excludePropertyList.indexOf(p) != -1)) { (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; 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 // keep a pointer to settings as models can use it for configuration
ModelClass.settings = modelDefinition.settings; ModelClass.settings = modelDefinition.settings;
var idInjection = settings.idInjection; let idInjection = settings.idInjection;
if (idInjection !== false) { if (idInjection !== false) {
// Default to true if undefined // Default to true if undefined
idInjection = true; idInjection = true;
} }
var idNames = modelDefinition.idNames(); let idNames = modelDefinition.idNames();
if (idNames.length > 0) { if (idNames.length > 0) {
// id already exists // id already exists
idInjection = false; idInjection = false;
@ -306,11 +306,11 @@ ModelBuilder.prototype.define = function defineClass(className, properties, sett
idNames = modelDefinition.idNames(); // Reload it after rebuild idNames = modelDefinition.idNames(); // Reload it after rebuild
// Create a virtual property 'id' // Create a virtual property 'id'
if (idNames.length === 1) { if (idNames.length === 1) {
var idProp = idNames[0]; const idProp = idNames[0];
if (idProp !== 'id') { if (idProp !== 'id') {
Object.defineProperty(ModelClass.prototype, 'id', { Object.defineProperty(ModelClass.prototype, 'id', {
get: function() { get: function() {
var idProp = ModelClass.definition.idNames()[0]; const idProp = ModelClass.definition.idNames()[0];
return this.__data[idProp]; return this.__data[idProp];
}, },
configurable: true, configurable: true,
@ -321,9 +321,9 @@ ModelBuilder.prototype.define = function defineClass(className, properties, sett
// Now the id property is an object that consists of multiple keys // Now the id property is an object that consists of multiple keys
Object.defineProperty(ModelClass.prototype, 'id', { Object.defineProperty(ModelClass.prototype, 'id', {
get: function() { get: function() {
var compositeId = {}; const compositeId = {};
var idNames = ModelClass.definition.idNames(); const idNames = ModelClass.definition.idNames();
for (var i = 0, p; i < idNames.length; i++) { for (let i = 0, p; i < idNames.length; i++) {
p = idNames[i]; p = idNames[i];
compositeId[p] = this.__data[p]; compositeId[p] = this.__data[p];
} }
@ -336,10 +336,10 @@ ModelBuilder.prototype.define = function defineClass(className, properties, sett
// updateOnly property is added to indicate that this property will appear in // updateOnly property is added to indicate that this property will appear in
// the model for update/updateorcreate operations but and not for create operation. // 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) { if (idNames.length > 0) {
var idName = modelDefinition.idName(); const idName = modelDefinition.idName();
idProp = ModelClass.definition.rawProperties[idName]; const idProp = ModelClass.definition.rawProperties[idName];
if (idProp.generated && forceId !== false) { if (idProp.generated && forceId !== false) {
forceId = 'auto'; forceId = 'auto';
} else if (!idProp.generated && forceId === 'auto') { } else if (!idProp.generated && forceId === 'auto') {
@ -362,9 +362,9 @@ ModelBuilder.prototype.define = function defineClass(className, properties, sett
// A function to loop through the properties // A function to loop through the properties
ModelClass.forEachProperty = function(cb) { ModelClass.forEachProperty = function(cb) {
var props = ModelClass.definition.properties; const props = ModelClass.definition.properties;
var keys = Object.keys(props); const keys = Object.keys(props);
for (var i = 0, n = keys.length; i < n; i++) { for (let i = 0, n = keys.length; i < n; i++) {
cb(keys[i], props[keys[i]]); cb(keys[i], props[keys[i]]);
} }
}; };
@ -396,15 +396,15 @@ ModelBuilder.prototype.define = function defineClass(className, properties, sett
* merged with base model settings. * merged with base model settings.
*/ */
ModelClass.extend = function(className, subClassProperties, subClassSettings) { ModelClass.extend = function(className, subClassProperties, subClassSettings) {
var baseClassProperties = ModelClass.definition.properties; const baseClassProperties = ModelClass.definition.properties;
var baseClassSettings = ModelClass.definition.settings; const baseClassSettings = ModelClass.definition.settings;
subClassProperties = subClassProperties || {}; subClassProperties = subClassProperties || {};
subClassSettings = subClassSettings || {}; subClassSettings = subClassSettings || {};
// Check if subclass redefines the ids // Check if subclass redefines the ids
var idFound = false; let idFound = false;
for (var k in subClassProperties) { for (const k in subClassProperties) {
if (subClassProperties[k] && subClassProperties[k].id) { if (subClassProperties[k] && subClassProperties[k].id) {
idFound = true; idFound = true;
break; break;
@ -412,17 +412,17 @@ ModelBuilder.prototype.define = function defineClass(className, properties, sett
} }
// Merging the properties // Merging the properties
var keys = Object.keys(baseClassProperties); const keys = Object.keys(baseClassProperties);
for (var i = 0, n = keys.length; i < n; i++) { for (let i = 0, n = keys.length; i < n; i++) {
var key = keys[i]; const key = keys[i];
if (idFound && baseClassProperties[key].id) { if (idFound && baseClassProperties[key].id) {
// don't inherit id properties // don't inherit id properties
continue; continue;
} }
if (subClassProperties[key] === undefined) { if (subClassProperties[key] === undefined) {
var baseProp = baseClassProperties[key]; const baseProp = baseClassProperties[key];
var basePropCopy = baseProp; let basePropCopy = baseProp;
if (baseProp && typeof baseProp === 'object') { if (baseProp && typeof baseProp === 'object') {
// Deep clone the base properties // Deep clone the base properties
basePropCopy = deepMerge(baseProp); basePropCopy = deepMerge(baseProp);
@ -432,8 +432,8 @@ ModelBuilder.prototype.define = function defineClass(className, properties, sett
} }
// Merging the settings // Merging the settings
var originalSubclassSettings = subClassSettings; const originalSubclassSettings = subClassSettings;
let mergePolicy = ModelClass.getMergePolicy(subClassSettings); const mergePolicy = ModelClass.getMergePolicy(subClassSettings);
subClassSettings = mergeSettings(baseClassSettings, subClassSettings, mergePolicy); subClassSettings = mergeSettings(baseClassSettings, subClassSettings, mergePolicy);
// Ensure 'base' is not inherited. Note we don't have to delete 'super' // 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 // Define the subclass
var subClass = modelBuilder.define(className, subClassProperties, subClassSettings, ModelClass); const subClass = modelBuilder.define(className, subClassProperties, subClassSettings, ModelClass);
// Calling the setup function // Calling the setup function
if (typeof subClass.setup === 'function') { if (typeof subClass.setup === 'function') {
@ -492,7 +492,7 @@ ModelBuilder.prototype.define = function defineClass(className, properties, sett
*/ */
function mergeSettings(baseClassSettings, subClassSettings, mergePolicy) { function mergeSettings(baseClassSettings, subClassSettings, mergePolicy) {
// deep clone base class settings // deep clone base class settings
let mergedSettings = deepMerge(baseClassSettings); const mergedSettings = deepMerge(baseClassSettings);
Object.keys(baseClassSettings).forEach(function(key) { Object.keys(baseClassSettings).forEach(function(key) {
// rank base class settings arrays elements where required // 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. * @param {String} propertyName Name of the property.
*/ */
ModelClass.registerProperty = function(propertyName) { ModelClass.registerProperty = function(propertyName) {
var properties = modelDefinition.build(); const properties = modelDefinition.build();
var prop = properties[propertyName]; const prop = properties[propertyName];
var DataType = prop.type; const DataType = prop.type;
if (!DataType) { if (!DataType) {
throw new Error(g.f('Invalid type for property %s', propertyName)); throw new Error(g.f('Invalid type for property %s', propertyName));
} }
if (prop.required) { 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); ModelClass.validatesPresenceOf(propertyName, requiredOptions);
} }
if (DataType === Date) ModelClass.validatesDateOf(propertyName); if (DataType === Date) ModelClass.validatesDateOf(propertyName);
@ -567,7 +567,7 @@ ModelBuilder.prototype.define = function defineClass(className, properties, sett
} }
}, },
set: function(value) { set: function(value) {
var DataType = ModelClass.definition.properties[propertyName].type; let DataType = ModelClass.definition.properties[propertyName].type;
if (Array.isArray(DataType) || DataType === Array) { if (Array.isArray(DataType) || DataType === Array) {
DataType = List; DataType = List;
} else if (DataType === Date) { } else if (DataType === Date) {
@ -578,7 +578,7 @@ ModelBuilder.prototype.define = function defineClass(className, properties, sett
DataType = modelBuilder.resolveType(DataType); DataType = modelBuilder.resolveType(DataType);
} }
var persistUndefinedAsNull = ModelClass.definition.settings.persistUndefinedAsNull; const persistUndefinedAsNull = ModelClass.definition.settings.persistUndefinedAsNull;
if (value === undefined && persistUndefinedAsNull) { if (value === undefined && persistUndefinedAsNull) {
value = null; value = null;
} }
@ -621,20 +621,20 @@ ModelBuilder.prototype.define = function defineClass(className, properties, sett
}); });
}; };
var props = ModelClass.definition.properties; const props = ModelClass.definition.properties;
var keys = Object.keys(props); let keys = Object.keys(props);
var size = keys.length; let size = keys.length;
for (i = 0; i < size; i++) { for (let i = 0; i < size; i++) {
var propertyName = keys[i]; const propertyName = keys[i];
ModelClass.registerProperty(propertyName); ModelClass.registerProperty(propertyName);
} }
var mixinSettings = settings.mixins || {}; const mixinSettings = settings.mixins || {};
keys = Object.keys(mixinSettings); keys = Object.keys(mixinSettings);
size = keys.length; size = keys.length;
for (i = 0; i < size; i++) { for (let i = 0; i < size; i++) {
var name = keys[i]; const name = keys[i];
var mixin = mixinSettings[name]; let mixin = mixinSettings[name];
if (mixin === true) { if (mixin === true) {
mixin = {}; mixin = {};
} }
@ -696,7 +696,7 @@ function createModelClassCtor(name, ModelBaseClass) {
// DataType for Date // DataType for Date
function DateType(arg) { function DateType(arg) {
if (arg === null) return null; if (arg === null) return null;
var d = new Date(arg); const d = new Date(arg);
return d; return d;
} }
@ -770,19 +770,19 @@ ModelBuilder.prototype.defineValueType = function(type, aliases) {
* @property {Boolean} index True if the property is an index; false otherwise. * @property {Boolean} index True if the property is an index; false otherwise.
*/ */
ModelBuilder.prototype.extendModel = function(model, props) { ModelBuilder.prototype.extendModel = function(model, props) {
var t = this; const t = this;
var keys = Object.keys(props); const keys = Object.keys(props);
for (var i = 0; i < keys.length; i++) { for (let i = 0; i < keys.length; i++) {
var definition = props[keys[i]]; const definition = props[keys[i]];
t.defineProperty(model, keys[i], definition); t.defineProperty(model, keys[i], definition);
} }
}; };
ModelBuilder.prototype.copyModel = function copyModel(Master) { ModelBuilder.prototype.copyModel = function copyModel(Master) {
var modelBuilder = this; const modelBuilder = this;
var className = Master.modelName; const className = Master.modelName;
var md = Master.modelBuilder.definitions[className]; const md = Master.modelBuilder.definitions[className];
var Slave = function SlaveModel() { const Slave = function SlaveModel() {
Master.apply(this, [].slice.call(arguments)); Master.apply(this, [].slice.call(arguments));
}; };
@ -858,7 +858,7 @@ ModelBuilder.prototype.resolveType = function(type) {
} }
if (Array.isArray(type) && type.length > 0) { if (Array.isArray(type) && type.length > 0) {
// For array types, the first item should be the type string // 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') { if (typeof itemType === 'function') {
return [itemType]; return [itemType];
} else { } else {
@ -866,7 +866,7 @@ ModelBuilder.prototype.resolveType = function(type) {
} }
} }
if (typeof type === 'string') { if (typeof type === 'string') {
var schemaType = ModelBuilder.schemaTypes[type.toLowerCase()] || this.models[type]; const schemaType = ModelBuilder.schemaTypes[type.toLowerCase()] || this.models[type];
if (schemaType) { if (schemaType) {
return schemaType; return schemaType;
} else { } else {
@ -906,7 +906,7 @@ ModelBuilder.prototype.resolveType = function(type) {
* model name. * model name.
*/ */
ModelBuilder.prototype.buildModels = function(schemas, createModel) { 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: {}} // Normalize the schemas to be an array of the schema objects {name: <name>, properties: {}, options: {}}
if (!Array.isArray(schemas)) { if (!Array.isArray(schemas)) {
@ -925,25 +925,22 @@ ModelBuilder.prototype.buildModels = function(schemas, createModel) {
} }
} }
var relations = []; let relations = [];
for (var s = 0, n = schemas.length; s < n; s++) { for (let s = 0, n = schemas.length; s < n; s++) {
var name = this.getSchemaName(schemas[s].name); const name = this.getSchemaName(schemas[s].name);
schemas[s].name = name; schemas[s].name = name;
var model; const model = typeof createModel === 'function' ?
if (typeof createModel === 'function') { createModel(schemas[s].name, schemas[s].properties, schemas[s].options) :
model = createModel(schemas[s].name, schemas[s].properties, schemas[s].options); this.define(schemas[s].name, schemas[s].properties, schemas[s].options);
} else {
model = this.define(schemas[s].name, schemas[s].properties, schemas[s].options);
}
models[name] = model; models[name] = model;
relations = relations.concat(model.definition.relations); relations = relations.concat(model.definition.relations);
} }
// Connect the models based on the relations // Connect the models based on the relations
for (var i = 0; i < relations.length; i++) { for (let i = 0; i < relations.length; i++) {
var relation = relations[i]; const relation = relations[i];
var sourceModel = models[relation.source]; const sourceModel = models[relation.source];
var targetModel = models[relation.target]; const targetModel = models[relation.target];
if (sourceModel && targetModel) { if (sourceModel && targetModel) {
if (typeof sourceModel[relation.type] === 'function') { if (typeof sourceModel[relation.type] === 'function') {
sourceModel[relation.type](targetModel, {as: relation.as}); sourceModel[relation.type](targetModel, {as: relation.as});
@ -962,7 +959,7 @@ ModelBuilder.prototype.buildModels = function(schemas, createModel) {
*/ */
ModelBuilder.prototype.buildModelFromInstance = function(name, json, options) { ModelBuilder.prototype.buildModelFromInstance = function(name, json, options) {
// Introspect the JSON document to generate a schema // Introspect the JSON document to generate a schema
var schema = introspect(json); const schema = introspect(json);
// Create a model for the generated schema // Create a model for the generated schema
return this.define(name, schema, options); return this.define(name, schema, options);

View File

@ -4,12 +4,12 @@
// License text available at https://opensource.org/licenses/MIT // License text available at https://opensource.org/licenses/MIT
'use strict'; 'use strict';
var assert = require('assert'); const assert = require('assert');
var util = require('util'); const util = require('util');
var EventEmitter = require('events').EventEmitter; const EventEmitter = require('events').EventEmitter;
var traverse = require('traverse'); const traverse = require('traverse');
var ModelBaseClass = require('./model'); const ModelBaseClass = require('./model');
var ModelBuilder = require('./model-builder'); const ModelBuilder = require('./model-builder');
/** /**
* Model definition * Model definition
@ -35,7 +35,7 @@ function ModelDefinition(modelBuilder, name, properties, settings) {
assert(name, 'name is missing'); assert(name, 'name is missing');
if (arguments.length === 2 && typeof name === 'object') { if (arguments.length === 2 && typeof name === 'object') {
var schema = name; const schema = name;
this.name = schema.name; this.name = schema.name;
this.rawProperties = schema.properties || {}; // Keep the raw property definitions this.rawProperties = schema.properties || {}; // Keep the raw property definitions
this.settings = schema.settings || {}; this.settings = schema.settings || {};
@ -60,7 +60,7 @@ require('./types')(ModelDefinition);
* @param {String} connectorType The connector type, such as 'oracle' or 'mongodb' * @param {String} connectorType The connector type, such as 'oracle' or 'mongodb'
*/ */
ModelDefinition.prototype.tableName = function(connectorType) { ModelDefinition.prototype.tableName = function(connectorType) {
var settings = this.settings; const settings = this.settings;
if (settings[connectorType]) { if (settings[connectorType]) {
return settings[connectorType].table || settings[connectorType].tableName || this.name; return settings[connectorType].table || settings[connectorType].tableName || this.name;
} else { } else {
@ -79,7 +79,7 @@ ModelDefinition.prototype.columnName = function(connectorType, propertyName) {
return propertyName; return propertyName;
} }
this.build(); this.build();
var property = this.properties[propertyName]; const property = this.properties[propertyName];
if (property && property[connectorType]) { if (property && property[connectorType]) {
return property[connectorType].column || property[connectorType].columnName || propertyName; return property[connectorType].column || property[connectorType].columnName || propertyName;
} else { } else {
@ -98,7 +98,7 @@ ModelDefinition.prototype.columnMetadata = function(connectorType, propertyName)
return propertyName; return propertyName;
} }
this.build(); this.build();
var property = this.properties[propertyName]; const property = this.properties[propertyName];
if (property && property[connectorType]) { if (property && property[connectorType]) {
return property[connectorType]; return property[connectorType];
} else { } else {
@ -113,9 +113,9 @@ ModelDefinition.prototype.columnMetadata = function(connectorType, propertyName)
*/ */
ModelDefinition.prototype.columnNames = function(connectorType) { ModelDefinition.prototype.columnNames = function(connectorType) {
this.build(); this.build();
var props = this.properties; const props = this.properties;
var cols = []; const cols = [];
for (var p in props) { for (const p in props) {
if (props[p][connectorType]) { if (props[p][connectorType]) {
cols.push(props[p][connectorType].column || props[p][connectorType].columnName || p); cols.push(props[p][connectorType].column || props[p][connectorType].columnName || p);
} else { } else {
@ -133,11 +133,11 @@ ModelDefinition.prototype.ids = function() {
if (this._ids) { if (this._ids) {
return this._ids; return this._ids;
} }
var ids = []; const ids = [];
this.build(); this.build();
var props = this.properties; const props = this.properties;
for (var key in props) { for (const key in props) {
var id = props[key].id; let id = props[key].id;
if (!id) { if (!id) {
continue; continue;
} }
@ -167,7 +167,7 @@ ModelDefinition.prototype.idColumnName = function(connectorType) {
* @returns {String} property name for ID * @returns {String} property name for ID
*/ */
ModelDefinition.prototype.idName = function() { ModelDefinition.prototype.idName = function() {
var id = this.ids()[0]; const id = this.ids()[0];
if (this.properties.id && this.properties.id.id) { if (this.properties.id && this.properties.id.id) {
return 'id'; return 'id';
} else { } else {
@ -180,8 +180,8 @@ ModelDefinition.prototype.idName = function() {
* @returns {String[]} property names for IDs * @returns {String[]} property names for IDs
*/ */
ModelDefinition.prototype.idNames = function() { ModelDefinition.prototype.idNames = function() {
var ids = this.ids(); const ids = this.ids();
var names = ids.map(function(id) { const names = ids.map(function(id) {
return id.name; return id.name;
}); });
return names; return names;
@ -193,13 +193,13 @@ ModelDefinition.prototype.idNames = function() {
*/ */
ModelDefinition.prototype.indexes = function() { ModelDefinition.prototype.indexes = function() {
this.build(); this.build();
var indexes = {}; const indexes = {};
if (this.settings.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]; indexes[i] = this.settings.indexes[i];
} }
} }
for (var p in this.properties) { for (const p in this.properties) {
if (this.properties[p].index) { if (this.properties[p].index) {
indexes[p + '_index'] = this.properties[p].index; indexes[p + '_index'] = this.properties[p].index;
} }
@ -222,9 +222,9 @@ ModelDefinition.prototype.build = function(forceRebuild) {
return this.properties; return this.properties;
} }
this.properties = {}; this.properties = {};
for (var p in this.rawProperties) { for (const p in this.rawProperties) {
var prop = this.rawProperties[p]; const prop = this.rawProperties[p];
var type = this.modelBuilder.resolveType(prop); const type = this.modelBuilder.resolveType(prop);
if (typeof type === 'string') { if (typeof type === 'string') {
this.relations.push({ this.relations.push({
source: this.name, source: this.name,
@ -233,11 +233,11 @@ ModelDefinition.prototype.build = function(forceRebuild) {
as: p, as: p,
}); });
} else { } else {
var typeDef = { const typeDef = {
type: type, type: type,
}; };
if (typeof prop === 'object' && prop !== null) { 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 // Skip the type property but don't delete it Model.extend() shares same instances of the properties from the base class
if (a !== 'type') { if (a !== 'type') {
typeDef[a] = prop[a]; typeDef[a] = prop[a];
@ -274,14 +274,14 @@ ModelDefinition.prototype.toJSON = function(forceRebuild) {
if (this.json) { if (this.json) {
return this.json; return this.json;
} }
var json = { const json = {
name: this.name, name: this.name,
properties: {}, properties: {},
settings: this.settings, settings: this.settings,
}; };
this.build(forceRebuild); this.build(forceRebuild);
var mapper = function(val) { const mapper = function(val) {
if (val === undefined || val === null) { if (val === undefined || val === null) {
return val; return val;
} }
@ -302,7 +302,7 @@ ModelDefinition.prototype.toJSON = function(forceRebuild) {
return val; return val;
} }
}; };
for (var p in this.properties) { for (const p in this.properties) {
json.properties[p] = traverse(this.properties[p]).map(mapper); json.properties[p] = traverse(this.properties[p]).map(mapper);
} }
this.json = json; this.json = json;

View File

@ -12,12 +12,12 @@ module.exports = ModelUtils;
/*! /*!
* Module dependencies * Module dependencies
*/ */
var g = require('strong-globalize')(); const g = require('strong-globalize')();
var geo = require('./geo'); const geo = require('./geo');
var utils = require('./utils'); const utils = require('./utils');
var fieldsToArray = utils.fieldsToArray; const fieldsToArray = utils.fieldsToArray;
var sanitizeQueryOrData = utils.sanitizeQuery; const sanitizeQueryOrData = utils.sanitizeQuery;
var BaseModel = require('./model'); const BaseModel = require('./model');
/** /**
* A mixin to contain utility methods for DataAccessObject * A mixin to contain utility methods for DataAccessObject
@ -48,10 +48,10 @@ ModelUtils._allowExtendedOperators = function(options) {
*/ */
ModelUtils._getSetting = function(key, options) { ModelUtils._getSetting = function(key, options) {
// Check method level options // Check method level options
var val = options && options[key]; let val = options && options[key];
if (val !== undefined) return val; if (val !== undefined) return val;
// Check for settings in model // Check for settings in model
var m = this.definition; const m = this.definition;
if (m && m.settings) { if (m && m.settings) {
val = m.settings[key]; val = m.settings[key];
if (val !== undefined) { if (val !== undefined) {
@ -61,7 +61,7 @@ ModelUtils._getSetting = function(key, options) {
} }
// Check for settings in connector // Check for settings in connector
var ds = this.getDataSource(); const ds = this.getDataSource();
if (ds && ds.settings) { if (ds && ds.settings) {
return ds.settings[key]; return ds.settings[key];
} }
@ -69,7 +69,7 @@ ModelUtils._getSetting = function(key, options) {
return undefined; return undefined;
}; };
var operators = { const operators = {
eq: '=', eq: '=',
gt: '>', gt: '>',
gte: '>=', gte: '>=',
@ -98,15 +98,15 @@ ModelUtils._normalize = function(filter, options) {
if (!filter) { if (!filter) {
return undefined; return undefined;
} }
var err = null; let err = null;
if ((typeof filter !== 'object') || Array.isArray(filter)) { if ((typeof filter !== 'object') || Array.isArray(filter)) {
err = new Error(g.f('The query filter %j is not an {{object}}', filter)); err = new Error(g.f('The query filter %j is not an {{object}}', filter));
err.statusCode = 400; err.statusCode = 400;
throw err; throw err;
} }
if (filter.limit || filter.skip || filter.offset) { if (filter.limit || filter.skip || filter.offset) {
var limit = Number(filter.limit || 100); const limit = Number(filter.limit || 100);
var offset = Number(filter.skip || filter.offset || 0); const offset = Number(filter.skip || filter.offset || 0);
if (isNaN(limit) || limit <= 0 || Math.ceil(limit) !== limit) { if (isNaN(limit) || limit <= 0 || Math.ceil(limit) !== limit) {
err = new Error(g.f('The {{limit}} parameter %j is not valid', err = new Error(g.f('The {{limit}} parameter %j is not valid',
filter.limit)); filter.limit));
@ -125,24 +125,24 @@ ModelUtils._normalize = function(filter, options) {
} }
if (filter.order) { if (filter.order) {
var order = filter.order; let order = filter.order;
if (!Array.isArray(order)) { if (!Array.isArray(order)) {
order = [order]; order = [order];
} }
var fields = []; const fields = [];
for (var i = 0, m = order.length; i < m; i++) { for (let i = 0, m = order.length; i < m; i++) {
if (typeof order[i] === 'string') { if (typeof order[i] === 'string') {
// Normalize 'f1 ASC, f2 DESC, f3' to ['f1 ASC', 'f2 DESC', 'f3'] // Normalize 'f1 ASC, f2 DESC, f3' to ['f1 ASC', 'f2 DESC', 'f3']
var tokens = order[i].split(/(?:\s*,\s*)+/); const tokens = order[i].split(/(?:\s*,\s*)+/);
for (var t = 0, n = tokens.length; t < n; t++) { for (let t = 0, n = tokens.length; t < n; t++) {
var token = tokens[t]; let token = tokens[t];
if (token.length === 0) { if (token.length === 0) {
// Skip empty token // Skip empty token
continue; continue;
} }
var parts = token.split(/\s+/); const parts = token.split(/\s+/);
if (parts.length >= 2) { if (parts.length >= 2) {
var dir = parts[1].toUpperCase(); const dir = parts[1].toUpperCase();
if (dir === 'ASC' || dir === 'DESC') { if (dir === 'ASC' || dir === 'DESC') {
token = parts[0] + ' ' + dir; token = parts[0] + ' ' + dir;
} else { } else {
@ -178,7 +178,7 @@ ModelUtils._normalize = function(filter, options) {
}; };
function DateType(arg) { function DateType(arg) {
var d = new Date(arg); const d = new Date(arg);
if (isNaN(d.getTime())) { if (isNaN(d.getTime())) {
throw new Error(g.f('Invalid date: %s', arg)); throw new Error(g.f('Invalid date: %s', arg));
} }
@ -203,7 +203,7 @@ function BooleanType(arg) {
} }
function NumberType(val) { function NumberType(val) {
var num = Number(val); const num = Number(val);
return !isNaN(num) ? num : val; return !isNaN(num) ? num : val;
} }
@ -217,14 +217,14 @@ function coerceArray(val) {
} }
// It is an object, check if empty // It is an object, check if empty
var props = Object.keys(val); const props = Object.keys(val);
if (props.length === 0) { if (props.length === 0) {
throw new Error(g.f('Value is an empty {{object}}')); throw new Error(g.f('Value is an empty {{object}}'));
} }
var arrayVal = new Array(props.length); const arrayVal = new Array(props.length);
for (var i = 0; i < arrayVal.length; ++i) { for (let i = 0; i < arrayVal.length; ++i) {
if (!val.hasOwnProperty(i)) { if (!val.hasOwnProperty(i)) {
throw new Error(g.f('Value is not an {{array}} or {{object}} with sequential numeric indices')); throw new Error(g.f('Value is not an {{array}} or {{object}} with sequential numeric indices'));
} }
@ -244,8 +244,8 @@ function _normalizeAsArray(result) {
} else { } else {
// See https://github.com/strongloop/loopback-datasource-juggler/issues/1646 // See https://github.com/strongloop/loopback-datasource-juggler/issues/1646
// `ModelBaseClass` normalize the properties to an object such as `{secret: true}` // `ModelBaseClass` normalize the properties to an object such as `{secret: true}`
var keys = []; const keys = [];
for (var k in result) { for (const k in result) {
if (result[k]) keys.push(k); if (result[k]) keys.push(k);
} }
return keys; return keys;
@ -256,8 +256,8 @@ function _normalizeAsArray(result) {
* Get an array of hidden property names * Get an array of hidden property names
*/ */
ModelUtils._getHiddenProperties = function() { ModelUtils._getHiddenProperties = function() {
var settings = this.definition.settings || {}; const settings = this.definition.settings || {};
var result = settings.hiddenProperties || settings.hidden || []; const result = settings.hiddenProperties || settings.hidden || [];
return _normalizeAsArray(result); return _normalizeAsArray(result);
}; };
@ -265,8 +265,8 @@ ModelUtils._getHiddenProperties = function() {
* Get an array of protected property names * Get an array of protected property names
*/ */
ModelUtils._getProtectedProperties = function() { ModelUtils._getProtectedProperties = function() {
var settings = this.definition.settings || {}; const settings = this.definition.settings || {};
var result = settings.protectedProperties || settings.protected || []; const result = settings.protectedProperties || settings.protected || [];
return _normalizeAsArray(result); return _normalizeAsArray(result);
}; };
@ -276,7 +276,7 @@ ModelUtils._getProtectedProperties = function() {
ModelUtils._getMaxDepthOfQuery = function(options, defaultValue) { ModelUtils._getMaxDepthOfQuery = function(options, defaultValue) {
options = options || {}; options = options || {};
// See https://github.com/strongloop/loopback-datasource-juggler/issues/1651 // 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) { if (maxDepth == null) {
maxDepth = defaultValue || 32; maxDepth = defaultValue || 32;
} }
@ -289,7 +289,7 @@ ModelUtils._getMaxDepthOfQuery = function(options, defaultValue) {
ModelUtils._getMaxDepthOfData = function(options, defaultValue) { ModelUtils._getMaxDepthOfData = function(options, defaultValue) {
options = options || {}; options = options || {};
// See https://github.com/strongloop/loopback-datasource-juggler/issues/1651 // 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) { if (maxDepth == null) {
maxDepth = defaultValue || 64; maxDepth = defaultValue || 64;
} }
@ -300,7 +300,7 @@ ModelUtils._getMaxDepthOfData = function(options, defaultValue) {
* Get the prohibitHiddenPropertiesInQuery flag * Get the prohibitHiddenPropertiesInQuery flag
*/ */
ModelUtils._getProhibitHiddenPropertiesInQuery = function(options, defaultValue) { ModelUtils._getProhibitHiddenPropertiesInQuery = function(options, defaultValue) {
var flag = this._getSetting('prohibitHiddenPropertiesInQuery', options); const flag = this._getSetting('prohibitHiddenPropertiesInQuery', options);
if (flag == null) return !!defaultValue; if (flag == null) return !!defaultValue;
return !!flag; return !!flag;
}; };
@ -312,14 +312,14 @@ ModelUtils._sanitizeQuery = function(query, options) {
options = options || {}; options = options || {};
// Get settings to normalize `undefined` values // 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 // 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 // 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 // Check violation of keys
if (prohibitHiddenPropertiesInQuery) { if (prohibitHiddenPropertiesInQuery) {
prohibitedKeys = this._getHiddenProperties(); prohibitedKeys = this._getHiddenProperties();
@ -355,24 +355,24 @@ ModelUtils._sanitizeData = function(data, options) {
* @private * @private
*/ */
ModelUtils._coerce = function(where, options) { ModelUtils._coerce = function(where, options) {
var self = this; const self = this;
if (where == null) { if (where == null) {
return where; return where;
} }
options = options || {}; options = options || {};
var err; let err;
if (typeof where !== 'object' || Array.isArray(where)) { if (typeof where !== 'object' || Array.isArray(where)) {
err = new Error(g.f('The where clause %j is not an {{object}}', where)); err = new Error(g.f('The where clause %j is not an {{object}}', where));
err.statusCode = 400; err.statusCode = 400;
throw err; throw err;
} }
var props = self.definition.properties; const props = self.definition.properties;
for (var p in where) { for (const p in where) {
// Handle logical operators // Handle logical operators
if (p === 'and' || p === 'or' || p === 'nor') { if (p === 'and' || p === 'or' || p === 'nor') {
var clauses = where[p]; let clauses = where[p];
try { try {
clauses = coerceArray(clauses); clauses = coerceArray(clauses);
} catch (e) { } catch (e) {
@ -381,13 +381,13 @@ ModelUtils._coerce = function(where, options) {
throw err; throw err;
} }
for (var k = 0; k < clauses.length; k++) { for (let k = 0; k < clauses.length; k++) {
self._coerce(clauses[k], options); self._coerce(clauses[k], options);
} }
continue; continue;
} }
var DataType = props[p] && props[p].type; let DataType = props[p] && props[p].type;
if (!DataType) { if (!DataType) {
continue; continue;
} }
@ -424,15 +424,15 @@ ModelUtils._coerce = function(where, options) {
continue; continue;
} }
var val = where[p]; let val = where[p];
if (val === null || val === undefined) { if (val === null || val === undefined) {
continue; continue;
} }
// Check there is an operator // Check there is an operator
var operator = null; let operator = null;
var exp = val; const exp = val;
if (val.constructor === Object) { if (val.constructor === Object) {
for (var op in operators) { for (const op in operators) {
if (op in val) { if (op in val) {
val = val[op]; val = val[op];
operator = op; operator = op;
@ -493,10 +493,10 @@ ModelUtils._coerce = function(where, options) {
// NOOP when not coercable into an array. // NOOP when not coercable into an array.
} }
var allowExtendedOperators = self._allowExtendedOperators(options); const allowExtendedOperators = self._allowExtendedOperators(options);
// Coerce the array items // Coerce the array items
if (Array.isArray(val)) { 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] !== null && val[i] !== undefined) {
if (!(val[i] instanceof RegExp)) { if (!(val[i] instanceof RegExp)) {
val[i] = DataType(val[i]); val[i] = DataType(val[i]);
@ -517,7 +517,7 @@ ModelUtils._coerce = function(where, options) {
// Do not coerce object values when extended operators are allowed // Do not coerce object values when extended operators are allowed
} else { } else {
if (!allowExtendedOperators) { if (!allowExtendedOperators) {
var extendedOperators = Object.keys(val).filter(function(k) { const extendedOperators = Object.keys(val).filter(function(k) {
return k[0] === '$'; return k[0] === '$';
}); });
if (extendedOperators.length) { if (extendedOperators.length) {
@ -538,7 +538,7 @@ ModelUtils._coerce = function(where, options) {
} }
// Rebuild {property: {operator: value}} // Rebuild {property: {operator: value}}
if (operator && operator !== 'eq') { if (operator && operator !== 'eq') {
var value = {}; const value = {};
value[operator] = val; value[operator] = val;
if (exp.options) { if (exp.options) {
// Keep options for operators // Keep options for operators

View File

@ -16,22 +16,22 @@ module.exports = ModelBaseClass;
* Module dependencies * Module dependencies
*/ */
var g = require('strong-globalize')(); const g = require('strong-globalize')();
var util = require('util'); const util = require('util');
var jutil = require('./jutil'); const jutil = require('./jutil');
var List = require('./list'); const List = require('./list');
var DataAccessUtils = require('./model-utils'); const DataAccessUtils = require('./model-utils');
var Observer = require('./observer'); const Observer = require('./observer');
var Hookable = require('./hooks'); const Hookable = require('./hooks');
var validations = require('./validations'); const validations = require('./validations');
var _extend = util._extend; const _extend = util._extend;
var utils = require('./utils'); const utils = require('./utils');
var fieldsToArray = utils.fieldsToArray; const fieldsToArray = utils.fieldsToArray;
var uuid = require('uuid'); const uuid = require('uuid');
var shortid = require('shortid'); const shortid = require('shortid');
// Set up an object for quick lookup // Set up an object for quick lookup
var BASE_TYPES = { const BASE_TYPES = {
'String': true, 'String': true,
'Boolean': true, 'Boolean': true,
'Number': true, 'Number': true,
@ -73,8 +73,8 @@ function ModelBaseClass(data, options) {
* @private * @private
*/ */
ModelBaseClass.prototype._initProperties = function(data, options) { ModelBaseClass.prototype._initProperties = function(data, options) {
var self = this; const self = this;
var ctor = this.constructor; const ctor = this.constructor;
if (typeof data !== 'undefined' && data !== null && data.constructor && if (typeof data !== 'undefined' && data !== null && data.constructor &&
typeof (data.constructor) !== 'function') { typeof (data.constructor) !== 'function') {
@ -85,7 +85,7 @@ ModelBaseClass.prototype._initProperties = function(data, options) {
// Convert the data to be plain object to avoid pollutions // Convert the data to be plain object to avoid pollutions
data = data.toObject(false); data = data.toObject(false);
} }
var properties = _extend({}, ctor.definition.properties); const properties = _extend({}, ctor.definition.properties);
data = data || {}; data = data || {};
if (typeof ctor.applyProperties === 'function') { if (typeof ctor.applyProperties === 'function') {
@ -93,9 +93,9 @@ ModelBaseClass.prototype._initProperties = function(data, options) {
} }
options = options || {}; options = options || {};
var applySetters = options.applySetters; const applySetters = options.applySetters;
var applyDefaultValues = options.applyDefaultValues; const applyDefaultValues = options.applyDefaultValues;
var strict = options.strict; let strict = options.strict;
if (strict === undefined) { if (strict === undefined) {
strict = ctor.definition.settings.strict; strict = ctor.definition.settings.strict;
@ -105,7 +105,7 @@ ModelBaseClass.prototype._initProperties = function(data, options) {
'{{`Validation Error`}} for unknown properties,', ctor.modelName); '{{`Validation Error`}} for unknown properties,', ctor.modelName);
} }
var persistUndefinedAsNull = ctor.definition.settings.persistUndefinedAsNull; const persistUndefinedAsNull = ctor.definition.settings.persistUndefinedAsNull;
if (ctor.hideInternalProperties) { if (ctor.hideInternalProperties) {
// Object.defineProperty() is expensive. We only try to make the internal // 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; this.__cachedRelations = data.__cachedRelations;
} }
var keys = Object.keys(data); let keys = Object.keys(data);
if (Array.isArray(options.fields)) { if (Array.isArray(options.fields)) {
keys = keys.filter(function(k) { keys = keys.filter(function(k) {
@ -185,9 +185,9 @@ ModelBaseClass.prototype._initProperties = function(data, options) {
}); });
} }
var size = keys.length; let size = keys.length;
var p, propVal; let p, propVal;
for (var k = 0; k < size; k++) { for (let k = 0; k < size; k++) {
p = keys[k]; p = keys[k];
propVal = data[p]; propVal = data[p];
if (typeof propVal === 'function') { if (typeof propVal === 'function') {
@ -206,14 +206,14 @@ ModelBaseClass.prototype._initProperties = function(data, options) {
self.__data[p] = propVal; self.__data[p] = propVal;
} }
} else if (ctor.relations[p]) { } else if (ctor.relations[p]) {
var relationType = ctor.relations[p].type; const relationType = ctor.relations[p].type;
var modelTo; let modelTo;
if (!properties[p]) { if (!properties[p]) {
modelTo = ctor.relations[p].modelTo || ModelBaseClass; modelTo = ctor.relations[p].modelTo || ModelBaseClass;
var multiple = ctor.relations[p].multiple; const multiple = ctor.relations[p].multiple;
var typeName = multiple ? 'Array' : modelTo.modelName; const typeName = multiple ? 'Array' : modelTo.modelName;
var propType = multiple ? [modelTo] : modelTo; const propType = multiple ? [modelTo] : modelTo;
properties[p] = {name: typeName, type: propType}; properties[p] = {name: typeName, type: propType};
/* Issue #1252 /* Issue #1252
this.setStrict(false); this.setStrict(false);
@ -226,7 +226,7 @@ ModelBaseClass.prototype._initProperties = function(data, options) {
self.__data[ctor.relations[p].keyFrom] = propVal[ctor.relations[p].keyTo]; self.__data[ctor.relations[p].keyFrom] = propVal[ctor.relations[p].keyTo];
if (ctor.relations[p].options.embedsProperties) { 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); modelTo.definition.properties, modelTo.settings.strict);
if (!~fields.indexOf(ctor.relations[p].keyTo)) { if (!~fields.indexOf(ctor.relations[p].keyTo)) {
fields.push(ctor.relations[p].keyTo); fields.push(ctor.relations[p].keyTo);
@ -272,14 +272,14 @@ ModelBaseClass.prototype._initProperties = function(data, options) {
size = keys.length; size = keys.length;
for (k = 0; k < size; k++) { for (let k = 0; k < size; k++) {
p = keys[k]; p = keys[k];
propVal = self.__data[p]; propVal = self.__data[p];
var type = properties[p].type; const type = properties[p].type;
// Set default values // Set default values
if (applyDefaultValues && propVal === undefined) { if (applyDefaultValues && propVal === undefined) {
var def = properties[p]['default']; let def = properties[p]['default'];
if (def !== undefined) { if (def !== undefined) {
if (typeof def === 'function') { if (typeof def === 'function') {
if (def === Date) { if (def === Date) {
@ -301,7 +301,7 @@ ModelBaseClass.prototype._initProperties = function(data, options) {
// Set default value using a named function // Set default value using a named function
if (applyDefaultValues && propVal === undefined) { if (applyDefaultValues && propVal === undefined) {
var defn = properties[p].defaultFn; const defn = properties[p].defaultFn;
switch (defn) { switch (defn) {
case undefined: case undefined:
break; break;
@ -381,7 +381,7 @@ ModelBaseClass.defineProperty = function(prop, params) {
* @returns {String} Name of property type * @returns {String} Name of property type
*/ */
ModelBaseClass.getPropertyType = function(propName) { ModelBaseClass.getPropertyType = function(propName) {
var prop = this.definition.properties[propName]; const prop = this.definition.properties[propName];
if (!prop) { if (!prop) {
// The property is not part of the definition // The property is not part of the definition
return null; return null;
@ -421,7 +421,7 @@ ModelBaseClass.toString = function() {
*/ */
ModelBaseClass.prototype.toObject = function(onlySchema, removeHidden, removeProtected) { ModelBaseClass.prototype.toObject = function(onlySchema, removeHidden, removeProtected) {
if (typeof onlySchema === 'object' && onlySchema != null) { if (typeof onlySchema === 'object' && onlySchema != null) {
var options = onlySchema; const options = onlySchema;
onlySchema = options.onlySchema; onlySchema = options.onlySchema;
removeHidden = options.removeHidden; removeHidden = options.removeHidden;
removeProtected = options.removeProtected; removeProtected = options.removeProtected;
@ -429,24 +429,24 @@ ModelBaseClass.prototype.toObject = function(onlySchema, removeHidden, removePro
if (onlySchema === undefined) { if (onlySchema === undefined) {
onlySchema = true; onlySchema = true;
} }
var data = {}; const data = {};
var self = this; const self = this;
var Model = this.constructor; const Model = this.constructor;
// if it is already an Object // if it is already an Object
if (Model === Object) { if (Model === Object) {
return self; return self;
} }
var strict = this.__strict; const strict = this.__strict;
var schemaLess = (strict === false) || !onlySchema; const schemaLess = (strict === false) || !onlySchema;
var persistUndefinedAsNull = Model.definition.settings.persistUndefinedAsNull; const persistUndefinedAsNull = Model.definition.settings.persistUndefinedAsNull;
var props = Model.definition.properties; const props = Model.definition.properties;
var keys = Object.keys(props); let keys = Object.keys(props);
var propertyName, val; let propertyName, val;
for (var i = 0; i < keys.length; i++) { for (let i = 0; i < keys.length; i++) {
propertyName = keys[i]; propertyName = keys[i];
val = self[propertyName]; val = self[propertyName];
@ -482,8 +482,8 @@ ModelBaseClass.prototype.toObject = function(onlySchema, removeHidden, removePro
// If the property is not declared in the model definition, no setter will be // If the property is not declared in the model definition, no setter will be
// triggered to add it to __data // triggered to add it to __data
keys = Object.keys(self); keys = Object.keys(self);
var size = keys.length; let size = keys.length;
for (i = 0; i < size; i++) { for (let i = 0; i < size; i++) {
propertyName = keys[i]; propertyName = keys[i];
if (props[propertyName]) { if (props[propertyName]) {
continue; continue;
@ -517,7 +517,7 @@ ModelBaseClass.prototype.toObject = function(onlySchema, removeHidden, removePro
// Now continue to check __data // Now continue to check __data
keys = Object.keys(self.__data); keys = Object.keys(self.__data);
size = keys.length; size = keys.length;
for (i = 0; i < size; i++) { for (let i = 0; i < size; i++) {
propertyName = keys[i]; propertyName = keys[i];
if (propertyName.indexOf('__') === 0) { if (propertyName.indexOf('__') === 0) {
continue; continue;
@ -529,7 +529,7 @@ ModelBaseClass.prototype.toObject = function(onlySchema, removeHidden, removePro
if (removeProtected && Model.isProtectedProperty(propertyName)) { if (removeProtected && Model.isProtectedProperty(propertyName)) {
continue; continue;
} }
var ownVal = self[propertyName]; const ownVal = self[propertyName];
// The ownVal can be a relation function // The ownVal can be a relation function
val = (ownVal !== undefined && (typeof ownVal !== 'function')) ? ownVal : self.__data[propertyName]; val = (ownVal !== undefined && (typeof ownVal !== 'function')) ? ownVal : self.__data[propertyName];
if (typeof val === 'function') { if (typeof val === 'function') {
@ -555,9 +555,9 @@ ModelBaseClass.prototype.toObject = function(onlySchema, removeHidden, removePro
* @param {string[]} arr An array of strings * @param {string[]} arr An array of strings
*/ */
function asObjectMap(arr) { function asObjectMap(arr) {
var obj = {}; const obj = {};
if (Array.isArray(arr)) { if (Array.isArray(arr)) {
for (var i = 0; i < arr.length; i++) { for (let i = 0; i < arr.length; i++) {
obj[arr[i]] = true; obj[arr[i]] = true;
} }
return obj; return obj;
@ -570,8 +570,8 @@ function asObjectMap(arr) {
* @returns {Boolean} true or false if protected or not. * @returns {Boolean} true or false if protected or not.
*/ */
ModelBaseClass.isProtectedProperty = function(propertyName) { ModelBaseClass.isProtectedProperty = function(propertyName) {
var settings = (this.definition && this.definition.settings) || {}; const settings = (this.definition && this.definition.settings) || {};
var protectedProperties = settings.protectedProperties || settings.protected; const protectedProperties = settings.protectedProperties || settings.protected;
settings.protectedProperties = asObjectMap(protectedProperties); settings.protectedProperties = asObjectMap(protectedProperties);
return settings.protectedProperties[propertyName]; return settings.protectedProperties[propertyName];
}; };
@ -582,8 +582,8 @@ ModelBaseClass.isProtectedProperty = function(propertyName) {
* @returns {Boolean} true or false if hidden or not. * @returns {Boolean} true or false if hidden or not.
*/ */
ModelBaseClass.isHiddenProperty = function(propertyName) { ModelBaseClass.isHiddenProperty = function(propertyName) {
var settings = (this.definition && this.definition.settings) || {}; const settings = (this.definition && this.definition.settings) || {};
var hiddenProperties = settings.hiddenProperties || settings.hidden; const hiddenProperties = settings.hiddenProperties || settings.hidden;
settings.hiddenProperties = asObjectMap(hiddenProperties); settings.hiddenProperties = asObjectMap(hiddenProperties);
return settings.hiddenProperties[propertyName]; return settings.hiddenProperties[propertyName];
}; };
@ -593,7 +593,7 @@ ModelBaseClass.prototype.toJSON = function() {
}; };
ModelBaseClass.prototype.fromObject = function(obj) { ModelBaseClass.prototype.fromObject = function(obj) {
for (var key in obj) { for (const key in obj) {
this[key] = obj[key]; this[key] = obj[key];
} }
}; };
@ -604,8 +604,8 @@ ModelBaseClass.prototype.fromObject = function(obj) {
* initial state. * initial state.
*/ */
ModelBaseClass.prototype.reset = function() { ModelBaseClass.prototype.reset = function() {
var obj = this; const obj = this;
for (var k in obj) { for (const k in obj) {
if (k !== 'id' && !obj.constructor.dataSource.definitions[obj.constructor.modelName].properties[k]) { if (k !== 'id' && !obj.constructor.dataSource.definitions[obj.constructor.modelName].properties[k]) {
delete obj[k]; delete obj[k];
} }
@ -615,11 +615,11 @@ ModelBaseClass.prototype.reset = function() {
// Node v0.11+ allows custom inspect functions to return an object // Node v0.11+ allows custom inspect functions to return an object
// instead of string. That way options like `showHidden` and `colors` // instead of string. That way options like `showHidden` and `colors`
// can be preserved. // 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; }) : process.versions.node.split(/\./g).map(function(v) { return +v; }) :
[1, 0, 0]; // browserify ships 1.0-compatible version of util.inspect [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[0] > 0 ||
versionParts[1] > 11 || versionParts[1] > 11 ||
(versionParts[0] === 11 && versionParts[1] >= 14); (versionParts[0] === 11 && versionParts[1] >= 14);
@ -648,8 +648,8 @@ ModelBaseClass.mixin = function(anotherClass, options) {
this.modelBuilder.mixins.applyMixin(this, anotherClass, options); this.modelBuilder.mixins.applyMixin(this, anotherClass, options);
} else { } else {
if (anotherClass.prototype instanceof ModelBaseClass) { if (anotherClass.prototype instanceof ModelBaseClass) {
var props = anotherClass.definition.properties; const props = anotherClass.definition.properties;
for (var i in props) { for (const i in props) {
if (this.definition.properties[i]) { if (this.definition.properties[i]) {
continue; continue;
} }
@ -780,7 +780,7 @@ ModelBaseClass.getMergePolicy = function(options) {
// + fix for description arrays that should not be merged // + fix for description arrays that should not be merged
// + fix for relations that should patch matching relations // + fix for relations that should patch matching relations
// + ranking of ACLs // + ranking of ACLs
var mergePolicy = { let mergePolicy = {
description: {replace: true}, // string or array description: {replace: true}, // string or array
properties: {patch: true}, // object properties: {patch: true}, // object
hidden: {replace: false}, // array hidden: {replace: false}, // array
@ -789,7 +789,7 @@ ModelBaseClass.getMergePolicy = function(options) {
acls: {rank: true}, // array acls: {rank: true}, // array
}; };
var config = (options || {}).configureModelMerge; const config = (options || {}).configureModelMerge;
if (config === true) { if (config === true) {
// NOTE: recommended merge policy from datasource-juggler v3.6.2 // 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 // License text available at https://opensource.org/licenses/MIT
'use strict'; 'use strict';
var async = require('async'); const async = require('async');
var utils = require('./utils'); const utils = require('./utils');
module.exports = ObserverMixin; module.exports = ObserverMixin;
@ -74,7 +74,7 @@ ObserverMixin.observe = function(operation, listener) {
ObserverMixin.removeObserver = function(operation, listener) { ObserverMixin.removeObserver = function(operation, listener) {
if (!(this._observers && this._observers[operation])) return; if (!(this._observers && this._observers[operation])) return;
var index = this._observers[operation].indexOf(listener); const index = this._observers[operation].indexOf(listener);
if (index !== -1) { if (index !== -1) {
return this._observers[operation].splice(index, 1); return this._observers[operation].splice(index, 1);
} }
@ -127,7 +127,7 @@ ObserverMixin.clearObservers = function(operation) {
* have finished. * have finished.
*/ */
ObserverMixin.notifyObserversOf = function(operation, context, callback) { ObserverMixin.notifyObserversOf = function(operation, context, callback) {
var self = this; const self = this;
if (!callback) callback = utils.createPromiseCallback(); if (!callback) callback = utils.createPromiseCallback();
function createNotifier(op) { function createNotifier(op) {
@ -141,14 +141,14 @@ ObserverMixin.notifyObserversOf = function(operation, context, callback) {
} }
if (Array.isArray(operation)) { if (Array.isArray(operation)) {
var tasks = []; const tasks = [];
for (var i = 0, n = operation.length; i < n; i++) { for (let i = 0, n = operation.length; i < n; i++) {
tasks.push(createNotifier(operation[i])); tasks.push(createNotifier(operation[i]));
} }
return async.waterfall(tasks, callback); 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) { this._notifyBaseObservers(operation, context, function doNotify(err) {
if (err) return callback(err, context); if (err) return callback(err, context);
@ -157,7 +157,7 @@ ObserverMixin.notifyObserversOf = function(operation, context, callback) {
async.eachSeries( async.eachSeries(
observers, observers,
function notifySingleObserver(fn, next) { function notifySingleObserver(fn, next) {
var retval = fn(context, next); const retval = fn(context, next);
if (retval && typeof retval.then === 'function') { if (retval && typeof retval.then === 'function') {
retval.then( retval.then(
function() { next(); return null; }, function() { next(); return null; },
@ -217,7 +217,7 @@ ObserverMixin._notifyBaseObservers = function(operation, context, callback) {
* @returns {*} * @returns {*}
*/ */
ObserverMixin.notifyObserversAround = function(operation, context, fn, callback) { ObserverMixin.notifyObserversAround = function(operation, context, fn, callback) {
var self = this; const self = this;
context = context || {}; context = context || {};
// Add callback to the context object so that an observer can skip other // Add callback to the context object so that an observer can skip other
// ones by calling the callback function directly and not calling next // 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); if (err) return callback(err);
function cbForWork(err) { function cbForWork(err) {
var args = [].slice.call(arguments, 0); const args = [].slice.call(arguments, 0);
if (err) return callback.apply(null, args); if (err) return callback.apply(null, args);
// Find the list of params from the callback in addition to err // 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 // Set up the array of results
context.results = returnedArgs; context.results = returnedArgs;
// Notify after observers // Notify after observers
self.notifyObserversOf('after ' + operation, context, self.notifyObserversOf('after ' + operation, context,
function(err, context) { function(err, context) {
if (err) return callback(err, context); if (err) return callback(err, context);
var results = returnedArgs; let results = returnedArgs;
if (context && Array.isArray(context.results)) { if (context && Array.isArray(context.results)) {
// Pickup the results from context // Pickup the results from context
results = context.results; results = context.results;
} }
// Build the list of params for final callback // Build the list of params for final callback
var args = [err].concat(results); const args = [err].concat(results);
callback.apply(null, args); callback.apply(null, args);
}); });
} }

File diff suppressed because it is too large Load Diff

View File

@ -7,8 +7,8 @@
/*! /*!
* Dependencies * Dependencies
*/ */
var relation = require('./relation-definition'); const relation = require('./relation-definition');
var RelationDefinition = relation.RelationDefinition; const RelationDefinition = relation.RelationDefinition;
module.exports = RelationMixin; module.exports = RelationMixin;

View File

@ -4,17 +4,17 @@
// License text available at https://opensource.org/licenses/MIT // License text available at https://opensource.org/licenses/MIT
'use strict'; 'use strict';
var _ = require('lodash'); const _ = require('lodash');
var i8n = require('inflection'); const i8n = require('inflection');
var g = require('strong-globalize')(); const g = require('strong-globalize')();
var utils = require('./utils'); const utils = require('./utils');
var defineCachedRelations = utils.defineCachedRelations; const defineCachedRelations = utils.defineCachedRelations;
var setScopeValuesFromWhere = utils.setScopeValuesFromWhere; const setScopeValuesFromWhere = utils.setScopeValuesFromWhere;
var mergeQuery = utils.mergeQuery; const mergeQuery = utils.mergeQuery;
var DefaultModelBaseClass = require('./model.js'); const DefaultModelBaseClass = require('./model.js');
var collectTargetIds = utils.collectTargetIds; const collectTargetIds = utils.collectTargetIds;
var idName = utils.idName; const idName = utils.idName;
var deprecated = require('depd')('loopback-datasource-juggler'); const deprecated = require('depd')('loopback-datasource-juggler');
/** /**
* Module exports * Module exports
@ -32,14 +32,14 @@ function ScopeDefinition(definition) {
} }
ScopeDefinition.prototype.targetModel = function(receiver) { ScopeDefinition.prototype.targetModel = function(receiver) {
var modelTo; let modelTo;
if (typeof this.options.modelTo === 'function') { if (typeof this.options.modelTo === 'function') {
modelTo = this.options.modelTo.call(this, receiver) || this.modelTo; modelTo = this.options.modelTo.call(this, receiver) || this.modelTo;
} else { } else {
modelTo = this.modelTo; modelTo = this.modelTo;
} }
if (!(modelTo.prototype instanceof DefaultModelBaseClass)) { 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 ? this.modelFrom : this.modelFrom.constructor).modelName;
msg += this.isStatic ? '.' : '.prototype.'; msg += this.isStatic ? '.' : '.prototype.';
msg += this.name + '`.'; msg += this.name + '`.';
@ -58,12 +58,12 @@ ScopeDefinition.prototype.targetModel = function(receiver) {
* @returns {*} * @returns {*}
*/ */
ScopeDefinition.prototype.related = function(receiver, scopeParams, condOrRefresh, options, cb) { ScopeDefinition.prototype.related = function(receiver, scopeParams, condOrRefresh, options, cb) {
var name = this.name; const name = this.name;
var self = receiver; const self = receiver;
var actualCond = {}; let actualCond = {};
var actualRefresh = false; let actualRefresh = false;
var saveOnCache = receiver instanceof DefaultModelBaseClass; let saveOnCache = receiver instanceof DefaultModelBaseClass;
if (typeof condOrRefresh === 'function' && if (typeof condOrRefresh === 'function' &&
options === undefined && cb === undefined) { options === undefined && cb === undefined) {
// related(receiver, scopeParams, cb) // related(receiver, scopeParams, cb)
@ -90,19 +90,20 @@ ScopeDefinition.prototype.related = function(receiver, scopeParams, condOrRefres
actualRefresh; actualRefresh;
if (refreshIsNeeded) { if (refreshIsNeeded) {
// It either doesn't hit the cache or refresh is required // It either doesn't hit the cache or refresh is required
var params = mergeQuery(actualCond, scopeParams, {nestedInclude: true}); const params = mergeQuery(actualCond, scopeParams, {nestedInclude: true});
var targetModel = this.targetModel(receiver); const targetModel = this.targetModel(receiver);
// If there is a through model // If there is a through model
// run another query to apply filter on relatedModel(targetModel) // run another query to apply filter on relatedModel(targetModel)
// see github.com/strongloop/loopback-datasource-juggler/issues/166 // see github.com/strongloop/loopback-datasource-juggler/issues/166
var scopeOnRelatedModel = params.collect && const scopeOnRelatedModel = params.collect &&
params.include.scope !== null && params.include.scope !== null &&
typeof params.include.scope === 'object'; typeof params.include.scope === 'object';
let filter, queryRelated;
if (scopeOnRelatedModel) { if (scopeOnRelatedModel) {
var filter = params.include; filter = params.include;
// The filter applied on relatedModel // The filter applied on relatedModel
var queryRelated = filter.scope; queryRelated = filter.scope;
delete params.include.scope; delete params.include.scope;
} }
@ -113,18 +114,18 @@ ScopeDefinition.prototype.related = function(receiver, scopeParams, condOrRefres
} }
if (scopeOnRelatedModel === true) { if (scopeOnRelatedModel === true) {
var relatedModel = targetModel.relations[filter.relation].modelTo; const relatedModel = targetModel.relations[filter.relation].modelTo;
var IdKey = idName(relatedModel); const IdKey = idName(relatedModel);
// return {inq: [1,2,3]}} // return {inq: [1,2,3]}}
var smartMerge = function(idCollection, qWhere) { const smartMerge = function(idCollection, qWhere) {
if (!qWhere[IdKey]) return idCollection; if (!qWhere[IdKey]) return idCollection;
var merged = {}; let merged = {};
var idsA = idCollection.inq; const idsA = idCollection.inq;
var idsB = qWhere[IdKey].inq ? qWhere[IdKey].inq : [qWhere[IdKey]]; 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 = intersect[0];
if (intersect.length > 1) merged = {inq: intersect}; if (intersect.length > 1) merged = {inq: intersect};
@ -133,7 +134,7 @@ ScopeDefinition.prototype.related = function(receiver, scopeParams, condOrRefres
if (queryRelated.where !== undefined) { if (queryRelated.where !== undefined) {
// Merge queryRelated filter and targetId filter // Merge queryRelated filter and targetId filter
var IdKeyCondition = {}; const IdKeyCondition = {};
IdKeyCondition[IdKey] = smartMerge(collectTargetIds(data, IdKey), IdKeyCondition[IdKey] = smartMerge(collectTargetIds(data, IdKey),
queryRelated.where); queryRelated.where);
@ -141,7 +142,7 @@ ScopeDefinition.prototype.related = function(receiver, scopeParams, condOrRefres
// return empty result // return empty result
if (_.isObject(IdKeyCondition[IdKey]) && _.isEmpty(IdKeyCondition[IdKey])) return cb(null, []); if (_.isObject(IdKeyCondition[IdKey]) && _.isEmpty(IdKeyCondition[IdKey])) return cb(null, []);
var mergedWhere = { const mergedWhere = {
and: [ and: [
IdKeyCondition, IdKeyCondition,
_.omit(queryRelated.where, IdKey), _.omit(queryRelated.where, IdKey),
@ -201,8 +202,8 @@ function defineScope(cls, targetClass, name, params, methods, options) {
options = options || {}; options = options || {};
// Check if the cls is the class itself or its prototype // Check if the cls is the class itself or its prototype
var isStatic = (typeof cls === 'function') || options.isStatic || false; const isStatic = (typeof cls === 'function') || options.isStatic || false;
var definition = new ScopeDefinition({ const definition = new ScopeDefinition({
isStatic: isStatic, isStatic: isStatic,
modelFrom: cls, modelFrom: cls,
modelTo: targetClass, modelTo: targetClass,
@ -236,10 +237,10 @@ function defineScope(cls, targetClass, name, params, methods, options) {
* *
*/ */
get: function() { get: function() {
var targetModel = definition.targetModel(this); const targetModel = definition.targetModel(this);
var self = this; const self = this;
var f = function(condOrRefresh, options, cb) { const f = function(condOrRefresh, options, cb) {
if (arguments.length === 0) { if (arguments.length === 0) {
if (typeof f.value === 'function') { if (typeof f.value === 'function') {
return f.value(self); return f.value(self);
@ -312,7 +313,7 @@ function defineScope(cls, targetClass, name, params, methods, options) {
f.findOne = findOne; f.findOne = findOne;
f.count = count; f.count = count;
for (var i in definition.methods) { for (const i in definition.methods) {
f[i] = definition.methods[i].bind(self); f[i] = definition.methods[i].bind(self);
} }
@ -336,52 +337,52 @@ function defineScope(cls, targetClass, name, params, methods, options) {
}); });
// Wrap the property into a function for remoting // Wrap the property into a function for remoting
var fn = function() { const fn = function() {
// primaryObject.scopeName, such as user.accounts // 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 // set receiver to be the scope property whose value is a function
f.apply(this[name], arguments); f.apply(this[name], arguments);
}; };
cls['__get__' + name] = fn; cls['__get__' + name] = fn;
var fnCreate = function() { const fnCreate = function() {
var f = this[name].create; const f = this[name].create;
f.apply(this[name], arguments); f.apply(this[name], arguments);
}; };
cls['__create__' + name] = fnCreate; cls['__create__' + name] = fnCreate;
var fnDelete = function() { const fnDelete = function() {
var f = this[name].destroyAll; const f = this[name].destroyAll;
f.apply(this[name], arguments); f.apply(this[name], arguments);
}; };
cls['__delete__' + name] = fnDelete; cls['__delete__' + name] = fnDelete;
var fnUpdate = function() { const fnUpdate = function() {
var f = this[name].updateAll; const f = this[name].updateAll;
f.apply(this[name], arguments); f.apply(this[name], arguments);
}; };
cls['__update__' + name] = fnUpdate; cls['__update__' + name] = fnUpdate;
var fnFindById = function(cb) { const fnFindById = function(cb) {
var f = this[name].findById; const f = this[name].findById;
f.apply(this[name], arguments); f.apply(this[name], arguments);
}; };
cls['__findById__' + name] = fnFindById; cls['__findById__' + name] = fnFindById;
var fnFindOne = function(cb) { const fnFindOne = function(cb) {
var f = this[name].findOne; const f = this[name].findOne;
f.apply(this[name], arguments); f.apply(this[name], arguments);
}; };
cls['__findOne__' + name] = fnFindOne; cls['__findOne__' + name] = fnFindOne;
var fnCount = function(cb) { const fnCount = function(cb) {
var f = this[name].count; const f = this[name].count;
f.apply(this[name], arguments); f.apply(this[name], arguments);
}; };
@ -391,8 +392,8 @@ function defineScope(cls, targetClass, name, params, methods, options) {
function build(data) { function build(data) {
data = data || {}; data = data || {};
// Find all fixed property values for the scope // Find all fixed property values for the scope
var targetModel = definition.targetModel(this._receiver); const targetModel = definition.targetModel(this._receiver);
var where = (this._scope && this._scope.where) || {}; const where = (this._scope && this._scope.where) || {};
setScopeValuesFromWhere(data, where, targetModel); setScopeValuesFromWhere(data, where, targetModel);
return new targetModel(data); return new targetModel(data);
} }
@ -430,9 +431,9 @@ function defineScope(cls, targetClass, name, params, methods, options) {
} }
options = options || {}; options = options || {};
var targetModel = definition.targetModel(this._receiver); const targetModel = definition.targetModel(this._receiver);
var scoped = (this._scope && this._scope.where) || {}; const scoped = (this._scope && this._scope.where) || {};
var filter = mergeQuery({where: scoped}, {where: where || {}}); const filter = mergeQuery({where: scoped}, {where: where || {}});
return targetModel.destroyAll(filter.where, options, cb); return targetModel.destroyAll(filter.where, options, cb);
} }
@ -450,9 +451,9 @@ function defineScope(cls, targetClass, name, params, methods, options) {
options = {}; options = {};
} }
options = options || {}; options = options || {};
var targetModel = definition.targetModel(this._receiver); const targetModel = definition.targetModel(this._receiver);
var scoped = (this._scope && this._scope.where) || {}; const scoped = (this._scope && this._scope.where) || {};
var filter = mergeQuery({where: scoped}, {where: where || {}}); const filter = mergeQuery({where: scoped}, {where: where || {}});
return targetModel.updateAll(filter.where, data, options, cb); return targetModel.updateAll(filter.where, data, options, cb);
} }
@ -478,9 +479,9 @@ function defineScope(cls, targetClass, name, params, methods, options) {
options = options || {}; options = options || {};
filter = filter || {}; filter = filter || {};
var targetModel = definition.targetModel(this._receiver); const targetModel = definition.targetModel(this._receiver);
var idName = targetModel.definition.idName(); const idName = targetModel.definition.idName();
var query = {where: {}}; let query = {where: {}};
query.where[idName] = id; query.where[idName] = id;
query = mergeQuery(query, filter); query = mergeQuery(query, filter);
return this.findOne(query, options, cb); return this.findOne(query, options, cb);
@ -498,8 +499,8 @@ function defineScope(cls, targetClass, name, params, methods, options) {
options = {}; options = {};
} }
options = options || {}; options = options || {};
var targetModel = definition.targetModel(this._receiver); const targetModel = definition.targetModel(this._receiver);
var scoped = (this._scope && this._scope.where) || {}; const scoped = (this._scope && this._scope.where) || {};
filter = mergeQuery({where: scoped}, filter || {}); filter = mergeQuery({where: scoped}, filter || {});
return targetModel.findOne(filter, options, cb); return targetModel.findOne(filter, options, cb);
} }
@ -516,9 +517,9 @@ function defineScope(cls, targetClass, name, params, methods, options) {
} }
options = options || {}; options = options || {};
var targetModel = definition.targetModel(this._receiver); const targetModel = definition.targetModel(this._receiver);
var scoped = (this._scope && this._scope.where) || {}; const scoped = (this._scope && this._scope.where) || {};
var filter = mergeQuery({where: scoped}, {where: where || {}}); const filter = mergeQuery({where: scoped}, {where: where || {}});
return targetModel.count(filter.where, options, cb); return targetModel.count(filter.where, options, cb);
} }

View File

@ -4,14 +4,14 @@
// License text available at https://opensource.org/licenses/MIT // License text available at https://opensource.org/licenses/MIT
'use strict'; 'use strict';
var g = require('strong-globalize')(); const g = require('strong-globalize')();
var debug = require('debug')('loopback:connector:transaction'); const debug = require('debug')('loopback:connector:transaction');
var uuid = require('uuid'); const uuid = require('uuid');
var utils = require('./utils'); const utils = require('./utils');
var jutil = require('./jutil'); const jutil = require('./jutil');
var ObserverMixin = require('./observer'); const ObserverMixin = require('./observer');
var Transaction = require('loopback-connector').Transaction; const Transaction = require('loopback-connector').Transaction;
module.exports = TransactionMixin; module.exports = TransactionMixin;
@ -73,7 +73,7 @@ function TransactionMixin() {
TransactionMixin.beginTransaction = function(options, cb) { TransactionMixin.beginTransaction = function(options, cb) {
cb = cb || utils.createPromiseCallback(); cb = cb || utils.createPromiseCallback();
if (Transaction) { if (Transaction) {
var connector = this.getConnector(); const connector = this.getConnector();
Transaction.begin(connector, options, function(err, transaction) { Transaction.begin(connector, options, function(err, transaction) {
if (err) return cb(err); if (err) return cb(err);
// NOTE(lehni) As part of the process of moving the handling of // 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) { if (options.timeout && !transaction.timeout) {
transaction.timeout = setTimeout(function() { transaction.timeout = setTimeout(function() {
var context = { const context = {
transaction: transaction, transaction: transaction,
operation: 'timeout', operation: 'timeout',
}; };
@ -105,7 +105,7 @@ TransactionMixin.beginTransaction = function(options, cb) {
}); });
} else { } else {
process.nextTick(function() { 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); cb(err);
}); });
} }
@ -136,7 +136,7 @@ if (Transaction) {
Transaction.prototype.commit = function(cb) { Transaction.prototype.commit = function(cb) {
cb = cb || utils.createPromiseCallback(); cb = cb || utils.createPromiseCallback();
if (this.ensureActive(cb)) { if (this.ensureActive(cb)) {
var context = { const context = {
transaction: this, transaction: this,
operation: 'commit', operation: 'commit',
}; };
@ -175,7 +175,7 @@ if (Transaction) {
Transaction.prototype.rollback = function(cb) { Transaction.prototype.rollback = function(cb) {
cb = cb || utils.createPromiseCallback(); cb = cb || utils.createPromiseCallback();
if (this.ensureActive(cb)) { if (this.ensureActive(cb)) {
var context = { const context = {
transaction: this, transaction: this,
operation: 'rollback', operation: 'rollback',
}; };

View File

@ -4,7 +4,7 @@
// License text available at https://opensource.org/licenses/MIT // License text available at https://opensource.org/licenses/MIT
'use strict'; 'use strict';
var Types = {}; const Types = {};
/** /**
* Schema types * Schema types
*/ */
@ -40,10 +40,10 @@ Types.Any.prototype.toObject = Types.Any.prototype.toJSON = function() {
}; };
module.exports = function(modelTypes) { module.exports = function(modelTypes) {
var DateString = require('./date-string'); const DateString = require('./date-string');
var GeoPoint = require('./geo').GeoPoint; const GeoPoint = require('./geo').GeoPoint;
for (var t in Types) { for (const t in Types) {
modelTypes[t] = Types[t]; modelTypes[t] = Types[t];
} }
@ -51,7 +51,7 @@ module.exports = function(modelTypes) {
modelTypes.registerType = function(type, names) { modelTypes.registerType = function(type, names) {
names = names || []; names = names || [];
names = names.concat([type.name]); 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; this.schemaTypes[names[n].toLowerCase()] = type;
} }
}; };

View File

@ -28,10 +28,10 @@ exports.idName = idName;
exports.rankArrayElements = rankArrayElements; exports.rankArrayElements = rankArrayElements;
exports.idsHaveDuplicates = idsHaveDuplicates; exports.idsHaveDuplicates = idsHaveDuplicates;
var g = require('strong-globalize')(); const g = require('strong-globalize')();
var traverse = require('traverse'); const traverse = require('traverse');
var assert = require('assert'); const assert = require('assert');
var debug = require('debug')('loopback:juggler:utils'); const debug = require('debug')('loopback:juggler:utils');
function safeRequire(module) { function safeRequire(module) {
try { try {
@ -52,17 +52,17 @@ function safeRequire(module) {
* @param {Object} The where clause * @param {Object} The where clause
*/ */
function setScopeValuesFromWhere(data, where, targetModel) { function setScopeValuesFromWhere(data, where, targetModel) {
for (var i in where) { for (const i in where) {
if (i === 'and') { if (i === 'and') {
// Find fixed property values from each subclauses // 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); setScopeValuesFromWhere(data, where[i][w], targetModel);
} }
continue; continue;
} }
var prop = targetModel.definition.properties[i]; const prop = targetModel.definition.properties[i];
if (prop) { if (prop) {
var val = where[i]; const val = where[i];
if (typeof val !== 'object' || val instanceof prop.type || if (typeof val !== 'object' || val instanceof prop.type ||
prop.type.name === 'ObjectID' || // MongoDB key prop.type.name === 'ObjectID' || // MongoDB key
prop.type.name === 'uuidFromString') { // C* prop.type.name === 'uuidFromString') { // C*
@ -82,26 +82,26 @@ function setScopeValuesFromWhere(data, where, targetModel) {
* @returns {Object} * @returns {Object}
*/ */
function mergeIncludes(destination, source) { function mergeIncludes(destination, source) {
var destArray = convertToArray(destination); const destArray = convertToArray(destination);
var sourceArray = convertToArray(source); const sourceArray = convertToArray(source);
if (destArray.length === 0) { if (destArray.length === 0) {
return sourceArray; return sourceArray;
} }
if (sourceArray.length === 0) { if (sourceArray.length === 0) {
return destArray; return destArray;
} }
var relationNames = []; const relationNames = [];
var resultArray = []; const resultArray = [];
for (var j in sourceArray) { for (const j in sourceArray) {
var sourceEntry = sourceArray[j]; const sourceEntry = sourceArray[j];
var sourceEntryRelationName = (typeof (sourceEntry.rel || sourceEntry.relation) === 'string') ? const sourceEntryRelationName = (typeof (sourceEntry.rel || sourceEntry.relation) === 'string') ?
sourceEntry.relation : Object.keys(sourceEntry)[0]; sourceEntry.relation : Object.keys(sourceEntry)[0];
relationNames.push(sourceEntryRelationName); relationNames.push(sourceEntryRelationName);
resultArray.push(sourceEntry); resultArray.push(sourceEntry);
} }
for (var i in destArray) { for (const i in destArray) {
var destEntry = destArray[i]; const destEntry = destArray[i];
var destEntryRelationName = (typeof (destEntry.rel || destEntry.relation) === 'string') ? const destEntryRelationName = (typeof (destEntry.rel || destEntry.relation) === 'string') ?
destEntry.relation : Object.keys(destEntry)[0]; destEntry.relation : Object.keys(destEntry)[0];
if (relationNames.indexOf(destEntryRelationName) === -1) { if (relationNames.indexOf(destEntryRelationName) === -1) {
resultArray.push(destEntry); resultArray.push(destEntry);
@ -129,17 +129,17 @@ function convertToArray(include) {
return [include]; return [include];
} }
// Build an array of key/value pairs // Build an array of key/value pairs
var newInclude = []; const newInclude = [];
for (var key in include) { for (const key in include) {
const obj = {}; const obj = {};
obj[key] = include[key]; obj[key] = include[key];
newInclude.push(obj); newInclude.push(obj);
} }
return newInclude; return newInclude;
} else if (Array.isArray(include)) { } else if (Array.isArray(include)) {
var normalized = []; const normalized = [];
for (var i in include) { for (const i in include) {
var includeEntry = include[i]; const includeEntry = include[i];
if (typeof includeEntry === 'string') { if (typeof includeEntry === 'string') {
const obj = {}; const obj = {};
obj[includeEntry] = true; obj[includeEntry] = true;
@ -185,7 +185,7 @@ function mergeQuery(base, update, spec) {
// specify nestedInclude=true to force nesting of inclusions on scoped // specify nestedInclude=true to force nesting of inclusions on scoped
// queries. e.g. In physician.patients.find({include: 'address'}), // queries. e.g. In physician.patients.find({include: 'address'}),
// inclusion should be on patient model, not on physician model. // inclusion should be on patient model, not on physician model.
var saved = base.include; const saved = base.include;
base.include = {}; base.include = {};
base.include[update.include] = saved; base.include[update.include] = saved;
} else { } else {
@ -217,7 +217,7 @@ function mergeQuery(base, update, spec) {
base.limit = update.limit; 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) { if (skip && update.skip !== undefined) {
base.skip = update.skip; base.skip = update.skip;
@ -241,8 +241,8 @@ function fieldsToArray(fields, properties, excludeUnknown) {
if (!fields) return; if (!fields) return;
// include all properties by default // include all properties by default
var result = properties; let result = properties;
var i, n; let i, n;
if (typeof fields === 'string') { if (typeof fields === 'string') {
result = [fields]; result = [fields];
@ -251,13 +251,13 @@ function fieldsToArray(fields, properties, excludeUnknown) {
result = fields; result = fields;
} else if ('object' === typeof fields) { } else if ('object' === typeof fields) {
// { field1: boolean, field2: boolean ... } // { field1: boolean, field2: boolean ... }
var included = []; const included = [];
var excluded = []; const excluded = [];
var keys = Object.keys(fields); const keys = Object.keys(fields);
if (!keys.length) return; if (!keys.length) return;
for (i = 0, n = keys.length; i < n; i++) { for (i = 0, n = keys.length; i < n; i++) {
var k = keys[i]; const k = keys[i];
if (fields[k]) { if (fields[k]) {
included.push(k); included.push(k);
} else if ((k in fields) && !fields[k]) { } else if ((k in fields) && !fields[k]) {
@ -268,13 +268,13 @@ function fieldsToArray(fields, properties, excludeUnknown) {
result = included; result = included;
} else if (excluded.length > 0) { } else if (excluded.length > 0) {
for (i = 0, n = excluded.length; i < n; i++) { 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 if (index !== -1) result.splice(index, 1); // only when existing field excluded
} }
} }
} }
var fieldArray = []; let fieldArray = [];
if (excludeUnknown) { if (excludeUnknown) {
for (i = 0, n = result.length; i < n; i++) { for (i = 0, n = result.length; i < n; i++) {
if (properties.indexOf(result[i]) !== -1) { if (properties.indexOf(result[i]) !== -1) {
@ -290,10 +290,10 @@ function fieldsToArray(fields, properties, excludeUnknown) {
function selectFields(fields) { function selectFields(fields) {
// map function // map function
return function(obj) { return function(obj) {
var result = {}; const result = {};
var key; let key;
for (var i = 0; i < fields.length; i++) { for (let i = 0; i < fields.length; i++) {
key = fields[i]; key = fields[i];
result[key] = obj[key]; result[key] = obj[key];
@ -307,7 +307,7 @@ function isProhibited(key, prohibitedKeys) {
if (typeof key !== 'string') { if (typeof key !== 'string') {
return false; return false;
} }
for (var k of prohibitedKeys) { for (const k of prohibitedKeys) {
if (k === key) return true; if (k === key) return true;
// x.secret, secret.y, or x.secret.y // x.secret, secret.y, or x.secret.y
if (key.split('.').indexOf(k) !== -1) return true; if (key.split('.').indexOf(k) !== -1) return true;
@ -416,8 +416,8 @@ function parseSettings(urlStr) {
if (!urlStr) { if (!urlStr) {
return {}; return {};
} }
var uri = url.parse(urlStr, false); const uri = url.parse(urlStr, false);
var settings = {}; const settings = {};
settings.connector = uri.protocol && uri.protocol.split(':')[0]; // Remove the trailing : settings.connector = uri.protocol && uri.protocol.split(':')[0]; // Remove the trailing :
settings.host = settings.hostname = uri.hostname; settings.host = settings.hostname = uri.hostname;
settings.port = uri.port && Number(uri.port); // port is a string 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.database = uri.pathname && uri.pathname.split('/')[1]; // remove the leading /
settings.url = urlStr; settings.url = urlStr;
if (uri.query) { if (uri.query) {
var params = qs.parse(uri.query); const params = qs.parse(uri.query);
for (var p in params) { for (const p in params) {
settings[p] = params[p]; settings[p] = params[p];
} }
} }
@ -451,8 +451,8 @@ function parseSettings(urlStr) {
*/ */
function deepMerge(base, extras) { function deepMerge(base, extras) {
// deepMerge allows undefined extras to allow deep cloning of arrays // deepMerge allows undefined extras to allow deep cloning of arrays
var array = Array.isArray(base) && (Array.isArray(extras) || !extras); const array = Array.isArray(base) && (Array.isArray(extras) || !extras);
var dst = array && [] || {}; let dst = array && [] || {};
if (array) { if (array) {
// extras or base is an array // extras or base is an array
@ -480,7 +480,7 @@ function deepMerge(base, extras) {
if (extras != null && typeof extras === 'object') { if (extras != null && typeof extras === 'object') {
// extras is an object {} // extras is an object {}
Object.keys(extras).forEach(function(key) { Object.keys(extras).forEach(function(key) {
var extra = extras[key]; const extra = extras[key];
if (extra == null || typeof extra !== 'object') { if (extra == null || typeof extra !== 'object') {
// extra item value is null, undefined or not an object // extra item value is null, undefined or not an object
dst[key] = extra; dst[key] = extra;
@ -511,8 +511,8 @@ function deepMerge(base, extras) {
* @returns {Object} The merged property * @returns {Object} The merged property
*/ */
function deepMergeProperty(base, extras) { function deepMergeProperty(base, extras) {
let mergedObject = deepMerge({key: base}, {key: extras}); const mergedObject = deepMerge({key: base}, {key: extras});
let mergedProperty = mergedObject.key; const mergedProperty = mergedObject.key;
return mergedProperty; return mergedProperty;
} }
@ -583,26 +583,26 @@ function sortObjectsByIds(idName, ids, objects, strict) {
return (typeof id === 'object') ? String(id) : id; return (typeof id === 'object') ? String(id) : id;
}); });
var indexOf = function(x) { const indexOf = function(x) {
var isObj = (typeof x[idName] === 'object'); // ObjectID const isObj = (typeof x[idName] === 'object'); // ObjectID
var id = isObj ? String(x[idName]) : x[idName]; const id = isObj ? String(x[idName]) : x[idName];
return ids.indexOf(id); return ids.indexOf(id);
}; };
var heading = []; const heading = [];
var tailing = []; const tailing = [];
objects.forEach(function(x) { objects.forEach(function(x) {
if (typeof x === 'object') { if (typeof x === 'object') {
var idx = indexOf(x); const idx = indexOf(x);
if (strict && idx === -1) return; if (strict && idx === -1) return;
idx === -1 ? tailing.push(x) : heading.push(x); idx === -1 ? tailing.push(x) : heading.push(x);
} }
}); });
heading.sort(function(x, y) { heading.sort(function(x, y) {
var a = indexOf(x); const a = indexOf(x);
var b = indexOf(y); const b = indexOf(y);
if (a === -1 || b === -1) return 1; // last if (a === -1 || b === -1) return 1; // last
if (a === b) return 0; if (a === b) return 0;
if (a > b) return 1; if (a > b) return 1;
@ -613,8 +613,8 @@ function sortObjectsByIds(idName, ids, objects, strict) {
} }
function createPromiseCallback() { function createPromiseCallback() {
var cb; let cb;
var promise = new Promise(function(resolve, reject) { const promise = new Promise(function(resolve, reject) {
cb = function(err, data) { cb = function(err, data) {
if (err) return reject(err); if (err) return reject(err);
return resolve(data); return resolve(data);
@ -636,15 +636,15 @@ function isBsonType(value) {
* @returns {Array} an array with unique items * @returns {Array} an array with unique items
*/ */
function uniq(a) { function uniq(a) {
var uniqArray = []; const uniqArray = [];
if (!a) { if (!a) {
return uniqArray; return uniqArray;
} }
assert(Array.isArray(a), 'array argument is required'); assert(Array.isArray(a), 'array argument is required');
var comparableA = a.map( const comparableA = a.map(
item => isBsonType(item) ? item.toString() : item item => isBsonType(item) ? item.toString() : item
); );
for (var i = 0, n = comparableA.length; i < n; i++) { for (let i = 0, n = comparableA.length; i < n; i++) {
if (comparableA.indexOf(comparableA[i]) === i) { if (comparableA.indexOf(comparableA[i]) === i) {
uniqArray.push(a[i]); uniqArray.push(a[i]);
} }
@ -658,8 +658,8 @@ function uniq(a) {
* @returns {Object} A RegExp object * @returns {Object} A RegExp object
*/ */
function toRegExp(regex) { function toRegExp(regex) {
var isString = typeof regex === 'string'; const isString = typeof regex === 'string';
var isRegExp = regex instanceof RegExp; const isRegExp = regex instanceof RegExp;
if (!(isString || isRegExp)) if (!(isString || isRegExp))
return new Error(g.f('Invalid argument, must be a string, {{regex}} literal, or ' + return new Error(g.f('Invalid argument, must be a string, {{regex}} literal, or ' +
@ -672,20 +672,20 @@ function toRegExp(regex) {
return new RegExp(regex); return new RegExp(regex);
// only accept i, g, or m as valid regex flags // only accept i, g, or m as valid regex flags
var flags = regex.split('/').pop().split(''); const flags = regex.split('/').pop().split('');
var validFlags = ['i', 'g', 'm']; const validFlags = ['i', 'g', 'm'];
var invalidFlags = []; const invalidFlags = [];
flags.forEach(function(flag) { flags.forEach(function(flag) {
if (validFlags.indexOf(flag) === -1) if (validFlags.indexOf(flag) === -1)
invalidFlags.push(flag); invalidFlags.push(flag);
}); });
var hasInvalidFlags = invalidFlags.length > 0; const hasInvalidFlags = invalidFlags.length > 0;
if (hasInvalidFlags) if (hasInvalidFlags)
return new Error(g.f('Invalid {{regex}} flags: %s', invalidFlags)); return new Error(g.f('Invalid {{regex}} flags: %s', invalidFlags));
// strip regex delimiter forward slashes // 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('')); return new RegExp(expression, flags.join(''));
} }
@ -723,7 +723,7 @@ function findIndexOf(arr, target, isEqual) {
return arr.indexOf(target); 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; } if (isEqual(arr[i], target)) { return i; }
} }
@ -737,12 +737,12 @@ function findIndexOf(arr, target, isEqual) {
* @returns {Object} The object that queries targetIds * @returns {Object} The object that queries targetIds
*/ */
function collectTargetIds(targetData, idPropertyName) { function collectTargetIds(targetData, idPropertyName) {
var targetIds = []; const targetIds = [];
for (var i = 0; i < targetData.length; i++) { for (let i = 0; i < targetData.length; i++) {
var targetId = targetData[i][idPropertyName]; const targetId = targetData[i][idPropertyName];
targetIds.push(targetId); targetIds.push(targetId);
} }
var IdQuery = { const IdQuery = {
inq: uniq(targetIds), inq: uniq(targetIds),
}; };
return IdQuery; return IdQuery;
@ -765,12 +765,12 @@ function idName(m) {
*/ */
function idsHaveDuplicates(ids) { function idsHaveDuplicates(ids) {
// use Set if available and all ids are of string or number type // use Set if available and all ids are of string or number type
var hasDuplicates = undefined; let hasDuplicates = undefined;
var i, j; let i, j;
if (typeof Set === 'function') { if (typeof Set === 'function') {
var uniqueIds = new Set(); const uniqueIds = new Set();
for (i = 0; i < ids.length; ++i) { for (i = 0; i < ids.length; ++i) {
var idType = typeof ids[i]; const idType = typeof ids[i];
if (idType === 'string' || idType === 'number') { if (idType === 'string' || idType === 'number') {
if (uniqueIds.has(ids[i])) { if (uniqueIds.has(ids[i])) {
hasDuplicates = true; hasDuplicates = true;

View File

@ -5,9 +5,9 @@
'use strict'; 'use strict';
var g = require('strong-globalize')(); const g = require('strong-globalize')();
var util = require('util'); const util = require('util');
var extend = util._extend; const extend = util._extend;
/*! /*!
* Module exports * Module exports
@ -307,7 +307,7 @@ function validateAbsence(attr, conf, err, options) {
function validateLength(attr, conf, err, options) { function validateLength(attr, conf, err, options) {
if (nullCheck.call(this, attr, conf, err)) return; if (nullCheck.call(this, attr, conf, err)) return;
var len = this[attr].length; const len = this[attr].length;
if (conf.min && len < conf.min) { if (conf.min && len < conf.min) {
err('min'); err('min');
} }
@ -362,7 +362,7 @@ function validateFormat(attr, conf, err, options) {
if (nullCheck.call(this, attr, conf, err)) return; if (nullCheck.call(this, attr, conf, err)) return;
if (typeof this[attr] === 'string' || typeof this[attr] === 'number') { 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])) { if (!regex.test(this[attr])) {
err(); err();
} }
@ -397,7 +397,7 @@ function escapeStringRegexp(str) {
if (typeof str !== 'string') { if (typeof str !== 'string') {
throw new TypeError('Expected a string'); throw new TypeError('Expected a string');
} }
var matchOperatorsRe = /[|\\{}()[\]^$+*?.]/g; const matchOperatorsRe = /[|\\{}()[\]^$+*?.]/g;
return str.replace(matchOperatorsRe, '\\$&'); return str.replace(matchOperatorsRe, '\\$&');
} }
@ -412,7 +412,7 @@ function validateUniqueness(attr, conf, err, options, done) {
if (blank(this[attr])) { if (blank(this[attr])) {
return process.nextTick(done); return process.nextTick(done);
} }
var cond = {where: {}}; const cond = {where: {}};
if (conf && conf.ignoreCase) { if (conf && conf.ignoreCase) {
cond.where[attr] = new RegExp('^' + escapeStringRegexp(this[attr]) + '$', 'i'); cond.where[attr] = new RegExp('^' + escapeStringRegexp(this[attr]) + '$', 'i');
@ -422,14 +422,14 @@ function validateUniqueness(attr, conf, err, options, done) {
if (conf && conf.scopedTo) { if (conf && conf.scopedTo) {
conf.scopedTo.forEach(function(k) { conf.scopedTo.forEach(function(k) {
var val = this[k]; const val = this[k];
if (val !== undefined) if (val !== undefined)
cond.where[k] = this[k]; cond.where[k] = this[k];
}, this); }, this);
} }
var idName = this.constructor.definition.idName(); const idName = this.constructor.definition.idName();
var isNewRecord = this.isNewRecord(); const isNewRecord = this.isNewRecord();
this.constructor.find(cond, options, function(error, found) { this.constructor.find(cond, options, function(error, found) {
if (error) { if (error) {
err(error); err(error);
@ -452,11 +452,11 @@ function validateUniqueness(attr, conf, err, options, done) {
function validateDate(attr, conf, err) { function validateDate(attr, conf, err) {
if (this[attr] === null || this[attr] === undefined) return; 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(); if (isNaN(date.getTime())) return err();
} }
var validators = { const validators = {
presence: validatePresence, presence: validatePresence,
absence: validateAbsence, absence: validateAbsence,
length: validateLength, length: validateLength,
@ -471,7 +471,7 @@ var validators = {
function getConfigurator(name, opts) { function getConfigurator(name, opts) {
return function() { return function() {
var args = Array.prototype.slice.call(arguments); const args = Array.prototype.slice.call(arguments);
args[1] = args[1] || {}; args[1] = args[1] || {};
configure(this, name, args, opts); configure(this, name, args, opts);
}; };
@ -513,10 +513,11 @@ function getConfigurator(name, opts) {
*/ */
Validatable.prototype.isValid = function(callback, data, options) { Validatable.prototype.isValid = function(callback, data, options) {
options = options || {}; options = options || {};
var valid = true, inst = this, wait = 0, async = false; let valid = true, wait = 0, async = false;
var validations = this.constructor.validations; const inst = this;
const validations = this.constructor.validations;
var reportDiscardedProperties = this.__strict && const reportDiscardedProperties = this.__strict &&
this.__unknownProperties && this.__unknownProperties.length; this.__unknownProperties && this.__unknownProperties.length;
// exit with success when no errors // exit with success when no errors
@ -539,13 +540,13 @@ Validatable.prototype.isValid = function(callback, data, options) {
}); });
this.trigger('validate', function(validationsDone) { this.trigger('validate', function(validationsDone) {
var inst = this, const inst = this;
asyncFail = false; let asyncFail = false;
var attrs = Object.keys(validations || {}); const attrs = Object.keys(validations || {});
attrs.forEach(function(attr) { attrs.forEach(function(attr) {
var attrValidations = validations[attr] || []; const attrValidations = validations[attr] || [];
attrValidations.forEach(function(v) { attrValidations.forEach(function(v) {
if (v.options && v.options.async) { if (v.options && v.options.async) {
async = true; async = true;
@ -562,10 +563,10 @@ Validatable.prototype.isValid = function(callback, data, options) {
}); });
if (reportDiscardedProperties) { if (reportDiscardedProperties) {
for (var ix in inst.__unknownProperties) { for (const ix in inst.__unknownProperties) {
var key = inst.__unknownProperties[ix]; const key = inst.__unknownProperties[ix];
var code = 'unknown-property'; const code = 'unknown-property';
var msg = defaultMessages[code]; const msg = defaultMessages[code];
inst.errors.add(key, msg, code); inst.errors.add(key, msg, code);
valid = false; valid = false;
} }
@ -611,7 +612,7 @@ function cleanErrors(inst) {
} }
function validationFailed(inst, attr, conf, options, cb) { function validationFailed(inst, attr, conf, options, cb) {
var opts = conf.options || {}; const opts = conf.options || {};
if (typeof options === 'function') { if (typeof options === 'function') {
cb = options; cb = options;
@ -628,13 +629,13 @@ function validationFailed(inst, attr, conf, options, cb) {
return false; return false;
} }
var fail = false; let fail = false;
var validator = validators[conf.validation]; const validator = validators[conf.validation];
var validatorArguments = []; const validatorArguments = [];
validatorArguments.push(attr); validatorArguments.push(attr);
validatorArguments.push(conf); validatorArguments.push(conf);
validatorArguments.push(function onerror(kind) { validatorArguments.push(function onerror(kind) {
var message, code = conf.code || conf.validation; let message, code = conf.code || conf.validation;
if (conf.message) { if (conf.message) {
message = conf.message; message = conf.message;
} }
@ -669,7 +670,7 @@ function validationFailed(inst, attr, conf, options, cb) {
} }
function skipValidation(inst, conf, kind) { function skipValidation(inst, conf, kind) {
var doValidate = true; let doValidate = true;
if (typeof conf[kind] === 'function') { if (typeof conf[kind] === 'function') {
doValidate = conf[kind].call(inst); doValidate = conf[kind].call(inst);
if (kind === 'unless') doValidate = !doValidate; if (kind === 'unless') doValidate = !doValidate;
@ -687,7 +688,7 @@ function skipValidation(inst, conf, kind) {
return !doValidate; return !doValidate;
} }
var defaultMessages = { const defaultMessages = {
presence: 'can\'t be blank', presence: 'can\'t be blank',
absence: 'can\'t be set', absence: 'can\'t be set',
'unknown-property': 'is not defined in the model', 'unknown-property': 'is not defined in the model',
@ -764,7 +765,7 @@ function configure(cls, validation, args, opts) {
}); });
} }
args = [].slice.call(args); args = [].slice.call(args);
var conf; let conf;
if (typeof args[args.length - 1] === 'object') { if (typeof args[args.length - 1] === 'object') {
conf = args.pop(); conf = args.pop();
} else { } else {
@ -776,7 +777,7 @@ function configure(cls, validation, args, opts) {
conf.validation = validation; conf.validation = validation;
args.forEach(function(attr) { args.forEach(function(attr) {
if (typeof attr === 'string') { if (typeof attr === 'string') {
var validation = extend({}, conf); const validation = extend({}, conf);
validation.options = opts || {}; validation.options = opts || {};
cls.validations[attr] = cls.validations[attr] || []; cls.validations[attr] = cls.validations[attr] || [];
cls.validations[attr].push(validation); cls.validations[attr].push(validation);
@ -803,7 +804,7 @@ Errors.prototype.add = function(field, message, code) {
}; };
function ErrorCodes(messages) { function ErrorCodes(messages) {
var c = this; const c = this;
Object.keys(messages).forEach(function(field) { Object.keys(messages).forEach(function(field) {
c[field] = messages[field].codes; c[field] = messages[field].codes;
}); });
@ -866,7 +867,7 @@ function ValidationError(obj) {
this.name = 'ValidationError'; this.name = 'ValidationError';
var context = obj && obj.constructor && obj.constructor.modelName; const context = obj && obj.constructor && obj.constructor.modelName;
this.message = g.f( this.message = g.f(
'The %s instance is not valid. Details: %s.', 'The %s instance is not valid. Details: %s.',
context ? '`' + context + '`' : 'model', context ? '`' + context + '`' : 'model',
@ -894,20 +895,20 @@ function ValidationError(obj) {
util.inherits(ValidationError, Error); util.inherits(ValidationError, Error);
var errorHasStackProperty = !!(new Error).stack; const errorHasStackProperty = !!(new Error).stack;
ValidationError.maxPropertyStringLength = 32; ValidationError.maxPropertyStringLength = 32;
function formatErrors(errors, propertyValues) { function formatErrors(errors, propertyValues) {
var DELIM = '; '; const DELIM = '; ';
errors = errors || {}; errors = errors || {};
return Object.getOwnPropertyNames(errors) return Object.getOwnPropertyNames(errors)
.filter(function(propertyName) { .filter(function(propertyName) {
return Array.isArray(errors[propertyName]); return Array.isArray(errors[propertyName]);
}) })
.map(function(propertyName) { .map(function(propertyName) {
var messages = errors[propertyName]; const messages = errors[propertyName];
var propertyValue = propertyValues[propertyName]; const propertyValue = propertyValues[propertyName];
return messages.map(function(msg) { return messages.map(function(msg) {
return formatPropertyError(propertyName, propertyValue, msg); return formatPropertyError(propertyName, propertyValue, msg);
}).join(DELIM); }).join(DELIM);
@ -916,8 +917,8 @@ function formatErrors(errors, propertyValues) {
} }
function formatPropertyError(propertyName, propertyValue, errorMessage) { function formatPropertyError(propertyName, propertyValue, errorMessage) {
var formattedValue; let formattedValue;
var valueType = typeof propertyValue; const valueType = typeof propertyValue;
if (valueType === 'string') { if (valueType === 'string') {
formattedValue = JSON.stringify(truncatePropertyString(propertyValue)); formattedValue = JSON.stringify(truncatePropertyString(propertyValue));
} else if (propertyValue instanceof Date) { } else if (propertyValue instanceof Date) {
@ -939,13 +940,13 @@ function formatPropertyError(propertyName, propertyValue, errorMessage) {
} }
function truncatePropertyString(value) { function truncatePropertyString(value) {
var len = ValidationError.maxPropertyStringLength; let len = ValidationError.maxPropertyStringLength;
if (value.length <= len) return value; if (value.length <= len) return value;
// preserve few last characters like `}` or `]`, but no more than 3 // 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 // this way the last `} ]` in the array of objects is included in the message
var tail; let tail;
var m = value.match(/([ \t})\]]+)$/); const m = value.match(/([ \t})\]]+)$/);
if (m) { if (m) {
tail = m[1].slice(-3); tail = m[1].slice(-3);
len -= tail.length; len -= tail.length;

View File

@ -12,30 +12,30 @@
* $ open hooks.hml * $ open hooks.hml
* *
*/ */
var Promise = global.Promise = require('bluebird'); const Promise = global.Promise = require('bluebird');
var DataSource = require('../').DataSource; const DataSource = require('../').DataSource;
var Memory = require('../lib/connectors/memory').Memory; const Memory = require('../lib/connectors/memory').Memory;
var HOOK_NAMES = [ const HOOK_NAMES = [
'access', 'access',
'before save', 'persist', 'loaded', 'after save', 'before save', 'persist', 'loaded', 'after save',
'before delete', 'after delete', 'before delete', 'after delete',
]; ];
var dataSources = [ const dataSources = [
createOptimizedDataSource(), createOptimizedDataSource(),
createUnoptimizedDataSource(), createUnoptimizedDataSource(),
]; ];
var observedContexts = []; const observedContexts = [];
var lastId = 0; let lastId = 0;
Promise.onPossiblyUnhandledRejection(function(err) { Promise.onPossiblyUnhandledRejection(function(err) {
console.error('POSSIBLY UNHANDLED REJECTION', err.stack); console.error('POSSIBLY UNHANDLED REJECTION', err.stack);
}); });
/* eslint-disable camelcase */ /* eslint-disable camelcase */
var operations = [ const operations = [
function find(ds) { function find(ds) {
return ds.TestModel.find({where: {id: '1'}}); return ds.TestModel.find({where: {id: '1'}});
}, },
@ -112,7 +112,7 @@ var operations = [
]; ];
/* eslint-enable camelcase */ /* eslint-enable camelcase */
var p = setupTestModels(); let p = setupTestModels();
operations.forEach(function(op) { operations.forEach(function(op) {
p = p.then(runner(op)); p = p.then(runner(op));
}); });
@ -120,13 +120,13 @@ operations.forEach(function(op) {
p.then(report, function(err) { console.error(err.stack); }); p.then(report, function(err) { console.error(err.stack); });
function createOptimizedDataSource() { function createOptimizedDataSource() {
var ds = new DataSource({connector: Memory}); const ds = new DataSource({connector: Memory});
ds.name = 'Optimized'; ds.name = 'Optimized';
return ds; return ds;
} }
function createUnoptimizedDataSource() { function createUnoptimizedDataSource() {
var ds = new DataSource({connector: Memory}); const ds = new DataSource({connector: Memory});
ds.name = 'Unoptimized'; ds.name = 'Unoptimized';
// disable optimized methods // disable optimized methods
@ -139,7 +139,7 @@ function createUnoptimizedDataSource() {
function setupTestModels() { function setupTestModels() {
dataSources.forEach(function setupOnDataSource(ds) { 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}, id: {type: String, id: true, default: uid},
name: {type: String, required: true}, name: {type: String, required: true},
extra: {type: String, required: false}, extra: {type: String, required: false},
@ -155,7 +155,7 @@ function uid() {
function runner(fn) { function runner(fn) {
return function() { return function() {
var res = Promise.resolve(); let res = Promise.resolve();
dataSources.forEach(function(ds) { dataSources.forEach(function(ds) {
res = res.then(function() { res = res.then(function() {
return resetStorage(ds); return resetStorage(ds);
@ -173,7 +173,7 @@ function runner(fn) {
} }
function resetStorage(ds) { function resetStorage(ds) {
var TestModel = ds.TestModel; const TestModel = ds.TestModel;
HOOK_NAMES.forEach(function(hook) { HOOK_NAMES.forEach(function(hook) {
TestModel.clearObservers(hook); TestModel.clearObservers(hook);
}); });
@ -192,7 +192,7 @@ function resetStorage(ds) {
.then(function() { .then(function() {
HOOK_NAMES.forEach(function(hook) { HOOK_NAMES.forEach(function(hook) {
TestModel.observe(hook, function(ctx, next) { TestModel.observe(hook, function(ctx, next) {
var row = observedContexts[observedContexts.length - 1]; const row = observedContexts[observedContexts.length - 1];
row.hooks[hook] = Object.keys(ctx); row.hooks[hook] = Object.keys(ctx);
next(); next();
}); });
@ -212,7 +212,7 @@ function report() {
// merge rows where Optimized and Unoptimized produce the same context // merge rows where Optimized and Unoptimized produce the same context
observedContexts.forEach(function(row, ix) { observedContexts.forEach(function(row, ix) {
if (!ix) return; if (!ix) return;
var last = observedContexts[ix - 1]; const last = observedContexts[ix - 1];
if (row.operation != last.operation) return; if (row.operation != last.operation) return;
if (JSON.stringify(row.hooks) !== JSON.stringify(last.hooks)) return; if (JSON.stringify(row.hooks) !== JSON.stringify(last.hooks)) return;
last.merge = true; last.merge = true;
@ -226,11 +226,11 @@ function report() {
observedContexts.forEach(function(row) { observedContexts.forEach(function(row) {
if (row.skip) return; if (row.skip) return;
var caption = row.operation; let caption = row.operation;
if (!row.merge) caption += ' (' + row.connector + ')'; if (!row.merge) caption += ' (' + row.connector + ')';
console.log('<tr><th>' + caption + '</th>'); console.log('<tr><th>' + caption + '</th>');
HOOK_NAMES.forEach(function(h) { 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(' <td>' + text + '</td>');
}); });
console.log('</tr>'); console.log('</tr>');

View File

@ -4,12 +4,12 @@
// License text available at https://opensource.org/licenses/MIT // License text available at https://opensource.org/licenses/MIT
'use strict'; 'use strict';
var should = require('./init.js'); const should = require('./init.js');
var jdb = require('../'); const jdb = require('../');
var DataSource = jdb.DataSource; const DataSource = jdb.DataSource;
var ds, Item, Variant; let ds, Item, Variant;
describe('Datasource-specific field types for foreign keys', function() { describe('Datasource-specific field types for foreign keys', function() {
before(function() { before(function() {
ds = new DataSource('memory'); 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) { 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);
should.exist(VariantDefinition.properties.myProp.memory); should.exist(VariantDefinition.properties.myProp.memory);
should.exist(VariantDefinition.properties.myProp.memory.dataType); should.exist(VariantDefinition.properties.myProp.memory.dataType);

View File

@ -60,7 +60,7 @@ describe('allowExtendedOperators', () => {
all(model, filter, options, callback) { all(model, filter, options, callback) {
// return the raw "value" query // return the raw "value" query
let instanceFound = { const instanceFound = {
value: filter.where.value, value: filter.where.value,
}; };
callback(null, [instanceFound]); callback(null, [instanceFound]);

View File

@ -4,18 +4,18 @@
// License text available at https://opensource.org/licenses/MIT // License text available at https://opensource.org/licenses/MIT
'use strict'; 'use strict';
var ModelBuilder = require('../').ModelBuilder; const ModelBuilder = require('../').ModelBuilder;
var should = require('./init'); const should = require('./init');
describe('async observer', function() { describe('async observer', function() {
var TestModel; let TestModel;
beforeEach(function defineTestModel() { beforeEach(function defineTestModel() {
var modelBuilder = new ModelBuilder(); const modelBuilder = new ModelBuilder();
TestModel = modelBuilder.define('TestModel', {name: String}); TestModel = modelBuilder.define('TestModel', {name: String});
}); });
it('calls registered async observers', function(done) { it('calls registered async observers', function(done) {
var notifications = []; const notifications = [];
TestModel.observe('before', pushAndNext(notifications, 'before')); TestModel.observe('before', pushAndNext(notifications, 'before'));
TestModel.observe('after', pushAndNext(notifications, 'after')); TestModel.observe('after', pushAndNext(notifications, 'after'));
@ -32,7 +32,7 @@ describe('async observer', function() {
}); });
it('allows multiple observers for the same operation', function(done) { 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, 'one'));
TestModel.observe('event', pushAndNext(notifications, 'two')); TestModel.observe('event', pushAndNext(notifications, 'two'));
@ -44,7 +44,7 @@ describe('async observer', function() {
}); });
it('allows multiple operations to be notified in one call', function(done) { it('allows multiple operations to be notified in one call', function(done) {
var notifications = []; const notifications = [];
TestModel.observe('event1', pushAndNext(notifications, 'one')); TestModel.observe('event1', pushAndNext(notifications, 'one'));
TestModel.observe('event2', pushAndNext(notifications, 'two')); TestModel.observe('event2', pushAndNext(notifications, 'two'));
@ -56,10 +56,10 @@ describe('async observer', function() {
}); });
it('inherits observers from base model', function(done) { it('inherits observers from base model', function(done) {
var notifications = []; const notifications = [];
TestModel.observe('event', pushAndNext(notifications, 'base')); TestModel.observe('event', pushAndNext(notifications, 'base'));
var Child = TestModel.extend('Child'); const Child = TestModel.extend('Child');
Child.observe('event', pushAndNext(notifications, 'child')); Child.observe('event', pushAndNext(notifications, 'child'));
Child.notifyObserversOf('event', {}, function(err) { Child.notifyObserversOf('event', {}, function(err) {
@ -70,11 +70,11 @@ describe('async observer', function() {
}); });
it('allow multiple operations to be notified with base models', function(done) { it('allow multiple operations to be notified with base models', function(done) {
var notifications = []; const notifications = [];
TestModel.observe('event1', pushAndNext(notifications, 'base1')); TestModel.observe('event1', pushAndNext(notifications, 'base1'));
TestModel.observe('event2', pushAndNext(notifications, 'base2')); TestModel.observe('event2', pushAndNext(notifications, 'base2'));
var Child = TestModel.extend('Child'); const Child = TestModel.extend('Child');
Child.observe('event1', pushAndNext(notifications, 'child1')); Child.observe('event1', pushAndNext(notifications, 'child1'));
Child.observe('event2', pushAndNext(notifications, 'child2')); Child.observe('event2', pushAndNext(notifications, 'child2'));
@ -86,10 +86,10 @@ describe('async observer', function() {
}); });
it('does not modify observers in the base model', function(done) { it('does not modify observers in the base model', function(done) {
var notifications = []; const notifications = [];
TestModel.observe('event', pushAndNext(notifications, 'base')); TestModel.observe('event', pushAndNext(notifications, 'base'));
var Child = TestModel.extend('Child'); const Child = TestModel.extend('Child');
Child.observe('event', pushAndNext(notifications, 'child')); Child.observe('event', pushAndNext(notifications, 'child'));
TestModel.notifyObserversOf('event', {}, function(err) { TestModel.notifyObserversOf('event', {}, function(err) {
@ -100,10 +100,10 @@ describe('async observer', function() {
}); });
it('always calls inherited observers', function(done) { it('always calls inherited observers', function(done) {
var notifications = []; const notifications = [];
TestModel.observe('event', pushAndNext(notifications, 'base')); 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 // Important: there are no observers on the Child model
Child.notifyObserversOf('event', {}, function(err) { Child.notifyObserversOf('event', {}, function(err) {
@ -114,7 +114,7 @@ describe('async observer', function() {
}); });
it('can remove observers', function(done) { it('can remove observers', function(done) {
var notifications = []; const notifications = [];
function call(ctx, next) { function call(ctx, next) {
notifications.push('call'); notifications.push('call');
@ -132,7 +132,7 @@ describe('async observer', function() {
}); });
it('can clear all observers', function(done) { it('can clear all observers', function(done) {
var notifications = []; const notifications = [];
function call(ctx, next) { function call(ctx, next) {
notifications.push('call'); notifications.push('call');
@ -159,7 +159,7 @@ describe('async observer', function() {
}); });
it('passes context to final callback', function(done) { it('passes context to final callback', function(done) {
var context = {}; const context = {};
TestModel.notifyObserversOf('event', context, function(err, ctx) { TestModel.notifyObserversOf('event', context, function(err, ctx) {
(ctx || 'null').should.equal(context); (ctx || 'null').should.equal(context);
done(); done();
@ -167,7 +167,7 @@ describe('async observer', function() {
}); });
describe('notifyObserversAround', function() { describe('notifyObserversAround', function() {
var notifications; let notifications;
beforeEach(function() { beforeEach(function() {
notifications = []; notifications = [];
TestModel.observe('before execute', TestModel.observe('before execute',
@ -177,7 +177,7 @@ describe('async observer', function() {
}); });
it('should notify before/after observers', function(done) { it('should notify before/after observers', function(done) {
var context = {}; const context = {};
function work(done) { function work(done) {
process.nextTick(function() { process.nextTick(function() {
@ -194,7 +194,7 @@ describe('async observer', function() {
}); });
it('should allow work with context', function(done) { it('should allow work with context', function(done) {
var context = {}; const context = {};
function work(context, done) { function work(context, done) {
process.nextTick(function() { process.nextTick(function() {
@ -212,7 +212,7 @@ describe('async observer', function() {
it('should notify before/after observers with multiple results', it('should notify before/after observers with multiple results',
function(done) { function(done) {
var context = {}; const context = {};
function work(done) { function work(done) {
process.nextTick(function() { process.nextTick(function() {
@ -239,7 +239,7 @@ describe('async observer', function() {
TestModel.observe('after invoke', TestModel.observe('after invoke',
pushAndNext(notifications, 'after invoke')); pushAndNext(notifications, 'after invoke'));
var context = {}; const context = {};
function work(done) { function work(done) {
process.nextTick(function() { process.nextTick(function() {
@ -264,7 +264,7 @@ describe('async observer', function() {
next(); next();
}); });
var context = {}; const context = {};
function work(done) { function work(done) {
process.nextTick(function() { process.nextTick(function() {
@ -292,7 +292,7 @@ describe('async observer', function() {
}); });
it('handles rejected promise returned by an observer', function(done) { 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) { TestModel.observe('event', function(ctx) {
return Promise.reject(testError); return Promise.reject(testError);
}); });
@ -303,8 +303,8 @@ describe('async observer', function() {
}); });
it('returns a promise when no callback is provided', function() { it('returns a promise when no callback is provided', function() {
var context = {value: 'a-test-context'}; const context = {value: 'a-test-context'};
var p = TestModel.notifyObserversOf('event', context); const p = TestModel.notifyObserversOf('event', context);
(p !== undefined).should.be.true; (p !== undefined).should.be.true;
return p.then(function(result) { return p.then(function(result) {
result.should.eql(context); result.should.eql(context);
@ -312,9 +312,9 @@ describe('async observer', function() {
}); });
it('returns a rejected promise when no callback is provided', 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); }); TestModel.observe('event', function(ctx, next) { next(testError); });
var p = TestModel.notifyObserversOf('event', context); const p = TestModel.notifyObserversOf('event', context);
return p.then( return p.then(
function(result) { function(result) {
throw new Error('The promise should have been rejected.'); throw new Error('The promise should have been rejected.');

View File

@ -7,16 +7,16 @@
'use strict'; 'use strict';
/* global getSchema:false, connectorCapabilities:false */ /* global getSchema:false, connectorCapabilities:false */
var async = require('async'); const async = require('async');
var bdd = require('./helpers/bdd-if'); const bdd = require('./helpers/bdd-if');
var should = require('./init.js'); const should = require('./init.js');
var uid = require('./helpers/uid-generator'); const uid = require('./helpers/uid-generator');
var db, User; let db, User;
describe('basic-querying', function() { describe('basic-querying', function() {
before(function(done) { before(function(done) {
var userModelDef = { const userModelDef = {
seq: {type: Number, index: true}, seq: {type: Number, index: true},
name: {type: String, index: true, sort: true}, name: {type: String, index: true, sort: true},
email: {type: String, index: true}, email: {type: String, index: true},
@ -71,7 +71,7 @@ describe('basic-querying', function() {
}); });
it('should query by id: not found', function(done) { 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) { User.findById(unknownId, function(err, u) {
should.not.exist(u); should.not.exist(u);
should.not.exist(err); should.not.exist(err);
@ -94,10 +94,10 @@ describe('basic-querying', function() {
}); });
describe('findByIds', function() { describe('findByIds', function() {
var createdUsers; let createdUsers;
before(function(done) { before(function(done) {
db = getSchema(); db = getSchema();
var people = [ const people = [
{name: 'a', vip: true}, {name: 'a', vip: true},
{name: 'b', vip: null}, {name: 'b', vip: null},
{name: 'c'}, {name: 'c'},
@ -122,7 +122,7 @@ describe('basic-querying', function() {
function(err, users) { function(err, users) {
should.exist(users); should.exist(users);
should.not.exist(err); should.not.exist(err);
var names = users.map(function(u) { const names = users.map(function(u) {
return u.name; return u.name;
}); });
names.should.eql( names.should.eql(
@ -142,7 +142,7 @@ describe('basic-querying', function() {
{where: {vip: true}}, function(err, users) { {where: {vip: true}}, function(err, users) {
should.exist(users); should.exist(users);
should.not.exist(err); should.not.exist(err);
var names = users.map(function(u) { const names = users.map(function(u) {
return u.name; return u.name;
}); });
names.should.eql(createdUsers.slice(0, 4). names.should.eql(createdUsers.slice(0, 4).
@ -283,7 +283,7 @@ describe('basic-querying', function() {
User.find({order: 'order DESC'}, function(err, users) { User.find({order: 'order DESC'}, function(err, users) {
if (err) return done(err); if (err) return done(err);
should.exists(users); 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]); order.should.eql([6, 5, 4, 3, 2, 1]);
done(); done();
}); });
@ -471,7 +471,7 @@ describe('basic-querying', function() {
User.find({where: {name: {'gte': 'Paul McCartney'}}}, function(err, users) { User.find({where: {name: {'gte': 'Paul McCartney'}}}, function(err, users) {
should.not.exist(err); should.not.exist(err);
users.should.have.property('length', 4); 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'); users[ix].name.should.be.greaterThanOrEqual('Paul McCartney');
} }
done(); done();
@ -493,7 +493,7 @@ describe('basic-querying', function() {
}}, function(err, users) { }}, function(err, users) {
should.not.exist(err); should.not.exist(err);
users.should.have.property('length', 3); 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'); users[ix].name.should.be.greaterThan('Paul McCartney');
} }
done(); done();
@ -506,7 +506,7 @@ describe('basic-querying', function() {
}}, function(err, users) { }}, function(err, users) {
should.not.exist(err); should.not.exist(err);
users.should.have.property('length', 2); 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'); users[ix].name.should.be.lessThan('Paul McCartney');
} }
done(); done();
@ -518,7 +518,7 @@ describe('basic-querying', function() {
}}, function(err, users) { }}, function(err, users) {
should.not.exist(err); should.not.exist(err);
users.should.have.property('length', 3); 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].name.should.be.oneOf(['John Lennon', 'Stuart Sutcliffe', 'Paul McCartney']);
users[ix].vip.should.be.true(); users[ix].vip.should.be.true();
} }
@ -540,7 +540,7 @@ describe('basic-querying', function() {
}}, function(err, users) { }}, function(err, users) {
should.not.exist(err); should.not.exist(err);
users.should.have.property('length', 3); 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].name.should.be.oneOf(['John Lennon', 'Stuart Sutcliffe', 'Paul McCartney']);
users[ix].vip.should.be.true(users[ix].name + ' should be VIP'); users[ix].vip.should.be.true(users[ix].name + ' should be VIP');
} }
@ -553,7 +553,7 @@ describe('basic-querying', function() {
}}, function(err, users) { }}, function(err, users) {
should.not.exist(err); should.not.exist(err);
users.should.have.property('length', 2); 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].name.should.be.oneOf(['Ringo Starr', 'George Harrison']);
users[ix].vip.should.be.false(users[ix].name + ' should not be VIP'); 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() { bdd.describeIf(itWhenIlikeSupported, 'ilike', function() {
it('should support "like" that is satisfied', it('should support "like" that is satisfied',
function(done) { 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() { bdd.describeIf(itWhenNilikeSupported, 'nilike', function() {
it('should support "nlike" that is satisfied', function(done) { it('should support "nlike" that is satisfied', function(done) {
User.find({where: {name: {nlike: 'John'}}}, User.find({where: {name: {nlike: 'John'}}},
@ -783,7 +783,7 @@ describe('basic-querying', function() {
}); });
it('should only include fields as specified', function(done) { it('should only include fields as specified', function(done) {
var remaining = 0; let remaining = 0;
function sample(fields) { function sample(fields) {
return { return {
@ -800,7 +800,7 @@ describe('basic-querying', function() {
} }
users.forEach(function(user) { users.forEach(function(user) {
var obj = user.toObject(); const obj = user.toObject();
Object.keys(obj) Object.keys(obj)
.forEach(function(key) { .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() { bdd.describeIf(describeWhenNestedSupported, 'query with nested property', function() {
it('should support nested property in query', function(done) { it('should support nested property in query', function(done) {
User.find({where: {'address.city': 'San Jose'}}, function(err, users) { User.find({where: {'address.city': 'San Jose'}}, function(err, users) {
if (err) return done(err); if (err) return done(err);
users.length.should.be.equal(1); 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'); users[i].address.city.should.be.eql('San Jose');
} }
done(); done();
@ -867,7 +867,7 @@ describe('basic-querying', function() {
User.find({where: {'friends.name': {regexp: /^Ringo/}}}, function(err, users) { User.find({where: {'friends.name': {regexp: /^Ringo/}}}, function(err, users) {
if (err) return done(err); if (err) return done(err);
users.length.should.be.equal(2); 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[0].name).should.not.equal(-1);
expectedUsers.indexOf(users[1].name).should.not.equal(-1); expectedUsers.indexOf(users[1].name).should.not.equal(-1);
done(); done();
@ -878,7 +878,7 @@ describe('basic-querying', function() {
User.find({where: {'address.city': {gt: 'San'}}}, function(err, users) { User.find({where: {'address.city': {gt: 'San'}}}, function(err, users) {
if (err) return done(err); if (err) return done(err);
users.length.should.be.equal(2); 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'); users[i].address.state.should.be.eql('CA');
} }
done(); done();
@ -1015,7 +1015,7 @@ describe('basic-querying', function() {
}); });
it('should check whether record not exist', function(done) { 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.destroyAll(function() {
User.exists(unknownId, function(err, exists) { User.exists(unknownId, function(err, exists) {
should.not.exist(err); should.not.exist(err);
@ -1027,7 +1027,7 @@ describe('basic-querying', function() {
}); });
context('regexp operator', function() { context('regexp operator', function() {
var invalidDataTypes = [0, true, {}, [], Function, null]; const invalidDataTypes = [0, true, {}, [], Function, null];
before(seed); before(seed);
@ -1046,7 +1046,7 @@ describe('basic-querying', function() {
// FIXME: This should either be re-enabled or removed. // FIXME: This should either be re-enabled or removed.
describe.skip('queries', function() { describe.skip('queries', function() {
var Todo; let Todo;
before(function prepDb(done) { before(function prepDb(done) {
db = getSchema(); db = getSchema();
@ -1078,7 +1078,7 @@ describe.skip('queries', function() {
}); });
it('should work for updateOrCreate/upsert', function(done) { it('should work for updateOrCreate/upsert', function(done) {
var aliases = ['updateOrCreate', 'upsert']; const aliases = ['updateOrCreate', 'upsert'];
async.each(aliases, function(alias, cb) { async.each(aliases, function(alias, cb) {
Todo[alias]({content: 'Buy ham'}, function(err) { Todo[alias]({content: 'Buy ham'}, function(err) {
should.not.exist(err); should.not.exist(err);
@ -1118,7 +1118,7 @@ describe.skip('queries', function() {
it('should work for deleteAll/destroyAll/remove', function(done) { it('should work for deleteAll/destroyAll/remove', function(done) {
// FIXME: We should add a DAO.delete static method alias for consistency // FIXME: We should add a DAO.delete static method alias for consistency
// (DAO.prototype.delete instance method already exists) // (DAO.prototype.delete instance method already exists)
var aliases = ['deleteAll', 'destroyAll', 'remove']; const aliases = ['deleteAll', 'destroyAll', 'remove'];
async.each(aliases, function(alias, cb) { async.each(aliases, function(alias, cb) {
Todo[alias](function(err) { Todo[alias](function(err) {
should.not.exist(err); should.not.exist(err);
@ -1143,7 +1143,7 @@ describe.skip('queries', function() {
}); });
context('that require an id', 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) { it('should return an error for findById', function(done) {
Todo.findById(1, function(err) { Todo.findById(1, function(err) {
@ -1163,7 +1163,7 @@ describe.skip('queries', function() {
it('should return an error for deleteById/destroyById/removeById', it('should return an error for deleteById/destroyById/removeById',
function(done) { function(done) {
var aliases = ['deleteById', 'destroyById', 'removeById']; const aliases = ['deleteById', 'destroyById', 'removeById'];
async.each(aliases, function(alias, cb) { async.each(aliases, function(alias, cb) {
Todo[alias](1, function(err) { Todo[alias](1, function(err) {
should.exist(err); should.exist(err);
@ -1174,7 +1174,7 @@ describe.skip('queries', function() {
}); });
it('should return an error for instance.save', function(done) { it('should return an error for instance.save', function(done) {
var todo = new Todo(); const todo = new Todo();
todo.content = 'Buy ham'; todo.content = 'Buy ham';
todo.save(function(err) { todo.save(function(err) {
should.exist(err); should.exist(err);
@ -1216,7 +1216,7 @@ describe.skip('queries', function() {
}); });
function seed(done) { function seed(done) {
var beatles = [ const beatles = [
{ {
seq: 0, seq: 0,
name: 'John Lennon', name: 'John Lennon',
@ -1285,6 +1285,6 @@ function seed(done) {
} }
function nextAfterDelay(ctx, next) { function nextAfterDelay(ctx, next) {
var randomTimeoutTrigger = Math.floor(Math.random() * 100); const randomTimeoutTrigger = Math.floor(Math.random() * 100);
setTimeout(function() { process.nextTick(next); }, randomTimeoutTrigger); setTimeout(function() { process.nextTick(next); }, randomTimeoutTrigger);
} }

View File

@ -5,13 +5,13 @@
'use strict'; 'use strict';
var Schema = require('../index').Schema; const Schema = require('../index').Schema;
var Text = Schema.Text; const Text = Schema.Text;
var nbSchemaRequests = 0; let nbSchemaRequests = 0;
var batch; let batch;
var schemaName; let schemaName;
function it(name, cases) { function it(name, cases) {
batch[schemaName][name] = cases; batch[schemaName][name] = cases;
@ -27,7 +27,7 @@ module.exports = function testSchema(exportCasesHere, dataSource) {
if (dataSource.name.match(/^\/.*\/test\/\.\.$/)) { if (dataSource.name.match(/^\/.*\/test\/\.\.$/)) {
schemaName = schemaName.split('/').slice(-3).shift(); schemaName = schemaName.split('/').slice(-3).shift();
} }
var start; let start;
batch['should connect to database'] = function(test) { batch['should connect to database'] = function(test) {
start = Date.now(); start = Date.now();
@ -70,12 +70,12 @@ Object.defineProperty(module.exports, 'skip', {
}); });
function clearAndCreate(model, data, callback) { function clearAndCreate(model, data, callback) {
var createdItems = []; const createdItems = [];
model.destroyAll(function() { model.destroyAll(function() {
nextItem(null, null); nextItem(null, null);
}); });
var itemIndex = 0; let itemIndex = 0;
function nextItem(err, lastItem) { function nextItem(err, lastItem) {
if (lastItem !== null) { if (lastItem !== null) {
@ -92,9 +92,9 @@ function clearAndCreate(model, data, callback) {
/* eslint-disable mocha/handle-done-callback */ /* eslint-disable mocha/handle-done-callback */
function testOrm(dataSource) { 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) { it('should define class', function(test) {
User = dataSource.define('User', { User = dataSource.define('User', {
@ -123,7 +123,7 @@ function testOrm(dataSource) {
extra: Object, extra: Object,
}); });
var newuser = new User({settings: {hey: 'you'}}); const newuser = new User({settings: {hey: 'you'}});
test.ok(newuser.settings); test.ok(newuser.settings);
Post = dataSource.define('Post', { Post = dataSource.define('Post', {
@ -177,7 +177,7 @@ function testOrm(dataSource) {
Passport.belongsTo(User, {as: 'owner', foreignKey: 'ownerId'}); Passport.belongsTo(User, {as: 'owner', foreignKey: 'ownerId'});
User.hasMany(Passport, {as: 'passports', foreignKey: 'ownerId'}); User.hasMany(Passport, {as: 'passports', foreignKey: 'ownerId'});
var user = new User; const user = new User;
test.ok(User instanceof Function); test.ok(User instanceof Function);
@ -199,7 +199,7 @@ function testOrm(dataSource) {
}); });
it('should initialize object properly', function(test) { it('should initialize object properly', function(test) {
var hw = 'Hello word', const hw = 'Hello word',
now = Date.now(), now = Date.now(),
post = new Post({title: hw}), post = new Post({title: hw}),
anotherPost = Post({title: 'Resig style constructor'}); anotherPost = Post({title: 'Resig style constructor'});
@ -218,7 +218,7 @@ function testOrm(dataSource) {
}); });
it('should save object', function(test) { it('should save object', function(test) {
var title = 'Initial title', title2 = 'Hello world', const title = 'Initial title', title2 = 'Hello world',
date = new Date; date = new Date;
Post.create({ Post.create({
@ -234,7 +234,7 @@ function testOrm(dataSource) {
test.equal(obj.title, title2); test.equal(obj.title, title2);
test.ok(!obj.propertyChanged('title')); test.ok(!obj.propertyChanged('title'));
var p = new Post({title: 1}); const p = new Post({title: 1});
p.title = 2; p.title = 2;
p.save(function(err, obj) { p.save(function(err, obj) {
test.ok(!p.propertyChanged('title')); test.ok(!p.propertyChanged('title'));
@ -252,7 +252,7 @@ function testOrm(dataSource) {
}); });
it('should create object with initial data', function(test) { it('should create object with initial data', function(test) {
var title = 'Initial title', const title = 'Initial title',
date = new Date; date = new Date;
Post.create({ Post.create({
@ -301,8 +301,8 @@ function testOrm(dataSource) {
*/ */
it('should not re-instantiate object on saving', function(test) { it('should not re-instantiate object on saving', function(test) {
var title = 'Initial title'; const title = 'Initial title';
var post = new Post({title: title}); const post = new Post({title: title});
post.save(function(err, savedPost) { post.save(function(err, savedPost) {
test.strictEqual(post, savedPost); test.strictEqual(post, savedPost);
test.done(); test.done();
@ -329,21 +329,21 @@ function testOrm(dataSource) {
}); });
it('should handle virtual attributes', function(test) { it('should handle virtual attributes', function(test) {
var salt = 's0m3s3cr3t5a1t'; const salt = 's0m3s3cr3t5a1t';
User.setter.passwd = function(password) { User.setter.passwd = function(password) {
this._passwd = calcHash(password, salt); this._passwd = calcHash(password, salt);
}; };
function calcHash(pass, salt) { function calcHash(pass, salt) {
var crypto = require('crypto'); const crypto = require('crypto');
var hash = crypto.createHash('sha256'); const hash = crypto.createHash('sha256');
hash.update(pass); hash.update(pass);
hash.update(salt); hash.update(salt);
return hash.digest('base64'); return hash.digest('base64');
} }
var u = new User; const u = new User;
u.passwd = 's3cr3t'; u.passwd = 's3cr3t';
test.equal(u.passwd, calcHash('s3cr3t', salt)); test.equal(u.passwd, calcHash('s3cr3t', salt));
test.done(); test.done();
@ -380,7 +380,7 @@ function testOrm(dataSource) {
}); });
}); });
var countOfposts, countOfpostsFiltered; let countOfposts, countOfpostsFiltered;
it('should fetch collection', function(test) { it('should fetch collection', function(test) {
Post.all(function(err, posts) { Post.all(function(err, posts) {
countOfposts = posts.length; countOfposts = posts.length;
@ -394,7 +394,7 @@ function testOrm(dataSource) {
}); });
it('should find records filtered with multiple attributes', function(test) { 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.create({title: 'title', content: 'content', published: true, date: d}, function(err, post) {
Post.all({where: {title: 'title', date: d, published: true}}, function(err, res) { Post.all({where: {title: 'title', date: d, published: true}}, function(err, res) {
test.equals(res.length, 1, 'Filtering Posts returns one post'); 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 // Finding one post with an existing author associated
Post.all(function(err, posts) { Post.all(function(err, posts) {
// We try to get the first post with a userId != NULL // We try to get the first post with a userId != NULL
for (var i = 0; i < posts.length; i++) { for (let i = 0; i < posts.length; i++) {
var post = posts[i]; const post = posts[i];
if (post.userId) { if (post.userId) {
// We could get the user with belongs to relationship but it is better if there is no interactions. // 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) { 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 // There can't be any concurrency because we are counting requests
// We are first testing cases when user has posts // We are first testing cases when user has posts
user.posts(function(err, data) { user.posts(function(err, data) {
var nbInitialRequests = nbSchemaRequests; const nbInitialRequests = nbSchemaRequests;
user.posts(function(err, data2) { user.posts(function(err, data2) {
test.equal(data.length, 2, 'There should be 2 posts.'); 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.'); 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 // We are now testing cases when user doesn't have any post
voidUser.posts(function(err, data) { voidUser.posts(function(err, data) {
var nbInitialRequests = nbSchemaRequests; const nbInitialRequests = nbSchemaRequests;
voidUser.posts(function(err, data2) { voidUser.posts(function(err, data2) {
test.equal(data.length, 0, 'There shouldn\'t be any posts (1/2).'); 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).'); 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) { it('should support scopes', function(test) {
var wait = 2; let wait = 2;
test.ok(Post.scope, 'Scope supported'); test.ok(Post.scope, 'Scope supported');
Post.scope('published', {where: {published: true}}); Post.scope('published', {where: {published: true}});
test.ok(typeof Post.published === 'function'); test.ok(typeof Post.published === 'function');
test.ok(Post.published._scope.where.published === true); 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.published, 'Can build');
test.ok(post.isNewRecord()); test.ok(post.isNewRecord());
Post.published.create(function(err, psto) { Post.published.create(function(err, psto) {
@ -583,14 +583,14 @@ function testOrm(dataSource) {
it('should return type of property', function(test) { it('should return type of property', function(test) {
test.equal(Post.getPropertyType('title'), 'String'); test.equal(Post.getPropertyType('title'), 'String');
test.equal(Post.getPropertyType('content'), 'Text'); test.equal(Post.getPropertyType('content'), 'Text');
var p = new Post; const p = new Post;
test.equal(p.getPropertyType('title'), 'String'); test.equal(p.getPropertyType('title'), 'String');
test.equal(p.getPropertyType('content'), 'Text'); test.equal(p.getPropertyType('content'), 'Text');
test.done(); test.done();
}); });
it('should handle ORDER clause', function(test) { it('should handle ORDER clause', function(test) {
var titles = [ const titles = [
{title: 'Title A', subject: 'B'}, {title: 'Title A', subject: 'B'},
{title: 'Title Z', subject: 'A'}, {title: 'Title Z', subject: 'A'},
{title: 'Title M', subject: 'C'}, {title: 'Title M', subject: 'C'},
@ -598,8 +598,8 @@ function testOrm(dataSource) {
{title: 'Title B', subject: 'A'}, {title: 'Title B', subject: 'A'},
{title: 'Title C', subject: 'D'}, {title: 'Title C', subject: 'D'},
]; ];
var isRedis = Post.dataSource.name === 'redis'; const isRedis = Post.dataSource.name === 'redis';
var dates = isRedis ? [5, 9, 0, 17, 10, 9] : [ const dates = isRedis ? [5, 9, 0, 17, 10, 9] : [
new Date(1000 * 5), new Date(1000 * 5),
new Date(1000 * 9), new Date(1000 * 9),
new Date(1000 * 0), new Date(1000 * 0),
@ -611,7 +611,7 @@ function testOrm(dataSource) {
Post.create({title: t.title, subject: t.subject, date: dates[i]}, done); Post.create({title: t.title, subject: t.subject, date: dates[i]}, done);
}); });
var i = 0, tests = 0; let i = 0, tests = 0;
function done(err, obj) { function done(err, obj) {
if (++i === titles.length) { if (++i === titles.length) {
@ -717,7 +717,7 @@ function testOrm(dataSource) {
}); });
} }
var fin = 0; let fin = 0;
function finished() { function finished() {
if (++fin === tests) { if (++fin === tests) {
@ -871,8 +871,8 @@ function testOrm(dataSource) {
// }); // });
it('should handle order clause with direction', function(test) { it('should handle order clause with direction', function(test) {
var wait = 0; let wait = 0;
var emails = [ const emails = [
'john@hcompany.com', 'john@hcompany.com',
'tom@hcompany.com', 'tom@hcompany.com',
'admin@hcompany.com', 'admin@hcompany.com',
@ -887,7 +887,7 @@ function testOrm(dataSource) {
User.create({email: email, name: 'Nick'}, done); User.create({email: email, name: 'Nick'}, done);
}); });
}); });
var tests = 2; let tests = 2;
function done() { function done() {
process.nextTick(function() { process.nextTick(function() {
@ -900,7 +900,7 @@ function testOrm(dataSource) {
function doSortTest() { function doSortTest() {
User.all({order: 'email ASC', where: {name: 'Nick'}}, function(err, users) { User.all({order: 'email ASC', where: {name: 'Nick'}}, function(err, users) {
var _emails = emails.sort(); const _emails = emails.sort();
users.forEach(function(user, i) { users.forEach(function(user, i) {
test.equal(_emails[i], user.email, 'ASC sorting'); test.equal(_emails[i], user.email, 'ASC sorting');
}); });
@ -910,7 +910,7 @@ function testOrm(dataSource) {
function doReverseSortTest() { function doReverseSortTest() {
User.all({order: 'email DESC', where: {name: 'Nick'}}, function(err, users) { User.all({order: 'email DESC', where: {name: 'Nick'}}, function(err, users) {
var _emails = emails.sort().reverse(); const _emails = emails.sort().reverse();
users.forEach(function(user, i) { users.forEach(function(user, i) {
test.equal(_emails[i], user.email, 'DESC sorting'); 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) { it('should return id in find result even after updateAttributes', function(test) {
Post.create(function(err, post) { Post.create(function(err, post) {
var id = post.id; const id = post.id;
test.ok(post.published === false); test.ok(post.published === false);
post.updateAttributes({title: 'hey', published: true}, function() { post.updateAttributes({title: 'hey', published: true}, function() {
Post.find(id, function(err, post) { Post.find(id, function(err, post) {
@ -938,7 +938,7 @@ function testOrm(dataSource) {
}); });
it('should handle belongsTo correctly', function(test) { it('should handle belongsTo correctly', function(test) {
var passport = new Passport({ownerId: 16}); const passport = new Passport({ownerId: 16});
// sync getter // sync getter
test.equal(passport.owner(), 16); test.equal(passport.owner(), 16);
// sync setter // sync setter
@ -1017,7 +1017,7 @@ function testOrm(dataSource) {
if (dataSource.name !== 'mongoose' && dataSource.name !== 'neo4j') if (dataSource.name !== 'mongoose' && dataSource.name !== 'neo4j')
it('should update or create record', function(test) { it('should update or create record', function(test) {
var newData = { const newData = {
id: 1, id: 1,
title: 'New title (really new)', title: 'New title (really new)',
content: 'Some example content (updated)', content: 'Some example content (updated)',
@ -1058,7 +1058,7 @@ function testOrm(dataSource) {
User.setter.passwd = function(pass) { User.setter.passwd = function(pass) {
this._passwd = pass + 'salt'; this._passwd = pass + 'salt';
}; };
var u = new User({passwd: 'qwerty'}); const u = new User({passwd: 'qwerty'});
test.equal(u.passwd, 'qwertysalt'); test.equal(u.passwd, 'qwertysalt');
u.save(function(err, user) { u.save(function(err, user) {
User.findById(user.id, 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) { it('should work with typed and untyped nested collections', function(test) {
var post = new Post; const post = new Post;
var like = post.likes.push({foo: 'bar'}); const like = post.likes.push({foo: 'bar'});
test.equal(like.constructor.name, 'ListItem'); test.equal(like.constructor.name, 'ListItem');
var related = post.related.push({hello: 'world'}); const related = post.related.push({hello: 'world'});
test.ok(related.someMethod); test.ok(related.someMethod);
post.save(function(err, p) { post.save(function(err, p) {
test.equal(p.likes.nextid, 2); test.equal(p.likes.nextid, 2);
@ -1119,7 +1119,7 @@ function testOrm(dataSource) {
}); });
it('should find or create', function(test) { 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) { User.findOrCreate({where: {email: email}}, function(err, u, created) {
test.ok(u); test.ok(u);
test.ok(!u.age); test.ok(!u.age);

View File

@ -7,9 +7,9 @@
'use strict'; 'use strict';
/* global getSchema:false */ /* global getSchema:false */
var should = require('./init.js'); const should = require('./init.js');
var async = require('async'); const async = require('async');
var db, User, options, filter; let db, User, options, filter;
describe('crud-with-options', function() { describe('crud-with-options', function() {
before(function(done) { before(function(done) {
@ -193,7 +193,7 @@ describe('crud-with-options', function() {
describe('findByIds', function() { describe('findByIds', function() {
before(function(done) { before(function(done) {
var people = [ const people = [
{id: 1, name: 'a', vip: true}, {id: 1, name: 'a', vip: true},
{id: 2, name: 'b'}, {id: 2, name: 'b'},
{id: 3, name: 'c'}, {id: 3, name: 'c'},
@ -213,7 +213,7 @@ describe('crud-with-options', function() {
User.findByIds([3, 2, 1], function(err, users) { User.findByIds([3, 2, 1], function(err, users) {
should.exist(users); should.exist(users);
should.not.exist(err); 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']); names.should.eql(['c', 'b', 'a']);
done(); done();
}); });
@ -225,7 +225,7 @@ describe('crud-with-options', function() {
{where: {vip: true}}, options, function(err, users) { {where: {vip: true}}, options, function(err, users) {
should.exist(users); should.exist(users);
should.not.exist(err); should.not.exist(err);
var names = users.map(function(u) { const names = users.map(function(u) {
return u.name; return u.name;
}); });
names.should.eql(['d', 'a']); names.should.eql(['d', 'a']);
@ -407,15 +407,15 @@ describe('crud-with-options', function() {
describe('save', function() { describe('save', function() {
it('should allow save(options, cb)', function(done) { it('should allow save(options, cb)', function(done) {
var options = {foo: 'bar'}; const options = {foo: 'bar'};
var opts; let opts;
User.observe('after save', function(ctx, next) { User.observe('after save', function(ctx, next) {
opts = ctx.options; opts = ctx.options;
next(); next();
}); });
var u = new User(); const u = new User();
u.save(options, function(err) { u.save(options, function(err) {
should.not.exist(err); should.not.exist(err);
options.should.equal(opts); options.should.equal(opts);
@ -605,7 +605,7 @@ describe('upsertWithWhere', function() {
}); });
function seed(done) { function seed(done) {
var beatles = [ const beatles = [
{ {
id: 0, id: 0,
seq: 0, seq: 0,

View File

@ -5,12 +5,12 @@
'use strict'; 'use strict';
var should = require('./init.js'); const should = require('./init.js');
var DataSource = require('../lib/datasource.js').DataSource; const DataSource = require('../lib/datasource.js').DataSource;
describe('DataSource', function() { describe('DataSource', function() {
it('reports helpful error when connector init throws', function() { it('reports helpful error when connector init throws', function() {
var throwingConnector = { const throwingConnector = {
name: 'loopback-connector-throwing', name: 'loopback-connector-throwing',
initialize: function(ds, cb) { initialize: function(ds, cb) {
throw new Error('expected test error'); throw new Error('expected test error');
@ -50,7 +50,7 @@ describe('DataSource', function() {
* new DataSource(dsName, settings) without settings.name * new DataSource(dsName, settings) without settings.name
*/ */
it('should retain the name assigned to it', function() { it('should retain the name assigned to it', function() {
var dataSource = new DataSource('myDataSource', { const dataSource = new DataSource('myDataSource', {
connector: 'memory', connector: 'memory',
}); });
@ -61,7 +61,7 @@ describe('DataSource', function() {
* new DataSource(dsName, settings) * new DataSource(dsName, settings)
*/ */
it('should allow the name assigned to it to take precedence over the settings name', function() { 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', name: 'defaultDataSource',
connector: 'memory', connector: 'memory',
}); });
@ -73,7 +73,7 @@ describe('DataSource', function() {
* new DataSource(settings) with settings.name * new DataSource(settings) with settings.name
*/ */
it('should retain the name from the settings if no name is assigned', function() { it('should retain the name from the settings if no name is assigned', function() {
var dataSource = new DataSource({ const dataSource = new DataSource({
name: 'defaultDataSource', name: 'defaultDataSource',
connector: 'memory', connector: 'memory',
}); });
@ -85,7 +85,7 @@ describe('DataSource', function() {
* new DataSource(undefined, settings) * new DataSource(undefined, settings)
*/ */
it('should retain the name from the settings if name is undefined', function() { 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', name: 'defaultDataSource',
connector: 'memory', connector: 'memory',
}); });
@ -97,7 +97,7 @@ describe('DataSource', function() {
* new DataSource(settings) without settings.name * new DataSource(settings) without settings.name
*/ */
it('should use the connector name if no name is provided', function() { it('should use the connector name if no name is provided', function() {
var dataSource = new DataSource({ const dataSource = new DataSource({
connector: 'memory', connector: 'memory',
}); });
@ -108,14 +108,14 @@ describe('DataSource', function() {
* new DataSource(connectorInstance) * new DataSource(connectorInstance)
*/ */
it('should accept resolved connector', function() { it('should accept resolved connector', function() {
var mockConnector = { const mockConnector = {
name: 'loopback-connector-mock', name: 'loopback-connector-mock',
initialize: function(ds, cb) { initialize: function(ds, cb) {
ds.connector = mockConnector; ds.connector = mockConnector;
return cb(null); return cb(null);
}, },
}; };
var dataSource = new DataSource(mockConnector); const dataSource = new DataSource(mockConnector);
dataSource.name.should.equal('loopback-connector-mock'); dataSource.name.should.equal('loopback-connector-mock');
dataSource.connector.should.equal(mockConnector); dataSource.connector.should.equal(mockConnector);
@ -125,14 +125,14 @@ describe('DataSource', function() {
* new DataSource(dsName, connectorInstance) * new DataSource(dsName, connectorInstance)
*/ */
it('should accept dsName and resolved connector', function() { it('should accept dsName and resolved connector', function() {
var mockConnector = { const mockConnector = {
name: 'loopback-connector-mock', name: 'loopback-connector-mock',
initialize: function(ds, cb) { initialize: function(ds, cb) {
ds.connector = mockConnector; ds.connector = mockConnector;
return cb(null); return cb(null);
}, },
}; };
var dataSource = new DataSource('myDataSource', mockConnector); const dataSource = new DataSource('myDataSource', mockConnector);
dataSource.name.should.equal('myDataSource'); dataSource.name.should.equal('myDataSource');
dataSource.connector.should.equal(mockConnector); dataSource.connector.should.equal(mockConnector);
@ -142,21 +142,21 @@ describe('DataSource', function() {
* new DataSource(connectorInstance, settings) * new DataSource(connectorInstance, settings)
*/ */
it('should accept resolved connector and settings', function() { it('should accept resolved connector and settings', function() {
var mockConnector = { const mockConnector = {
name: 'loopback-connector-mock', name: 'loopback-connector-mock',
initialize: function(ds, cb) { initialize: function(ds, cb) {
ds.connector = mockConnector; ds.connector = mockConnector;
return cb(null); return cb(null);
}, },
}; };
var dataSource = new DataSource(mockConnector, {name: 'myDataSource'}); const dataSource = new DataSource(mockConnector, {name: 'myDataSource'});
dataSource.name.should.equal('myDataSource'); dataSource.name.should.equal('myDataSource');
dataSource.connector.should.equal(mockConnector); dataSource.connector.should.equal(mockConnector);
}); });
it('should set states correctly with eager connect', function(done) { it('should set states correctly with eager connect', function(done) {
var mockConnector = { const mockConnector = {
name: 'loopback-connector-mock', name: 'loopback-connector-mock',
initialize: function(ds, cb) { initialize: function(ds, cb) {
ds.connector = mockConnector; ds.connector = mockConnector;
@ -169,7 +169,7 @@ describe('DataSource', function() {
}); });
}, },
}; };
var dataSource = new DataSource(mockConnector); const dataSource = new DataSource(mockConnector);
// DataSource is instantiated // DataSource is instantiated
// connected: false, connecting: false, initialized: false // connected: false, connecting: false, initialized: false
dataSource.connected.should.be.false(); dataSource.connected.should.be.false();
@ -211,7 +211,7 @@ describe('DataSource', function() {
}); });
it('should set states correctly with deferred connect', function(done) { it('should set states correctly with deferred connect', function(done) {
var mockConnector = { const mockConnector = {
name: 'loopback-connector-mock', name: 'loopback-connector-mock',
initialize: function(ds, cb) { initialize: function(ds, cb) {
ds.connector = mockConnector; ds.connector = mockConnector;
@ -227,7 +227,7 @@ describe('DataSource', function() {
}); });
}, },
}; };
var dataSource = new DataSource(mockConnector); const dataSource = new DataSource(mockConnector);
// DataSource is instantiated // DataSource is instantiated
// connected: false, connecting: false, initialized: false // connected: false, connecting: false, initialized: false
dataSource.connected.should.be.false(); dataSource.connected.should.be.false();
@ -267,7 +267,7 @@ describe('DataSource', function() {
}); });
it('should set states correctly with lazyConnect = true', function(done) { it('should set states correctly with lazyConnect = true', function(done) {
var mockConnector = { const mockConnector = {
name: 'loopback-connector-mock', name: 'loopback-connector-mock',
initialize: function(ds, cb) { initialize: function(ds, cb) {
ds.connector = mockConnector; ds.connector = mockConnector;
@ -282,7 +282,7 @@ describe('DataSource', function() {
}); });
}, },
}; };
var dataSource = new DataSource(mockConnector, {lazyConnect: true}); const dataSource = new DataSource(mockConnector, {lazyConnect: true});
// DataSource is instantiated // DataSource is instantiated
// connected: false, connecting: false, initialized: false // connected: false, connecting: false, initialized: false
dataSource.connected.should.be.false(); dataSource.connected.should.be.false();

View File

@ -7,15 +7,15 @@
'use strict'; 'use strict';
/* global getSchema:false */ /* global getSchema:false */
var should = require('./init.js'); const should = require('./init.js');
var db, Model; let db, Model;
describe('datatypes', function() { describe('datatypes', function() {
before(function(done) { before(function(done) {
db = getSchema(); db = getSchema();
var Nested = db.define('Nested', {}); const Nested = db.define('Nested', {});
var modelTableSchema = { const modelTableSchema = {
str: String, str: String,
date: Date, date: Date,
num: Number, num: Number,
@ -30,7 +30,7 @@ describe('datatypes', function() {
it('should return 400 when property of type array is set to string value', it('should return 400 when property of type array is set to string value',
function(done) { function(done) {
var myModel = db.define('myModel', { const myModel = db.define('myModel', {
list: {type: ['object']}, list: {type: ['object']},
}); });
@ -42,7 +42,7 @@ describe('datatypes', function() {
it('should return 400 when property of type array is set to object value', it('should return 400 when property of type array is set to object value',
function(done) { function(done) {
var myModel = db.define('myModel', { const myModel = db.define('myModel', {
list: {type: ['object']}, list: {type: ['object']},
}); });
@ -53,7 +53,8 @@ describe('datatypes', function() {
}); });
it('should keep types when get read data from db', function(done) { it('should keep types when get read data from db', function(done) {
var d = new Date('2015-01-01T12:00:00'), id; const d = new Date('2015-01-01T12:00:00');
let id;
Model.create({ Model.create({
str: 'hello', date: d, num: '3', bool: 1, list: ['test'], arr: [1, 'str'], str: 'hello', date: d, num: '3', bool: 1, list: ['test'], arr: [1, 'str'],
@ -101,7 +102,8 @@ describe('datatypes', function() {
}); });
it('should respect data types when updating attributes', function(done) { it('should respect data types when updating attributes', function(done) {
var d = new Date, id; const d = new Date;
let id;
Model.create({ Model.create({
str: 'hello', date: d, num: '3', bool: 1}, function(err, m) { str: 'hello', date: d, num: '3', bool: 1}, function(err, m) {
@ -151,7 +153,7 @@ describe('datatypes', function() {
}); });
it('should not coerce nested objects into ModelConstructor types', 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'); coerced.nested.constructor.name.should.equal('Object');
}); });
@ -176,13 +178,13 @@ describe('datatypes', function() {
data: {type: 'string'}, data: {type: 'string'},
}); });
db.automigrate(['HandleNullModel'], function() { db.automigrate(['HandleNullModel'], function() {
let a = new Model(null); const a = new Model(null);
done(); done();
}); });
}); });
describe('model option persistUndefinedAsNull', function() { describe('model option persistUndefinedAsNull', function() {
var TestModel, isStrict; let TestModel, isStrict;
before(function(done) { before(function(done) {
db = getSchema(); db = getSchema();
TestModel = db.define( TestModel = db.define(
@ -203,7 +205,7 @@ describe('datatypes', function() {
}); });
it('should set missing optional properties to null', function(done) { 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) { TestModel.create({name: 'a-test-name'}, function(err, created) {
if (err) return done(err); if (err) return done(err);
created.should.have.properties(EXPECTED); created.should.have.properties(EXPECTED);
@ -217,8 +219,8 @@ describe('datatypes', function() {
}); });
it('should convert property value undefined to null', function(done) { it('should convert property value undefined to null', function(done) {
var EXPECTED = {desc: null, extra: null}; const EXPECTED = {desc: null, extra: null};
var data = {desc: undefined, extra: undefined}; const data = {desc: undefined, extra: undefined};
if (isStrict) { if (isStrict) {
// SQL-based connectors don't support dynamic properties // SQL-based connectors don't support dynamic properties
delete EXPECTED.extra; delete EXPECTED.extra;
@ -238,21 +240,21 @@ describe('datatypes', function() {
}); });
it('should convert undefined to null in the setter', function() { it('should convert undefined to null in the setter', function() {
var inst = new TestModel(); const inst = new TestModel();
inst.desc = undefined; inst.desc = undefined;
inst.should.have.property('desc', null); inst.should.have.property('desc', null);
inst.toObject().should.have.property('desc', null); inst.toObject().should.have.property('desc', null);
}); });
it('should use null in unsetAttribute()', function() { it('should use null in unsetAttribute()', function() {
var inst = new TestModel(); const inst = new TestModel();
inst.unsetAttribute('stars'); inst.unsetAttribute('stars');
inst.should.have.property('stars', null); inst.should.have.property('stars', null);
inst.toObject().should.have.property('stars', null); inst.toObject().should.have.property('stars', null);
}); });
it('should convert undefined to null on save', function(done) { 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) { if (isStrict) {
// SQL-based connectors don't support dynamic properties // SQL-based connectors don't support dynamic properties
delete EXPECTED.extra; delete EXPECTED.extra;
@ -298,7 +300,7 @@ describe('datatypes', function() {
}); });
it('should convert undefined to null in toObject()', 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.desc = undefined; // Note: this may be a no-op
inst.unsetAttribute('stars'); inst.unsetAttribute('stars');
inst.extra = undefined; inst.extra = undefined;

View File

@ -10,16 +10,16 @@
require('should'); require('should');
var DateString = require('../lib/date-string'); const DateString = require('../lib/date-string');
var fmt = require('util').format; const fmt = require('util').format;
var inspect = require('util').inspect; const inspect = require('util').inspect;
var os = require('os'); const os = require('os');
describe('DateString', function() { describe('DateString', function() {
describe('constructor', function() { describe('constructor', function() {
it('should support a valid date string', function() { it('should support a valid date string', function() {
var theDate = '2015-01-01'; const theDate = '2015-01-01';
var date = new DateString(theDate); const date = new DateString(theDate);
date.should.not.eql(null); date.should.not.eql(null);
date.when.should.eql(theDate); date.when.should.eql(theDate);
date.toString().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'); testInvalidInput('should throw on null input', null, 'Input must be a string');
it('should update internal date on set', function() { 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 = '2016-01-01';
date.when.should.eql('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! // The internal date representation should also be updated!
date._date.toString().should.eql(d.toString()); date._date.toString().should.eql(d.toString());
}); });
it('should return custom inspect output', function() { it('should return custom inspect output', function() {
var date = new DateString('2015-01-01'); const date = new DateString('2015-01-01');
var result = inspect(date); const result = inspect(date);
result.should.not.eql(null); result.should.not.eql(null);
result.should.eql(fmt('DateString ' + inspect({ result.should.eql(fmt('DateString ' + inspect({
when: date.when, when: date.when,
@ -55,24 +55,24 @@ describe('DateString', function() {
}); });
it('should return JSON output', function() { it('should return JSON output', function() {
var date = new DateString('2015-01-01'); const date = new DateString('2015-01-01');
var result = date.toJSON(); const result = date.toJSON();
result.should.eql(JSON.stringify({when: date.when})); result.should.eql(JSON.stringify({when: date.when}));
}); });
function testValidInput(msg, val) { function testValidInput(msg, val) {
it(msg, function() { it(msg, function() {
var theDate = new DateString(val); const theDate = new DateString(val);
theDate.when.should.eql(val); theDate.when.should.eql(val);
var d = new Date(val); const d = new Date(val);
theDate._date.toString().should.eql(d.toString()); theDate._date.toString().should.eql(d.toString());
}); });
} }
function testInvalidInput(msg, val, err) { function testInvalidInput(msg, val, err) {
it(msg, () => { it(msg, () => {
var fn = () => { const fn = () => {
var theDate = new DateString(val); const theDate = new DateString(val);
}; };
fn.should.throw(err); fn.should.throw(err);
}); });

View File

@ -7,10 +7,10 @@
'use strict'; 'use strict';
/* global getSchema:false */ /* global getSchema:false */
var should = require('./init.js'); const should = require('./init.js');
var async = require('async'); 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 // This test requires a connector that can
// handle a custom collection or table name // 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] add table for pgsql/mysql
// TODO [fabien] change model definition - see #293 // TODO [fabien] change model definition - see #293
var setupProducts = function(ids, done) { const setupProducts = function(ids, done) {
async.series([ async.series([
function(next) { function(next) {
Tool.create({name: 'Tool Z'}, function(err, inst) { Tool.create({name: 'Tool Z'}, function(err, inst) {
@ -72,7 +72,7 @@ describe('default scope', function() {
}); });
Product.lookupModel = function(data) { Product.lookupModel = function(data) {
var m = this.dataSource.models[data.kind]; const m = this.dataSource.models[data.kind];
if (m.base === this) return m; if (m.base === this) return m;
return this; return this;
}; };
@ -104,11 +104,11 @@ describe('default scope', function() {
// inst is only valid for instance methods // inst is only valid for instance methods
// like save, updateAttributes // like save, updateAttributes
var scopeFn = function(target, inst) { const scopeFn = function(target, inst) {
return {where: {kind: this.modelName}}; return {where: {kind: this.modelName}};
}; };
var propertiesFn = function(target, inst) { const propertiesFn = function(target, inst) {
return {kind: this.modelName}; return {kind: this.modelName};
}; };
@ -138,14 +138,14 @@ describe('default scope', function() {
}); });
describe('manipulation', function() { describe('manipulation', function() {
var ids = {}; const ids = {};
before(function(done) { before(function(done) {
db.automigrate(done); db.automigrate(done);
}); });
it('should return a scoped instance', function() { 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.name.should.equal('Product A');
p.kind.should.equal('Tool'); p.kind.should.equal('Tool');
p.setAttributes({kind: 'ignored'}); p.setAttributes({kind: 'ignored'});
@ -205,7 +205,7 @@ describe('default scope', function() {
}); });
it('should update a scoped instance - updateOrCreate', function(done) { 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) { Tool.updateOrCreate(data, function(err, p) {
should.not.exist(err); should.not.exist(err);
p.name.should.equal('Product A'); p.name.should.equal('Product A');
@ -217,7 +217,7 @@ describe('default scope', function() {
}); });
describe('findById', function() { describe('findById', function() {
var ids = {}; const ids = {};
before(function(done) { before(function(done) {
db.automigrate(setupProducts.bind(null, ids, done)); db.automigrate(setupProducts.bind(null, ids, done));
@ -250,7 +250,7 @@ describe('default scope', function() {
}); });
describe('find', function() { describe('find', function() {
var ids = {}; const ids = {};
before(function(done) { before(function(done) {
db.automigrate(setupProducts.bind(null, ids, done)); db.automigrate(setupProducts.bind(null, ids, done));
@ -322,7 +322,7 @@ describe('default scope', function() {
}); });
describe('exists', function() { describe('exists', function() {
var ids = {}; const ids = {};
before(function(done) { before(function(done) {
db.automigrate(setupProducts.bind(null, ids, done)); db.automigrate(setupProducts.bind(null, ids, done));
@ -370,7 +370,7 @@ describe('default scope', function() {
}); });
describe('count', function() { describe('count', function() {
var ids = {}; const ids = {};
before(function(done) { before(function(done) {
db.automigrate(setupProducts.bind(null, ids, done)); db.automigrate(setupProducts.bind(null, ids, done));
@ -418,7 +418,7 @@ describe('default scope', function() {
}); });
describe('removeById', function() { describe('removeById', function() {
var ids = {}; const ids = {};
function isDeleted(id, done) { function isDeleted(id, done) {
Product.exists(id, function(err, exists) { Product.exists(id, function(err, exists) {
@ -476,7 +476,7 @@ describe('default scope', function() {
}); });
describe('update', function() { describe('update', function() {
var ids = {}; const ids = {};
before(function(done) { before(function(done) {
db.automigrate(setupProducts.bind(null, ids, done)); db.automigrate(setupProducts.bind(null, ids, done));
@ -521,7 +521,7 @@ describe('default scope', function() {
}); });
describe('remove', function() { describe('remove', function() {
var ids = {}; const ids = {};
before(function(done) { before(function(done) {
db.automigrate(setupProducts.bind(null, ids, done)); db.automigrate(setupProducts.bind(null, ids, done));
@ -593,7 +593,7 @@ describe('default scope', function() {
}); });
describe('scopes', function() { describe('scopes', function() {
var ids = {}; const ids = {};
before(function(done) { before(function(done) {
db.automigrate(setupProducts.bind(null, ids, done)); db.automigrate(setupProducts.bind(null, ids, done));
@ -673,7 +673,7 @@ describe('default scope', function() {
products.should.have.length(2); products.should.have.length(2);
products[0].name.should.equal('Product'); products[0].name.should.equal('Product');
products[1].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.sort();
kinds.should.eql(['Thing', 'Widget']); kinds.should.eql(['Thing', 'Widget']);
done(); done();
@ -682,7 +682,7 @@ describe('default scope', function() {
}); });
describe('relations', function() { describe('relations', function() {
var ids = {}; const ids = {};
before(function(done) { before(function(done) {
db.automigrate(done); db.automigrate(done);
@ -817,7 +817,7 @@ describe('default scope', function() {
Person.findById(1, function(err, person) { Person.findById(1, function(err, person) {
should.not.exist(err); should.not.exist(err);
should.exist(person); should.exist(person);
var things = person.things(); const things = person.things();
should.exist(things); should.exist(things);
things.should.be.an.instanceOf(Array); things.should.be.an.instanceOf(Array);
things.should.have.length(1); things.should.have.length(1);

View File

@ -7,12 +7,12 @@
'use strict'; 'use strict';
/* global getSchema:false */ /* global getSchema:false */
var should = require('./init.js'); const should = require('./init.js');
var db = getSchema(); const db = getSchema();
describe('defaults', function() { describe('defaults', function() {
var Server; let Server;
before(function() { before(function() {
Server = db.define('Server', { Server = db.define('Server', {
@ -23,7 +23,7 @@ describe('defaults', function() {
}); });
it('should apply defaults on new', function() { it('should apply defaults on new', function() {
var s = new Server; const s = new Server;
s.port.should.equal(80); s.port.should.equal(80);
}); });

View File

@ -5,17 +5,17 @@
'use strict'; 'use strict';
var jdb = require('../'); const jdb = require('../');
var DataSource = jdb.DataSource; const DataSource = jdb.DataSource;
var should = require('./init.js'); const should = require('./init.js');
describe('Memory connector with mocked discovery', function() { describe('Memory connector with mocked discovery', function() {
var ds; let ds;
before(function() { before(function() {
ds = new DataSource({connector: 'memory'}); 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: 'INVENTORY', owner: 'STRONGLOOP'},
{type: 'table', name: 'LOCATION', 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', owner: 'STRONGLOOP',
tableName: 'INVENTORY', tableName: 'INVENTORY',
columnName: 'PRODUCT_ID', columnName: 'PRODUCT_ID',
@ -77,7 +77,7 @@ describe('Memory connector with mocked discovery', function() {
ds.discoverSchemas('INVENTORY', {}, function(err, schemas) { ds.discoverSchemas('INVENTORY', {}, function(err, schemas) {
if (err) return done(err); if (err) return done(err);
schemas.should.have.property('STRONGLOOP.INVENTORY'); schemas.should.have.property('STRONGLOOP.INVENTORY');
var s = schemas['STRONGLOOP.INVENTORY']; const s = schemas['STRONGLOOP.INVENTORY'];
s.name.should.be.eql('Inventory'); s.name.should.be.eql('Inventory');
Object.keys(s.properties).should.be.eql( Object.keys(s.properties).should.be.eql(
['productId', 'locationId', 'available', 'total'] ['productId', 'locationId', 'available', 'total']
@ -95,7 +95,7 @@ describe('Memory connector with mocked discovery', function() {
}, function(err, schemas) { }, function(err, schemas) {
if (err) return done(err); if (err) return done(err);
schemas.should.have.property('STRONGLOOP.INVENTORY'); schemas.should.have.property('STRONGLOOP.INVENTORY');
var s = schemas['STRONGLOOP.INVENTORY']; const s = schemas['STRONGLOOP.INVENTORY'];
s.name.should.be.eql('inventory'); s.name.should.be.eql('inventory');
Object.keys(s.properties).should.be.eql( Object.keys(s.properties).should.be.eql(
['product_id', 'location_id', 'available', 'total'] ['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) { ds.discoverSchemas('INVENTORY', {nameMapper: null}, function(err, schemas) {
if (err) return done(err); if (err) return done(err);
schemas.should.have.property('STRONGLOOP.INVENTORY'); schemas.should.have.property('STRONGLOOP.INVENTORY');
var s = schemas['STRONGLOOP.INVENTORY']; const s = schemas['STRONGLOOP.INVENTORY'];
s.name.should.be.eql('INVENTORY'); s.name.should.be.eql('INVENTORY');
Object.keys(s.properties).should.be.eql( Object.keys(s.properties).should.be.eql(
['PRODUCT_ID', 'LOCATION_ID', 'AVAILABLE', 'TOTAL'] ['PRODUCT_ID', 'LOCATION_ID', 'AVAILABLE', 'TOTAL']
@ -120,7 +120,7 @@ describe('Memory connector with mocked discovery', function() {
it('should honor connector\'s discoverSchemas implementation', it('should honor connector\'s discoverSchemas implementation',
function(done) { function(done) {
var models = { const models = {
inventory: { inventory: {
product: {type: 'string'}, product: {type: 'string'},
location: {type: 'string'}, location: {type: 'string'},
@ -140,7 +140,7 @@ describe('Memory connector with mocked discovery', function() {
it('should callback function, passed as options parameter', it('should callback function, passed as options parameter',
function(done) { function(done) {
var models = { const models = {
inventory: { inventory: {
product: {type: 'string'}, product: {type: 'string'},
location: {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); if (err) return done(err);
schemas.should.be.eql(models); schemas.should.be.eql(models);
done(); done();
@ -168,7 +168,7 @@ describe('Memory connector with mocked discovery', function() {
.then(function(schemas) { .then(function(schemas) {
schemas.should.have.property('STRONGLOOP.INVENTORY'); schemas.should.have.property('STRONGLOOP.INVENTORY');
var s = schemas['STRONGLOOP.INVENTORY']; const s = schemas['STRONGLOOP.INVENTORY'];
s.name.should.be.eql('Inventory'); s.name.should.be.eql('Inventory');
Object.keys(s.properties).should.be.eql( Object.keys(s.properties).should.be.eql(
@ -182,8 +182,8 @@ describe('Memory connector with mocked discovery', function() {
}); });
describe('discoverSchema', function() { describe('discoverSchema', function() {
var models; let models;
var schema; let schema;
before(function() { before(function() {
schema = { schema = {
name: 'Inventory', name: 'Inventory',
@ -265,7 +265,7 @@ describe('Memory connector with mocked discovery', function() {
}); });
it('should callback function, passed as options parameter', function(done) { 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); if (err) return done(err);
schemas.should.be.eql(schema); schemas.should.be.eql(schema);
done(); done();
@ -288,11 +288,11 @@ describe('Memory connector with mocked discovery', function() {
}); });
describe('discoverModelDefinitions', function() { describe('discoverModelDefinitions', function() {
var ds; let ds;
before(function() { before(function() {
ds = new DataSource({connector: 'memory'}); 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: 'INVENTORY', owner: 'STRONGLOOP'},
{type: 'table', name: 'LOCATION', owner: 'STRONGLOOP'}]; {type: 'table', name: 'LOCATION', owner: 'STRONGLOOP'}];
@ -307,7 +307,7 @@ describe('discoverModelDefinitions', function() {
ds.discoverModelDefinitions({}, function(err, schemas) { ds.discoverModelDefinitions({}, function(err, schemas) {
if (err) return done(err); if (err) return done(err);
var tableNames = schemas.map(function(s) { const tableNames = schemas.map(function(s) {
return s.name; return s.name;
}); });
@ -319,10 +319,10 @@ describe('discoverModelDefinitions', function() {
}); });
it('should callback function, passed as options parameter', function(done) { 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); if (err) return done(err);
var tableNames = schemas.map(function(s) { const tableNames = schemas.map(function(s) {
return s.name; return s.name;
}); });
@ -338,7 +338,7 @@ describe('discoverModelDefinitions', function() {
it('should discover model using `discoverModelDefinitions` - promise variant', function(done) { it('should discover model using `discoverModelDefinitions` - promise variant', function(done) {
ds.discoverModelDefinitions({}) ds.discoverModelDefinitions({})
.then(function(schemas) { .then(function(schemas) {
var tableNames = schemas.map(function(s) { const tableNames = schemas.map(function(s) {
return s.name; return s.name;
}); });
@ -354,8 +354,8 @@ describe('discoverModelDefinitions', function() {
}); });
describe('discoverModelProperties', function() { describe('discoverModelProperties', function() {
var ds; let ds;
var modelProperties; let modelProperties;
before(function() { before(function() {
ds = new DataSource({connector: 'memory'}); ds = new DataSource({connector: 'memory'});
@ -408,7 +408,7 @@ describe('discoverModelProperties', function() {
}); });
it('should callback function, passed as options parameter', function(done) { 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); if (err) return done(err);
schemas.should.be.eql(modelProperties); schemas.should.be.eql(modelProperties);
@ -440,8 +440,8 @@ describe('discoverModelProperties', function() {
}); });
describe('discoverPrimaryKeys', function() { describe('discoverPrimaryKeys', function() {
var ds; let ds;
var modelProperties, primaryKeys; let modelProperties, primaryKeys;
before(function() { before(function() {
ds = new DataSource({connector: 'memory'}); ds = new DataSource({connector: 'memory'});
@ -478,7 +478,7 @@ describe('discoverPrimaryKeys', function() {
}); });
it('should callback function, passed as options parameter', function(done) { 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); if (err) return done(err);
modelPrimaryKeys.should.be.eql(primaryKeys); modelPrimaryKeys.should.be.eql(primaryKeys);
@ -500,8 +500,8 @@ describe('discoverPrimaryKeys', function() {
}); });
describe('discoverForeignKeys', function() { describe('discoverForeignKeys', function() {
var ds; let ds;
var modelProperties, foreignKeys; let modelProperties, foreignKeys;
before(function() { before(function() {
ds = new DataSource({connector: 'memory'}); ds = new DataSource({connector: 'memory'});
@ -534,7 +534,7 @@ describe('discoverForeignKeys', function() {
}); });
it('should callback function, passed as options parameter', function(done) { 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); if (err) return done(err);
modelForeignKeys.should.be.eql(foreignKeys); modelForeignKeys.should.be.eql(foreignKeys);
@ -557,8 +557,8 @@ describe('discoverForeignKeys', function() {
}); });
describe('discoverExportedForeignKeys', function() { describe('discoverExportedForeignKeys', function() {
var ds; let ds;
var modelProperties, exportedForeignKeys; let modelProperties, exportedForeignKeys;
before(function() { before(function() {
ds = new DataSource({connector: 'memory'}); ds = new DataSource({connector: 'memory'});
@ -591,7 +591,7 @@ describe('discoverExportedForeignKeys', function() {
}); });
it('should callback function, passed as options parameter', function(done) { 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); if (err) return done(err);
modelForeignKeys.should.be.eql(exportedForeignKeys); modelForeignKeys.should.be.eql(exportedForeignKeys);
@ -615,9 +615,9 @@ describe('discoverExportedForeignKeys', function() {
}); });
describe('Mock connector', function() { describe('Mock connector', function() {
var mockConnectors = require('./mock-connectors'); const mockConnectors = require('./mock-connectors');
describe('customFieldSettings', function() { describe('customFieldSettings', function() {
var ds = new DataSource(mockConnectors.customFieldSettings); const ds = new DataSource(mockConnectors.customFieldSettings);
it('should be present in discoverSchemas', function(done) { it('should be present in discoverSchemas', function(done) {
ds.discoverSchemas('person', function(err, schemas) { ds.discoverSchemas('person', function(err, schemas) {
@ -632,7 +632,8 @@ describe('Mock connector', function() {
}); });
describe('Default memory connector', function() { describe('Default memory connector', function() {
var ds, nonExistantError = 'Table \'NONEXISTENT\' does not exist.'; const nonExistantError = 'Table \'NONEXISTENT\' does not exist.';
let ds;
before(function() { before(function() {
ds = new DataSource({connector: 'memory'}); ds = new DataSource({connector: 'memory'});

View File

@ -5,19 +5,19 @@
// This test written in mocha+should.js // This test written in mocha+should.js
'use strict'; 'use strict';
var should = require('./init.js'); const should = require('./init.js');
var assert = require('assert'); const assert = require('assert');
var jdb = require('../'); const jdb = require('../');
var ModelBuilder = jdb.ModelBuilder; const ModelBuilder = jdb.ModelBuilder;
describe('exclude properties ', function() { describe('exclude properties ', function() {
it('from base model', function(done) { 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 // create a base model User which has name and password properties. id property gets
// internally created for the User Model // internally created for the User Model
var User = ds.define('User', {name: String, password: String}); const User = ds.define('User', {name: String, password: String});
var properties = User.definition.properties; let properties = User.definition.properties;
// User should have id, name & password properties // User should have id, name & password properties
assert(('id' in properties) && ('password' in properties) && ('name' in properties), assert(('id' in properties) && ('password' in properties) && ('name' in properties),
'User should have id, name & password 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 excludeBaseProperties, 'password' and 'id' gets excluded from base User model
// With idInjection: false - id property of sub Model Customer gets excluded. At the end // 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). // 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']}); {idInjection: false, excludeBaseProperties: ['password', 'id']});
// Customer should have these properties: name(from UserModel) & vip // Customer should have these properties: name(from UserModel) & vip
properties = Customer.definition.properties; properties = Customer.definition.properties;

View File

@ -10,36 +10,36 @@
require('should'); require('should');
var GeoPoint = require('../lib/geo').GeoPoint; const GeoPoint = require('../lib/geo').GeoPoint;
var nearFilter = require('../lib/geo').nearFilter; const nearFilter = require('../lib/geo').nearFilter;
var geoFilter = require('../lib/geo').filter; const geoFilter = require('../lib/geo').filter;
var DELTA = 0.0000001; const DELTA = 0.0000001;
describe('GeoPoint', function() { describe('GeoPoint', function() {
describe('constructor', function() { describe('constructor', function() {
it('should support a valid array', 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.lat.should.equal(-34);
point.lng.should.equal(150); point.lng.should.equal(150);
}); });
it('should support a valid object', function() { 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.lat.should.equal(-34);
point.lng.should.equal(150); point.lng.should.equal(150);
}); });
it('should support valid string geo coordinates', function() { 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.lat.should.equal(-34);
point.lng.should.equal(150); point.lng.should.equal(150);
}); });
it('should support coordinates as inline parameters', function() { 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.lat.should.equal(-34);
point.lng.should.equal(150); point.lng.should.equal(150);
@ -47,7 +47,7 @@ describe('GeoPoint', function() {
it('should reject invalid parameters', function() { it('should reject invalid parameters', function() {
/* jshint -W024 */ /* jshint -W024 */
var fn = function() { let fn = function() {
new GeoPoint('150,-34'); new GeoPoint('150,-34');
}; };
fn.should.throw(); fn.should.throw();
@ -84,17 +84,17 @@ describe('GeoPoint', function() {
describe('toString()', function() { describe('toString()', function() {
it('should return a string in the form "lat,lng"', 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'); point.toString().should.equal('-34,150');
}); });
}); });
describe('distance calculation between two points', function() { describe('distance calculation between two points', function() {
var here = new GeoPoint({lat: 40.77492964101182, lng: -73.90950187151662}); const here = new GeoPoint({lat: 40.77492964101182, lng: -73.90950187151662});
var there = new GeoPoint({lat: 40.7753227, lng: -73.909217}); const there = new GeoPoint({lat: 40.7753227, lng: -73.909217});
it('should return value in miles by default', function() { 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.a.Number;
distance.should.be.approximately(0.03097916611592679, DELTA); distance.should.be.approximately(0.03097916611592679, DELTA);
}); });
@ -109,7 +109,7 @@ describe('GeoPoint', function() {
* - `degrees` * - `degrees`
*/ */
var distance = here.distanceTo(there, {type: 'radians'}); let distance = here.distanceTo(there, {type: 'radians'});
distance.should.be.a.Number; distance.should.be.a.Number;
distance.should.be.approximately(0.000007825491914348416, DELTA); distance.should.be.approximately(0.000007825491914348416, DELTA);
@ -137,7 +137,7 @@ describe('GeoPoint', function() {
describe('nearFilter()', function() { describe('nearFilter()', function() {
it('should return a filter includes minDistance if where contains minDistance option', function() { it('should return a filter includes minDistance if where contains minDistance option', function() {
var where = { const where = {
location: { location: {
near: { near: {
lat: 40.77492964101182, lat: 40.77492964101182,
@ -146,7 +146,7 @@ describe('GeoPoint', function() {
minDistance: 100, minDistance: 100,
}, },
}; };
var filter = nearFilter(where); const filter = nearFilter(where);
filter[0].key.should.equal('location'); filter[0].key.should.equal('location');
filter[0].should.have.properties({ filter[0].should.have.properties({
key: 'location', key: 'location',
@ -161,7 +161,7 @@ describe('GeoPoint', function() {
describe('filter()', function() { describe('filter()', function() {
it('should be able to filter geo points via minDistance', function() { it('should be able to filter geo points via minDistance', function() {
var points = [{ const points = [{
location: { location: {
lat: 30.283552, lat: 30.283552,
lng: 120.126048, lng: 120.126048,
@ -187,7 +187,7 @@ describe('GeoPoint', function() {
lng: 121.483687, lng: 121.483687,
}, },
}]; }];
var filter = [{ const filter = [{
key: 'location', key: 'location',
near: { near: {
lat: 30.278562, lat: 30.278562,
@ -196,7 +196,7 @@ describe('GeoPoint', function() {
unit: 'meters', unit: 'meters',
minDistance: 10000, minDistance: 10000,
}]; }];
var results = geoFilter(points, filter); const results = geoFilter(points, filter);
results.length.should.be.equal(3); results.length.should.be.equal(3);
}); });
}); });

View File

@ -4,7 +4,7 @@
// License text available at https://opensource.org/licenses/MIT // License text available at https://opensource.org/licenses/MIT
'use strict'; 'use strict';
var fmt = require('util').format; const fmt = require('util').format;
exports.describeIf = function describeIf(cond, name, fn) { exports.describeIf = function describeIf(cond, name, fn) {
if (cond) if (cond)

View File

@ -4,7 +4,7 @@
// License text available at https://opensource.org/licenses/MIT // License text available at https://opensource.org/licenses/MIT
'use strict'; 'use strict';
var traverse = require('traverse'); const traverse = require('traverse');
exports.ContextRecorder = ContextRecorder; exports.ContextRecorder = ContextRecorder;
exports.deepCloneToObject = deepCloneToObject; exports.deepCloneToObject = deepCloneToObject;
@ -18,7 +18,7 @@ function ContextRecorder(initialValue) {
} }
ContextRecorder.prototype.recordAndNext = function(transformFm) { ContextRecorder.prototype.recordAndNext = function(transformFm) {
var self = this; const self = this;
return function(context, next) { return function(context, next) {
if (typeof transformFm === 'function') { if (typeof transformFm === 'function') {
transformFm(context); transformFm(context);

View File

@ -16,12 +16,12 @@ function HookMonitor(opts) {
} }
HookMonitor.prototype.install = function(ObservedModel, hookNames) { HookMonitor.prototype.install = function(ObservedModel, hookNames) {
var monitor = this; const monitor = this;
this.names = []; this.names = [];
ObservedModel._notify = ObservedModel.notifyObserversOf; ObservedModel._notify = ObservedModel.notifyObserversOf;
ObservedModel.notifyObserversOf = function(operation, context, callback) { ObservedModel.notifyObserversOf = function(operation, context, callback) {
if (!Array.isArray(hookNames) || hookNames.indexOf(operation) !== -1) { if (!Array.isArray(hookNames) || hookNames.indexOf(operation) !== -1) {
var item = monitor.options.includeModelName ? const item = monitor.options.includeModelName ?
ObservedModel.modelName + ':' + operation : ObservedModel.modelName + ':' + operation :
operation; operation;
monitor.names.push(item); monitor.names.push(item);

View File

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

View File

@ -7,14 +7,14 @@
// This test written in mocha+should.js // This test written in mocha+should.js
/* global getSchema:false */ /* global getSchema:false */
var should = require('./init.js'); const should = require('./init.js');
var j = require('../'), const j = require('../'),
Schema = j.Schema, Schema = j.Schema,
AbstractClass = j.AbstractClass, AbstractClass = j.AbstractClass,
Hookable = j.Hookable, Hookable = j.Hookable;
db, User; let db, User;
describe('hooks', function() { describe('hooks', function() {
before(function(done) { before(function(done) {
@ -43,7 +43,7 @@ describe('hooks', function() {
}); });
it('should be triggered on create', function(done) { it('should be triggered on create', function(done) {
var user; let user;
User.afterInitialize = function() { User.afterInitialize = function() {
if (this.name === 'Nickolay') { if (this.name === 'Nickolay') {
this.name += ' Rozental'; this.name += ' Rozental';
@ -70,7 +70,7 @@ describe('hooks', function() {
should.fail('This should not be called'); should.fail('This should not be called');
next(); next();
}; };
var u = new User; const u = new User;
}); });
it('should be triggered on new+save', function(done) { 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) { 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) { User.dataSource.connector.create = function(modelName, id, cb) {
cb(new Error('error')); cb(new Error('error'));
}; };
@ -99,7 +99,7 @@ describe('hooks', function() {
next(new Error('fail in beforeCreate')); 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) { User.dataSource.connector.create = function(modelName, id, cb) {
throw new Error('shouldn\'t be called'); throw new Error('shouldn\'t be called');
}; };
@ -259,7 +259,7 @@ describe('hooks', function() {
should.fail('afterUpdate shouldn\'t be called'); should.fail('afterUpdate shouldn\'t be called');
}; };
User.create(function(err, user) { 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 = function(modelName, id, cb) {
User.dataSource.connector.save = save; User.dataSource.connector.save = save;
cb(new Error('Error')); cb(new Error('Error'));
@ -276,7 +276,7 @@ describe('hooks', function() {
afterEach(removeHooks('Destroy')); afterEach(removeHooks('Destroy'));
it('should be triggered on destroy', function(done) { it('should be triggered on destroy', function(done) {
var hook = 'not called'; let hook = 'not called';
User.beforeDestroy = function(next) { User.beforeDestroy = function(next) {
hook = 'called'; hook = 'called';
next(); next();
@ -291,7 +291,7 @@ describe('hooks', function() {
}); });
it('should not trigger after-hook on failed destroy', function(done) { 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) { User.dataSource.connector.destroy = function(modelName, id, cb) {
cb(new Error('error')); cb(new Error('error'));
}; };
@ -308,7 +308,7 @@ describe('hooks', function() {
}); });
describe('lifecycle', function() { describe('lifecycle', function() {
var life = [], user; let life = [], user;
before(function(done) { before(function(done) {
User.beforeSave = function(d) { User.beforeSave = function(d) {
life.push('beforeSave'); life.push('beforeSave');
@ -379,7 +379,7 @@ describe('hooks', function() {
}); });
it('should describe new+save sequence', function(done) { it('should describe new+save sequence', function(done) {
var u = new User; const u = new User;
u.save(function() { u.save(function() {
life.should.eql([ life.should.eql([
'afterInitialize', 'afterInitialize',
@ -436,7 +436,8 @@ describe('hooks', function() {
}); });
function addHooks(name, done) { function addHooks(name, done) {
var called = false, random = String(Math.floor(Math.random() * 1000)); const random = String(Math.floor(Math.random() * 1000));
let called = false;
User['before' + name] = function(next, data) { User['before' + name] = function(next, data) {
called = true; called = true;
data.email = random; data.email = random;

View File

@ -6,19 +6,19 @@
'use strict'; 'use strict';
/* global getSchema:false, connectorCapabilities:false */ /* global getSchema:false, connectorCapabilities:false */
var assert = require('assert'); const assert = require('assert');
var async = require('async'); const async = require('async');
var bdd = require('./helpers/bdd-if'); const bdd = require('./helpers/bdd-if');
var should = require('./init.js'); 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']; const knownUsers = ['User A', 'User B', 'User C', 'User D', 'User E'];
var knownPassports = ['1', '2', '3', '4']; const knownPassports = ['1', '2', '3', '4'];
var knownPosts = ['Post A', 'Post B', 'Post C', 'Post D', 'Post E']; const knownPosts = ['Post A', 'Post B', 'Post C', 'Post D', 'Post E'];
var knownProfiles = ['Profile A', 'Profile B', 'Profile Z']; const knownProfiles = ['Profile A', 'Profile B', 'Profile Z'];
describe('include', function() { describe('include', function() {
before(setup); before(setup);
@ -34,7 +34,7 @@ describe('include', function() {
// The __cachedRelations should be removed from json output // The __cachedRelations should be removed from json output
p.toJSON().should.not.have.property('__cachedRelations'); p.toJSON().should.not.have.property('__cachedRelations');
var owner = p.__cachedRelations.owner; const owner = p.__cachedRelations.owner;
if (!p.ownerId) { if (!p.ownerId) {
should.not.exist(owner); should.not.exist(owner);
} else { } else {
@ -49,7 +49,7 @@ describe('include', function() {
it('does not return included item if FK is excluded', function(done) { it('does not return included item if FK is excluded', function(done) {
Passport.find({include: 'owner', fields: 'number'}, function(err, passports) { Passport.find({include: 'owner', fields: 'number'}, function(err, passports) {
if (err) return done(err); if (err) return done(err);
var owner = passports[0].toJSON().owner; const owner = passports[0].toJSON().owner;
should.not.exist(owner); should.not.exist(owner);
done(); done();
}); });
@ -117,13 +117,13 @@ describe('include', function() {
user.save(function(err) { // save the returned user user.save(function(err) { // save the returned user
if (err) return finish(err); if (err) return finish(err);
// should not store in db the posts // should not store in db the posts
var dsName = User.dataSource.name; const dsName = User.dataSource.name;
if (dsName === 'memory') { if (dsName === 'memory') {
JSON.parse(User.dataSource.adapter.cache.User[1]).should.not.have.property('posts'); JSON.parse(User.dataSource.adapter.cache.User[1]).should.not.have.property('posts');
finish(); finish();
} else if (dsName === 'mongodb') { // Check native mongodb connector } else if (dsName === 'mongodb') { // Check native mongodb connector
// get hold of native mongodb collection // 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}) dbCollection.findOne({_id: user.id})
.then(function(foundUser) { .then(function(foundUser) {
if (!foundUser) { if (!foundUser) {
@ -153,7 +153,7 @@ describe('include', function() {
// The __cachedRelations should be removed from json output // The __cachedRelations should be removed from json output
p.toJSON().should.not.have.property('__cachedRelations'); p.toJSON().should.not.have.property('__cachedRelations');
var user = p.__cachedRelations.owner; const user = p.__cachedRelations.owner;
if (!p.ownerId) { if (!p.ownerId) {
should.not.exist(user); should.not.exist(user);
} else { } else {
@ -183,7 +183,7 @@ describe('include', function() {
// The __cachedRelations should be removed from json output // The __cachedRelations should be removed from json output
passport.toJSON().should.not.have.property('__cachedRelations'); passport.toJSON().should.not.have.property('__cachedRelations');
var user = passport.__cachedRelations.owner; const user = passport.__cachedRelations.owner;
should.exist(user); should.exist(user);
user.id.should.eql(passport.ownerId); user.id.should.eql(passport.ownerId);
user.__cachedRelations.should.have.property('posts'); user.__cachedRelations.should.have.property('posts');
@ -199,7 +199,7 @@ describe('include', function() {
should.not.exist(err); should.not.exist(err);
should.exist(passports); should.exist(passports);
passports.length.should.be.ok; passports.length.should.be.ok;
var posts; let posts;
if (connectorCapabilities.adhocSort !== false) { if (connectorCapabilities.adhocSort !== false) {
posts = passports[0].owner().posts(); posts = passports[0].owner().posts();
posts.should.have.length(3); posts.should.have.length(3);
@ -222,7 +222,7 @@ describe('include', function() {
passports.length.should.be.ok; passports.length.should.be.ok;
passports.forEach(function(p) { passports.forEach(function(p) {
p.__cachedRelations.should.have.property('owner'); p.__cachedRelations.should.have.property('owner');
var user = p.__cachedRelations.owner; const user = p.__cachedRelations.owner;
if (!p.ownerId) { if (!p.ownerId) {
should.not.exist(user); should.not.exist(user);
} else { } else {
@ -235,7 +235,7 @@ describe('include', function() {
pp.userId.toString().should.eql(user.id.toString()); pp.userId.toString().should.eql(user.id.toString());
pp.should.have.property('author'); pp.should.have.property('author');
pp.__cachedRelations.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); author.id.should.eql(user.id);
}); });
} }
@ -253,7 +253,7 @@ describe('include', function() {
}, function(err, passports) { }, function(err, passports) {
should.not.exist(err); should.not.exist(err);
should.exist(passports); should.exist(passports);
var passport, owner, posts; let passport, owner, posts;
if (connectorCapabilities.adhocSort !== false) { if (connectorCapabilities.adhocSort !== false) {
passports.length.should.equal(4); passports.length.should.equal(4);
@ -317,10 +317,10 @@ describe('include', function() {
}, function(err, passports) { }, function(err, passports) {
if (err) return done(err); if (err) return done(err);
passports.length.should.equal(2); 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.length.should.equal(1);
posts1[0].title.should.equal('Post C'); 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.length.should.equal(1);
posts2[0].title.should.equal('Post D'); posts2[0].title.should.equal('Post D');
@ -344,9 +344,9 @@ describe('include', function() {
}, function(err, passports) { }, function(err, passports) {
if (err) return done(err); if (err) return done(err);
passports.length.should.equal(2); passports.length.should.equal(2);
var owner = passports[0].toJSON().owner; let owner = passports[0].toJSON().owner;
if (owner) { if (owner) {
var posts1 = owner.posts; const posts1 = owner.posts;
posts1.length.should.belowOrEqual(1); posts1.length.should.belowOrEqual(1);
if (posts1.length === 1) { if (posts1.length === 1) {
posts1[0].title.should.be.oneOf(knownPosts); posts1[0].title.should.be.oneOf(knownPosts);
@ -354,7 +354,7 @@ describe('include', function() {
} }
owner = passports[1].toJSON().owner; owner = passports[1].toJSON().owner;
if (owner) { if (owner) {
var posts2 = owner.posts; const posts2 = owner.posts;
posts2.length.should.belowOrEqual(1); posts2.length.should.belowOrEqual(1);
if (posts2.length === 1) { if (posts2.length === 1) {
posts2[0].title.should.be.oneOf(knownPosts); posts2[0].title.should.be.oneOf(knownPosts);
@ -394,10 +394,10 @@ describe('include', function() {
if (err) return done(err); if (err) return done(err);
passports.length.should.equal(4); 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.length.should.equal(3);
posts1[0].title.should.equal('Post A'); 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.length.should.equal(1);
posts2[0].title.should.equal('Post D'); posts2[0].title.should.equal('Post D');
@ -417,7 +417,7 @@ describe('include', function() {
}, function(err, user) { }, function(err, user) {
if (err) return done(err); 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 // eql instead of equal because mongo uses object id type
passport.id.should.eql(createdPassports[0].id); passport.id.should.eql(createdPassports[0].id);
passport.ownerId.should.eql(createdPassports[0].ownerId); passport.ownerId.should.eql(createdPassports[0].ownerId);
@ -448,9 +448,9 @@ describe('include', function() {
user.name.should.equal('User A'); user.name.should.equal('User A');
user.age.should.equal(21); user.age.should.equal(21);
user.id.should.eql(createdUsers[0].id); user.id.should.eql(createdUsers[0].id);
var posts = user.posts(); const posts = user.posts();
posts.length.should.equal(1); posts.length.should.equal(1);
var post = posts[0]; const post = posts[0];
post.title.should.equal('Post A'); post.title.should.equal('Post A');
// eql instead of equal because mongo uses object id type // eql instead of equal because mongo uses object id type
post.userId.should.eql(createdPosts[0].userId); post.userId.should.eql(createdPosts[0].userId);
@ -488,7 +488,7 @@ describe('include', function() {
}, function(err, user) { }, function(err, user) {
if (err) return done(err); 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]); ids.should.eql([createdPosts[1].id, createdPosts[2].id]);
done(); done();
@ -506,7 +506,7 @@ describe('include', function() {
}, function(err, user) { }, function(err, user) {
if (err) return done(err); 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]); ids.should.eql([createdPosts[1].id, createdPosts[2].id]);
done(); done();
@ -518,8 +518,8 @@ describe('include', function() {
User.findOne({include: {relation: 'posts'}}, function(err, user) { User.findOne({include: {relation: 'posts'}}, function(err, user) {
if (err) return done(err); if (err) return done(err);
var posts = user.posts(); const posts = user.posts();
var ids = posts.map(function(p) { return p.id; }); const ids = posts.map(function(p) { return p.id; });
ids.should.eql([ ids.should.eql([
createdPosts[0].id, createdPosts[0].id,
createdPosts[1].id, createdPosts[1].id,
@ -586,7 +586,7 @@ describe('include', function() {
user.age.should.equal(21); user.age.should.equal(21);
// eql instead of equal because mongo uses object id type // eql instead of equal because mongo uses object id type
user.id.should.eql(createdUsers[0].id); user.id.should.eql(createdUsers[0].id);
var profile = user.profile(); const profile = user.profile();
profile.profileName.should.equal('Profile A'); profile.profileName.should.equal('Profile A');
// eql instead of equal because mongo uses object id type // eql instead of equal because mongo uses object id type
profile.userId.should.eql(createdProfiles[0].userId); profile.userId.should.eql(createdProfiles[0].userId);
@ -621,9 +621,9 @@ describe('include', function() {
}); });
it('works when hasManyThrough is called', function(done) { it('works when hasManyThrough is called', function(done) {
var Physician = db.define('Physician', {name: String}); const Physician = db.define('Physician', {name: String});
var Patient = db.define('Patient', {name: String}); const Patient = db.define('Patient', {name: String});
var Appointment = db.define('Appointment', { const Appointment = db.define('Appointment', {
date: { date: {
type: Date, type: Date,
default: function() { 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}); Physician.hasMany(Patient, {through: Appointment});
Patient.hasMany(Physician, {through: Appointment}); Patient.hasMany(Physician, {through: Appointment});
@ -651,7 +651,7 @@ describe('include', function() {
if (err) return done(err); if (err) return done(err);
patients.should.have.length(1); patients.should.have.length(1);
var p = patients[0]; const p = patients[0];
p.name.should.equal('a'); p.name.should.equal('a');
p.addressId.should.eql(patient.addressId); p.addressId.should.eql(patient.addressId);
p.address().id.should.eql(address.id); p.address().id.should.eql(address.id);
@ -673,7 +673,7 @@ describe('include', function() {
profile.profileName.should.equal('Profile A'); profile.profileName.should.equal('Profile A');
profile.userId.should.eql(createdProfiles[0].userId); profile.userId.should.eql(createdProfiles[0].userId);
profile.id.should.eql(createdProfiles[0].id); profile.id.should.eql(createdProfiles[0].id);
var user = profile.user(); const user = profile.user();
user.name.should.equal('User A'); user.name.should.equal('User A');
user.age.should.equal(21); user.age.should.equal(21);
user.id.should.eql(createdUsers[0].id); user.id.should.eql(createdUsers[0].id);
@ -696,10 +696,10 @@ describe('include', function() {
}, function(err, user) { }, function(err, user) {
if (err) return done(err); if (err) return done(err);
var passport = user.passports()[0]; const passport = user.passports()[0];
if (passport) { if (passport) {
var knownPassportIds = []; const knownPassportIds = [];
var knownOwnerIds = []; const knownOwnerIds = [];
createdPassports.forEach(function(p) { createdPassports.forEach(function(p) {
if (p.id) knownPassportIds.push(p.id); if (p.id) knownPassportIds.push(p.id);
if (p.ownerId) knownOwnerIds.push(p.ownerId.toString()); if (p.ownerId) knownOwnerIds.push(p.ownerId.toString());
@ -731,7 +731,7 @@ describe('include', function() {
}, function(err, user) { }, function(err, user) {
if (err) return done(err); if (err) return done(err);
var posts, post; let posts, post;
if (connectorCapabilities.adhocSort !== false) { if (connectorCapabilities.adhocSort !== false) {
user.name.should.equal('User A'); user.name.should.equal('User A');
user.age.should.equal(21); user.age.should.equal(21);
@ -745,7 +745,7 @@ describe('include', function() {
post.id.should.eql(createdPosts[0].id); post.id.should.eql(createdPosts[0].id);
} else { } else {
user.name.should.be.oneOf(knownUsers); user.name.should.be.oneOf(knownUsers);
var knownUserIds = []; const knownUserIds = [];
createdUsers.forEach(function(u) { createdUsers.forEach(function(u) {
knownUserIds.push(u.id.toString()); knownUserIds.push(u.id.toString());
}); });
@ -755,7 +755,7 @@ describe('include', function() {
post = posts[0]; post = posts[0];
post.title.should.be.oneOf(knownPosts); post.title.should.be.oneOf(knownPosts);
post.userId.toString().should.be.oneOf(knownUserIds); post.userId.toString().should.be.oneOf(knownUserIds);
var knownPostIds = []; const knownPostIds = [];
createdPosts.forEach(function(p) { createdPosts.forEach(function(p) {
knownPostIds.push(p.id); knownPostIds.push(p.id);
}); });
@ -794,9 +794,9 @@ describe('include', function() {
}, function(err, user) { }, function(err, user) {
if (err) return done(err); 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) { if (ids.length > 0) {
var knownPosts = []; const knownPosts = [];
createdPosts.forEach(function(p) { createdPosts.forEach(function(p) {
if (p.id) knownPosts.push(p.id); if (p.id) knownPosts.push(p.id);
}); });
@ -820,9 +820,9 @@ describe('include', function() {
}, function(err, user) { }, function(err, user) {
if (err) return done(err); 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) { if (ids.length > 0) {
var knownPosts = []; const knownPosts = [];
createdPosts.forEach(function(p) { createdPosts.forEach(function(p) {
if (p.id) knownPosts.push(p.id); if (p.id) knownPosts.push(p.id);
}); });
@ -840,10 +840,10 @@ describe('include', function() {
User.findOne({include: {relation: 'posts'}}, function(err, user) { User.findOne({include: {relation: 'posts'}}, function(err, user) {
if (err) return done(err); if (err) return done(err);
var posts = user.posts(); const posts = user.posts();
var ids = posts.map(function(p) { return p.id; }); const ids = posts.map(function(p) { return p.id; });
if (ids.length > 0) { if (ids.length > 0) {
var knownPosts = []; const knownPosts = [];
createdPosts.forEach(function(p) { createdPosts.forEach(function(p) {
if (p.id) knownPosts.push(p.id); if (p.id) knownPosts.push(p.id);
}); });
@ -910,8 +910,8 @@ describe('include', function() {
User.findOne({include: {relation: 'profile'}}, function(err, user) { User.findOne({include: {relation: 'profile'}}, function(err, user) {
if (err) return done(err); if (err) return done(err);
var knownUserIds = []; const knownUserIds = [];
var knownProfileIds = []; const knownProfileIds = [];
createdUsers.forEach(function(u) { createdUsers.forEach(function(u) {
// FIXME user.id below might be string, so knownUserIds should match // FIXME user.id below might be string, so knownUserIds should match
knownUserIds.push(u.id.toString()); knownUserIds.push(u.id.toString());
@ -924,7 +924,7 @@ describe('include', function() {
user.name.should.be.oneOf(knownUsers); user.name.should.be.oneOf(knownUsers);
// eql instead of equal because mongo uses object id type // eql instead of equal because mongo uses object id type
user.id.toString().should.be.oneOf(knownUserIds); user.id.toString().should.be.oneOf(knownUserIds);
var profile = user.profile(); const profile = user.profile();
if (profile) { if (profile) {
profile.profileName.should.be.oneOf(knownProfiles); profile.profileName.should.be.oneOf(knownProfiles);
// eql instead of equal because mongo uses object id type // 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) { User.findOne({include: {relation: 'posts'}}, function(err, user) {
if (err) return done(); if (err) return done();
var knownUserIds = []; const knownUserIds = [];
createdUsers.forEach(function(u) { createdUsers.forEach(function(u) {
knownUserIds.push(u.id); knownUserIds.push(u.id);
}); });
@ -955,9 +955,9 @@ describe('include', function() {
}); });
it('works when hasManyThrough is called', function(done) { it('works when hasManyThrough is called', function(done) {
var Physician = db.define('Physician', {name: String}); const Physician = db.define('Physician', {name: String});
var Patient = db.define('Patient', {name: String}); const Patient = db.define('Patient', {name: String});
var Appointment = db.define('Appointment', { const Appointment = db.define('Appointment', {
date: { date: {
type: Date, type: Date,
default: function() { 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}); Physician.hasMany(Patient, {through: Appointment});
Patient.hasMany(Physician, {through: Appointment}); Patient.hasMany(Physician, {through: Appointment});
@ -984,7 +984,7 @@ describe('include', function() {
function(err, patients) { function(err, patients) {
if (err) return done(err); if (err) return done(err);
patients.should.have.length(1); patients.should.have.length(1);
var p = patients[0]; const p = patients[0];
p.name.should.equal('a'); p.name.should.equal('a');
p.addressId.should.eql(patient.addressId); p.addressId.should.eql(patient.addressId);
p.address().id.should.eql(address.id); p.address().id.should.eql(address.id);
@ -1004,8 +1004,8 @@ describe('include', function() {
if (err) return done(err); if (err) return done(err);
if (!profile) return done(); // not every user has progile if (!profile) return done(); // not every user has progile
var knownUserIds = []; const knownUserIds = [];
var knownProfileIds = []; const knownProfileIds = [];
createdUsers.forEach(function(u) { createdUsers.forEach(function(u) {
knownUserIds.push(u.id.toString()); knownUserIds.push(u.id.toString());
}); });
@ -1016,7 +1016,7 @@ describe('include', function() {
profile.profileName.should.be.oneOf(knownProfiles); profile.profileName.should.be.oneOf(knownProfiles);
if (profile.userId) profile.userId.toString().should.be.oneOf(knownUserIds); if (profile.userId) profile.userId.toString().should.be.oneOf(knownUserIds);
if (profile.id) profile.id.toString().should.be.oneOf(knownProfileIds); if (profile.id) profile.id.toString().should.be.oneOf(knownProfileIds);
var user = profile.user(); const user = profile.user();
if (user) { if (user) {
user.name.should.be.oneOf(knownUsers); user.name.should.be.oneOf(knownUsers);
user.id.toString().should.be.oneOf(knownUserIds); user.id.toString().should.be.oneOf(knownUserIds);
@ -1038,7 +1038,7 @@ describe('include', function() {
should.exist(posts); should.exist(posts);
posts.length.should.equal(5); posts.length.should.equal(5);
var author = posts[0].author(); const author = posts[0].author();
author.name.should.equal('User A'); author.name.should.equal('User A');
author.should.have.property('id'); author.should.have.property('id');
author.should.have.property('age', undefined); author.should.have.property('age', undefined);
@ -1056,7 +1056,7 @@ describe('include', function() {
should.exist(posts); should.exist(posts);
posts.length.should.be.belowOrEqual(5); posts.length.should.be.belowOrEqual(5);
var author = posts[0].author(); const author = posts[0].author();
if (author) { if (author) {
author.name.should.be.oneOf('User A', 'User B', 'User C', 'User D', 'User E'); author.name.should.be.oneOf('User A', 'User B', 'User C', 'User D', 'User E');
author.should.have.property('id'); author.should.have.property('id');
@ -1081,7 +1081,7 @@ describe('include', function() {
users[0].name.should.equal('User A'); users[0].name.should.equal('User A');
users[1].name.should.equal('User B'); users[1].name.should.equal('User B');
var posts = users[0].posts(); let posts = users[0].posts();
posts.should.be.an.array; posts.should.be.an.array;
posts.should.have.length(3); posts.should.have.length(3);
@ -1096,7 +1096,7 @@ describe('include', function() {
} else { } else {
users.forEach(function(u) { users.forEach(function(u) {
u.name.should.be.oneOf(knownUsers); u.name.should.be.oneOf(knownUsers);
var posts = u.posts(); const posts = u.posts();
if (posts) { if (posts) {
posts.should.be.an.array; posts.should.be.an.array;
posts.length.should.be.belowOrEqual(3); posts.length.should.be.belowOrEqual(3);
@ -1121,7 +1121,7 @@ describe('include', function() {
user.should.have.property('posts'); user.should.have.property('posts');
user.should.have.property('passports'); user.should.have.property('passports');
var userObj = user.toJSON(); const userObj = user.toJSON();
userObj.should.have.property('posts'); userObj.should.have.property('posts');
userObj.should.have.property('passports'); userObj.should.have.property('passports');
userObj.posts.should.be.an.instanceOf(Array); userObj.posts.should.be.an.instanceOf(Array);
@ -1161,7 +1161,7 @@ describe('include', function() {
user.should.have.property('posts'); user.should.have.property('posts');
user.should.have.property('passports'); user.should.have.property('passports');
var userObj = user.toJSON(); const userObj = user.toJSON();
userObj.should.have.property('posts'); userObj.should.have.property('posts');
userObj.should.have.property('passports'); userObj.should.have.property('passports');
userObj.posts.should.be.an.instanceOf(Array); userObj.posts.should.be.an.instanceOf(Array);
@ -1192,7 +1192,7 @@ describe('include', function() {
should.exist(users); should.exist(users);
users.length.should.be.ok; users.length.should.be.ok;
users.forEach(function(user) { users.forEach(function(user) {
var userObj = user.toJSON(); const userObj = user.toJSON();
userObj.should.not.have.property('accesstokens'); userObj.should.not.have.property('accesstokens');
}); });
done(); done();
@ -1228,12 +1228,12 @@ describe('include', function() {
should.not.exist(err); should.not.exist(err);
should.exist(users); should.exist(users);
users.length.should.be.ok; users.length.should.be.ok;
var usersWithProfile = 0; let usersWithProfile = 0;
users.forEach(function(user) { users.forEach(function(user) {
// The relation should be promoted as the 'owner' property // The relation should be promoted as the 'owner' property
user.should.have.property('profile'); user.should.have.property('profile');
var userObj = user.toJSON(); const userObj = user.toJSON();
var profile = user.profile(); const profile = user.profile();
if (profile) { if (profile) {
profile.should.be.an.instanceOf(Profile); profile.should.be.an.instanceOf(Profile);
usersWithProfile++; usersWithProfile++;
@ -1261,7 +1261,7 @@ describe('include', function() {
where: {partNumber: 'engine'}, where: {partNumber: 'engine'},
}}}, function(err, assemblies) { }}}, function(err, assemblies) {
assemblies.length.should.equal(1); assemblies.length.should.equal(1);
var parts = assemblies[0].parts(); const parts = assemblies[0].parts();
parts.should.have.length(1); parts.should.have.length(1);
parts[0].partNumber.should.equal('engine'); parts[0].partNumber.should.equal('engine');
done(); done();
@ -1273,7 +1273,7 @@ describe('include', function() {
include: 'posts', include: 'posts',
}) })
.then(function(users) { .then(function(users) {
var posts = users[0].posts(); const posts = users[0].posts();
if (connectorCapabilities.adhocSort !== false) { if (connectorCapabilities.adhocSort !== false) {
posts.should.have.length(3); posts.should.have.length(3);
} else { } else {
@ -1287,7 +1287,7 @@ describe('include', function() {
}); });
}) })
.then(function(user) { .then(function(user) {
var posts = user.posts(); const posts = user.posts();
if (connectorCapabilities.adhocSort !== false) { if (connectorCapabilities.adhocSort !== false) {
posts.should.have.length(3); posts.should.have.length(3);
} else { } else {
@ -1299,10 +1299,10 @@ describe('include', function() {
}); });
describe('performance', function() { describe('performance', function() {
var all; let all;
beforeEach(function() { beforeEach(function() {
this.called = 0; this.called = 0;
var self = this; const self = this;
all = db.connector.all; all = db.connector.all;
db.connector.all = function(model, filter, options, cb) { db.connector.all = function(model, filter, options, cb) {
self.called++; self.called++;
@ -1313,9 +1313,9 @@ describe('include', function() {
db.connector.all = all; 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) { it('including belongsTo should make only ' + nDBCalls + ' db calls', function(done) {
var self = this; const self = this;
Passport.find({include: 'owner'}, function(err, passports) { Passport.find({include: 'owner'}, function(err, passports) {
passports.length.should.be.ok; passports.length.should.be.ok;
passports.forEach(function(p) { passports.forEach(function(p) {
@ -1324,7 +1324,7 @@ describe('include', function() {
p.should.have.property('owner'); p.should.have.property('owner');
// The __cachedRelations should be removed from json output // The __cachedRelations should be removed from json output
p.toJSON().should.not.have.property('__cachedRelations'); p.toJSON().should.not.have.property('__cachedRelations');
var owner = p.__cachedRelations.owner; const owner = p.__cachedRelations.owner;
if (!p.ownerId) { if (!p.ownerId) {
should.not.exist(owner); should.not.exist(owner);
} else { } else {
@ -1338,7 +1338,7 @@ describe('include', function() {
}); });
it('including hasManyThrough should make only 3 db calls', function(done) { it('including hasManyThrough should make only 3 db calls', function(done) {
var self = this; const self = this;
Assembly.create([{name: 'sedan'}, {name: 'hatchback'}, Assembly.create([{name: 'sedan'}, {name: 'hatchback'},
{name: 'SUV'}], {name: 'SUV'}],
function(err, assemblies) { function(err, assemblies) {
@ -1359,10 +1359,10 @@ describe('include', function() {
}); });
}, next); }, next);
}, function(err) { }, function(err) {
var autos = connectorCapabilities.supportTwoOrMoreInq !== false ? const autos = connectorCapabilities.supportTwoOrMoreInq !== false ?
['sedan', 'hatchback', 'SUV'] : ['sedan']; ['sedan', 'hatchback', 'SUV'] : ['sedan'];
var resultLength = connectorCapabilities.supportTwoOrMoreInq !== false ? 3 : 1; const resultLength = connectorCapabilities.supportTwoOrMoreInq !== false ? 3 : 1;
var dbCalls = connectorCapabilities.supportTwoOrMoreInq !== false ? 3 : 5; const dbCalls = connectorCapabilities.supportTwoOrMoreInq !== false ? 3 : 5;
self.called = 0; self.called = 0;
Assembly.find({ Assembly.find({
where: { where: {
@ -1376,7 +1376,7 @@ describe('include', function() {
should.exists(result); should.exists(result);
result.length.should.equal(resultLength); result.length.should.equal(resultLength);
// Please note the order of assemblies is random // Please note the order of assemblies is random
var assemblies = {}; const assemblies = {};
result.forEach(function(r) { result.forEach(function(r) {
assemblies[r.name] = 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) { 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) { User.find({include: ['posts', 'passports']}, function(err, users) {
should.not.exist(err); should.not.exist(err);
should.exist(users); should.exist(users);
@ -1403,7 +1403,7 @@ describe('include', function() {
user.should.have.property('posts'); user.should.have.property('posts');
user.should.have.property('passports'); user.should.have.property('passports');
var userObj = user.toJSON(); const userObj = user.toJSON();
userObj.should.have.property('posts'); userObj.should.have.property('posts');
userObj.should.have.property('passports'); userObj.should.have.property('passports');
userObj.posts.should.be.an.instanceOf(Array); 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', it('should not make n+1 db calls in relation syntax',
function(done) { function(done) {
var self = this; const self = this;
User.find({include: [{relation: 'posts', scope: { User.find({include: [{relation: 'posts', scope: {
where: {title: 'Post A'}, where: {title: 'Post A'},
}}, 'passports']}, function(err, users) { }}, 'passports']}, function(err, users) {
@ -1442,7 +1442,7 @@ describe('include', function() {
user.should.have.property('posts'); user.should.have.property('posts');
user.should.have.property('passports'); user.should.have.property('passports');
var userObj = user.toJSON(); const userObj = user.toJSON();
userObj.should.have.property('posts'); userObj.should.have.property('posts');
userObj.should.have.property('passports'); userObj.should.have.property('passports');
userObj.posts.should.be.an.instanceOf(Array); userObj.posts.should.be.an.instanceOf(Array);
@ -1470,15 +1470,15 @@ describe('include', function() {
}); });
it('should support disableInclude for hasAndBelongsToMany', function() { it('should support disableInclude for hasAndBelongsToMany', function() {
var Patient = db.define('Patient', {name: String}); const Patient = db.define('Patient', {name: String});
var Doctor = db.define('Doctor', {name: String}); const Doctor = db.define('Doctor', {name: String});
var DoctorPatient = db.define('DoctorPatient'); const DoctorPatient = db.define('DoctorPatient');
Doctor.hasAndBelongsToMany('patients', { Doctor.hasAndBelongsToMany('patients', {
model: 'Patient', model: 'Patient',
options: {disableInclude: true}, options: {disableInclude: true},
}); });
var doctor; let doctor;
return db.automigrate(['Patient', 'Doctor', 'DoctorPatient']).then(function() { return db.automigrate(['Patient', 'Doctor', 'DoctorPatient']).then(function() {
return Doctor.create({name: 'Who'}); return Doctor.create({name: 'Who'});
}).then(function(inst) { }).then(function(inst) {
@ -1493,10 +1493,10 @@ describe('include', function() {
}); });
}); });
var createdUsers = []; let createdUsers = [];
var createdPassports = []; let createdPassports = [];
var createdProfiles = []; let createdProfiles = [];
var createdPosts = []; let createdPosts = [];
function setup(done) { function setup(done) {
db = getSchema(); db = getSchema();
City = db.define('City'); City = db.define('City');
@ -1624,12 +1624,12 @@ function setup(done) {
} }
function clearAndCreate(model, data, callback) { function clearAndCreate(model, data, callback) {
var createdItems = []; const createdItems = [];
model.destroyAll(function() { model.destroyAll(function() {
nextItem(null, null); nextItem(null, null);
}); });
var itemIndex = 0; let itemIndex = 0;
function nextItem(err, lastItem) { function nextItem(err, lastItem) {
if (lastItem !== null) { if (lastItem !== null) {
@ -1645,7 +1645,7 @@ function clearAndCreate(model, data, callback) {
} }
describe('Model instance with included relation .toJSON()', function() { describe('Model instance with included relation .toJSON()', function() {
var db, ChallengerModel, GameParticipationModel, ResultModel; let db, ChallengerModel, GameParticipationModel, ResultModel;
before(function(done) { before(function(done) {
db = new DataSource({connector: 'memory'}); db = new DataSource({connector: 'memory'});
@ -1720,12 +1720,12 @@ describe('Model instance with included relation .toJSON()', function() {
} }
it('should recursively serialize objects', function(done) { it('should recursively serialize objects', function(done) {
var filter = {include: {gameParticipations: 'results'}}; const filter = {include: {gameParticipations: 'results'}};
ChallengerModel.find(filter, function(err, challengers) { 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.'); 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.'); assert(levelTwoInclusion.__data === undefined, '__data of a level 2 inclusion is undefined.');
done(); done();
}); });

View File

@ -4,25 +4,25 @@
// License text available at https://opensource.org/licenses/MIT // License text available at https://opensource.org/licenses/MIT
'use strict'; 'use strict';
var assert = require('assert'); const assert = require('assert');
var should = require('should'); const should = require('should');
var includeUtils = require('../lib/include_utils'); const includeUtils = require('../lib/include_utils');
describe('include_util', function() { describe('include_util', function() {
describe('#buildOneToOneIdentityMapWithOrigKeys', function() { describe('#buildOneToOneIdentityMapWithOrigKeys', function() {
it('should return an object with keys', function() { it('should return an object with keys', function() {
var objs = [ const objs = [
{id: 11, letter: 'A'}, {id: 11, letter: 'A'},
{id: 22, letter: 'B'}, {id: 22, letter: 'B'},
]; ];
var result = includeUtils.buildOneToOneIdentityMapWithOrigKeys(objs, 'id'); const result = includeUtils.buildOneToOneIdentityMapWithOrigKeys(objs, 'id');
result.get(11).should.be.ok; result.get(11).should.be.ok;
result.get(22).should.be.ok; result.get(22).should.be.ok;
}); });
it('should report errors if id is missing', function() { it('should report errors if id is missing', function() {
var objs = [ const objs = [
{letter: 'A'}, {letter: 'A'},
{id: 22, letter: 'B'}, {id: 22, letter: 'B'},
]; ];
@ -33,14 +33,14 @@ describe('include_util', function() {
}); });
it('should overwrite keys in case of collision', function() { it('should overwrite keys in case of collision', function() {
var objs = [ const objs = [
{id: 11, letter: 'A'}, {id: 11, letter: 'A'},
{id: 22, letter: 'B'}, {id: 22, letter: 'B'},
{id: 33, letter: 'C'}, {id: 33, letter: 'C'},
{id: 11, letter: 'HA!'}, {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(11);
result.getKeys().should.containEql(22); result.getKeys().should.containEql(22);
result.getKeys().should.containEql(33); result.getKeys().should.containEql(33);
@ -49,28 +49,28 @@ describe('include_util', function() {
}); });
it('should return an object with no additional keys', function() { it('should return an object with no additional keys', function() {
var objs = [ const objs = [
{id: 11, letter: 'A'}, {id: 11, letter: 'A'},
{id: 22, letter: 'B'}, {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 result.getKeys().should.eql([11, 22]); // no additional properties
}); });
}); });
describe('#buildOneToManyIdentityMap', function() { describe('#buildOneToManyIdentityMap', function() {
it('should return an object with keys', function() { it('should return an object with keys', function() {
var objs = [ const objs = [
{id: 11, letter: 'A'}, {id: 11, letter: 'A'},
{id: 22, letter: 'B'}, {id: 22, letter: 'B'},
]; ];
var result = includeUtils.buildOneToManyIdentityMapWithOrigKeys(objs, 'id'); const result = includeUtils.buildOneToManyIdentityMapWithOrigKeys(objs, 'id');
result.exist(11).should.be.true; result.exist(11).should.be.true;
result.exist(22).should.be.true; result.exist(22).should.be.true;
}); });
it('should report errors if id is missing', function() { it('should report errors if id is missing', function() {
var objs = [ const objs = [
{letter: 'A'}, {letter: 'A'},
{id: 22, letter: 'B'}, {id: 22, letter: 'B'},
]; ];
@ -81,14 +81,14 @@ describe('include_util', function() {
}); });
it('should collect keys in case of collision', function() { it('should collect keys in case of collision', function() {
var objs = [ const objs = [
{'fk_id': 11, letter: 'A'}, {'fk_id': 11, letter: 'A'},
{'fk_id': 22, letter: 'B'}, {'fk_id': 22, letter: 'B'},
{'fk_id': 33, letter: 'C'}, {'fk_id': 33, letter: 'C'},
{'fk_id': 11, letter: 'HA!'}, {'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)[0]['letter'].should.equal('A');
result.get(11)[1]['letter'].should.equal('HA!'); result.get(11)[1]['letter'].should.equal('HA!');
result.get(33)[0]['letter'].should.equal('C'); result.get(33)[0]['letter'].should.equal('C');
@ -98,7 +98,7 @@ describe('include_util', function() {
describe('KVMap', function() { describe('KVMap', function() {
it('should allow to set and get value with key string', 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('name', 'Alex');
map.set('gender', true); map.set('gender', true);
map.set('age', 25); map.set('age', 25);
@ -107,7 +107,7 @@ describe('KVMap', function() {
map.get('age').should.be.equal(25); map.get('age').should.be.equal(25);
}); });
it('should allow to set and get value with arbitrary key type', function() { 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('name', 'Alex');
map.set(true, 'male'); map.set(true, 'male');
map.set(false, false); map.set(false, false);
@ -118,12 +118,12 @@ describe('KVMap', function() {
map.get({isTrue: 'yes'}).should.be.equal(25); map.get({isTrue: 'yes'}).should.be.equal(25);
}); });
it('should not allow to get values with [] operator', function() { 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.set('name', 'Alex');
(map['name'] === undefined).should.be.equal(true); (map['name'] === undefined).should.be.equal(true);
}); });
it('should provide .exist() method for checking if key presented', function() { 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('one', 1);
map.set(2, 'two'); map.set(2, 'two');
map.set(true, 'true'); map.set(true, 'true');
@ -133,24 +133,24 @@ describe('KVMap', function() {
map.exist('two').should.be.false; map.exist('two').should.be.false;
}); });
it('should return array of original keys with .getKeys()', function() { 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('one', 1);
map.set(2, 'two'); map.set(2, 'two');
map.set(true, 'true'); map.set(true, 'true');
var keys = map.getKeys(); const keys = map.getKeys();
keys.should.containEql('one'); keys.should.containEql('one');
keys.should.containEql(2); keys.should.containEql(2);
keys.should.containEql(true); keys.should.containEql(true);
}); });
it('should allow to store and fetch arrays', function() { 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(1, [1, 2, 3]);
map.set(2, [2, 3, 4]); map.set(2, [2, 3, 4]);
var valueOne = map.get(1); const valueOne = map.get(1);
valueOne.should.be.eql([1, 2, 3]); valueOne.should.be.eql([1, 2, 3]);
valueOne.push(99); valueOne.push(99);
map.set(1, valueOne); map.set(1, valueOne);
var valueOneUpdated = map.get(1); const valueOneUpdated = map.get(1);
valueOneUpdated.should.be.eql([1, 2, 3, 99]); valueOneUpdated.should.be.eql([1, 2, 3, 99]);
}); });
}); });

View File

@ -18,8 +18,8 @@ module.exports = require('should');
} }
*/ */
var ModelBuilder = require('../').ModelBuilder; const ModelBuilder = require('../').ModelBuilder;
var Schema = require('../').Schema; const Schema = require('../').Schema;
if (!('getSchema' in global)) { if (!('getSchema' in global)) {
global.getSchema = function(connector, settings) { global.getSchema = function(connector, settings) {

View File

@ -4,13 +4,13 @@
// License text available at https://opensource.org/licenses/MIT // License text available at https://opensource.org/licenses/MIT
'use strict'; 'use strict';
var assert = require('assert'); const assert = require('assert');
var ModelBuilder = require('..').ModelBuilder; const ModelBuilder = require('..').ModelBuilder;
var DataSource = require('../').DataSource; const DataSource = require('../').DataSource;
var introspectType = require('../lib/introspection')(ModelBuilder); const introspectType = require('../lib/introspection')(ModelBuilder);
var traverse = require('traverse'); const traverse = require('traverse');
var json = { const json = {
name: 'Joe', name: 'Joe',
age: 30, age: 30,
birthday: new Date(), birthday: new Date(),
@ -40,7 +40,7 @@ describe('Introspection of model definitions from JSON', function() {
}); });
it('should handle array types', function() { it('should handle array types', function() {
var type = introspectType(['123']); let type = introspectType(['123']);
assert.deepEqual(type, ['string'], 'type should be ["string"]'); assert.deepEqual(type, ['string'], 'type should be ["string"]');
type = introspectType([1]); type = introspectType([1]);
assert.deepEqual(type, ['number'], 'type should be ["number"]'); 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() { it('should return a schema for object', function() {
var json = {a: 'str', b: 0, c: true}; const json = {a: 'str', b: 0, c: true};
var type = introspectType(json); const type = introspectType(json);
assert.equal(type.a, 'string'); assert.equal(type.a, 'string');
assert.equal(type.b, 'number'); assert.equal(type.b, 'number');
assert.equal(type.c, 'boolean'); assert.equal(type.c, 'boolean');
}); });
it('should handle nesting objects', function() { it('should handle nesting objects', function() {
var json = {a: 'str', b: 0, c: true, d: {x: 10, y: 5}}; const json = {a: 'str', b: 0, c: true, d: {x: 10, y: 5}};
var type = introspectType(json); const type = introspectType(json);
assert.equal(type.a, 'string'); assert.equal(type.a, 'string');
assert.equal(type.b, 'number'); assert.equal(type.b, 'number');
assert.equal(type.c, 'boolean'); assert.equal(type.c, 'boolean');
@ -78,8 +78,8 @@ describe('Introspection of model definitions from JSON', function() {
}); });
it('should handle nesting arrays', function() { it('should handle nesting arrays', function() {
var json = {a: 'str', b: 0, c: true, d: [1, 2]}; const json = {a: 'str', b: 0, c: true, d: [1, 2]};
var type = introspectType(json); const type = introspectType(json);
assert.equal(type.a, 'string'); assert.equal(type.a, 'string');
assert.equal(type.b, 'number'); assert.equal(type.b, 'number');
assert.equal(type.c, 'boolean'); 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) { 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(); const builder = new ModelBuilder();
var Model = builder.define('MyModel', schema, {idInjection: false}); const Model = builder.define('MyModel', schema, {idInjection: false});
// FIXME: [rfeng] The constructor mutates the arguments // FIXME: [rfeng] The constructor mutates the arguments
var obj = new Model(json); let obj = new Model(json);
obj = obj.toObject(); obj = obj.toObject();
@ -104,27 +104,27 @@ describe('Introspection of model definitions from JSON', function() {
}); });
it('should build a model using buildModelFromInstance', function(done) { it('should build a model using buildModelFromInstance', function(done) {
var copy = traverse(json).clone(); const copy = traverse(json).clone();
var builder = new ModelBuilder(); const builder = new ModelBuilder();
var Model = builder.buildModelFromInstance('MyModel', copy, {idInjection: false}); const Model = builder.buildModelFromInstance('MyModel', copy, {idInjection: false});
var obj = new Model(json); let obj = new Model(json);
obj = obj.toObject(); obj = obj.toObject();
assert.deepEqual(obj, copy); assert.deepEqual(obj, copy);
done(); done();
}); });
it('should build a model using DataSource.buildModelFromInstance', function(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'); const builder = new DataSource('memory');
var Model = builder.buildModelFromInstance('MyModel', copy, const Model = builder.buildModelFromInstance('MyModel', copy,
{idInjection: false}); {idInjection: false});
assert.equal(Model.dataSource, builder); assert.equal(Model.dataSource, builder);
var obj = new Model(json); let obj = new Model(json);
obj = obj.toObject(); obj = obj.toObject();
assert.deepEqual(obj, copy); assert.deepEqual(obj, copy);
done(); done();

View File

@ -7,24 +7,24 @@
'use strict'; 'use strict';
/* global getSchema:false */ /* global getSchema:false */
var should = require('./init.js'); const should = require('./init.js');
var Schema = require('../').Schema; const Schema = require('../').Schema;
var ModelBuilder = require('../').ModelBuilder; const ModelBuilder = require('../').ModelBuilder;
describe('JSON property', function() { describe('JSON property', function() {
var dataSource, Model; let dataSource, Model;
it('should be defined', function() { it('should be defined', function() {
dataSource = getSchema(); dataSource = getSchema();
Model = dataSource.define('Model', {propertyName: ModelBuilder.JSON}); Model = dataSource.define('Model', {propertyName: ModelBuilder.JSON});
var m = new Model; const m = new Model;
(new Boolean('propertyName' in m)).should.eql(true); (new Boolean('propertyName' in m)).should.eql(true);
should.not.exist(m.propertyName); should.not.exist(m.propertyName);
}); });
it('should accept JSON in constructor and return object', function() { it('should accept JSON in constructor and return object', function() {
var m = new Model({ const m = new Model({
propertyName: '{"foo": "bar"}', propertyName: '{"foo": "bar"}',
}); });
m.propertyName.should.be.an.Object; m.propertyName.should.be.an.Object;
@ -32,14 +32,14 @@ describe('JSON property', function() {
}); });
it('should accept object in setter and return object', 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 = {'foo': 'bar'};
m.propertyName.should.be.an.Object; m.propertyName.should.be.an.Object;
m.propertyName.foo.should.equal('bar'); m.propertyName.foo.should.equal('bar');
}); });
it('should accept string in setter and return string', function() { it('should accept string in setter and return string', function() {
var m = new Model; const m = new Model;
m.propertyName = '{"foo": "bar"}'; m.propertyName = '{"foo": "bar"}';
m.propertyName.should.be.a.String; m.propertyName.should.be.a.String;
m.propertyName.should.equal('{"foo": "bar"}'); m.propertyName.should.equal('{"foo": "bar"}');

View File

@ -4,11 +4,11 @@
// License text available at https://opensource.org/licenses/MIT // License text available at https://opensource.org/licenses/MIT
'use strict'; 'use strict';
var kvMemory = require('../lib/connectors/kv-memory'); const kvMemory = require('../lib/connectors/kv-memory');
var DataSource = require('..').DataSource; const DataSource = require('..').DataSource;
describe('Optimized KeyValue-Memory connector', function() { describe('Optimized KeyValue-Memory connector', function() {
var dataSourceFactory = function() { const dataSourceFactory = function() {
return new DataSource({connector: kvMemory}); return new DataSource({connector: kvMemory});
}; };
@ -16,8 +16,8 @@ describe('Optimized KeyValue-Memory connector', function() {
}); });
describe('Unoptimized KeyValue-Memory connector', function() { describe('Unoptimized KeyValue-Memory connector', function() {
var dataSourceFactory = function() { const dataSourceFactory = function() {
var ds = new DataSource({connector: kvMemory}); const ds = new DataSource({connector: kvMemory});
// disable optimized methods // disable optimized methods
ds.connector.deleteAll = false; ds.connector.deleteAll = false;

View File

@ -5,10 +5,10 @@
'use strict'; 'use strict';
var debug = require('debug')('test'); const debug = require('debug')('test');
var extend = require('util')._extend; const extend = require('util')._extend;
var fs = require('fs'); const fs = require('fs');
var path = require('path'); const path = require('path');
module.exports = function(dataSourceFactory, connectorCapabilities) { module.exports = function(dataSourceFactory, connectorCapabilities) {
connectorCapabilities = extend({ connectorCapabilities = extend({
@ -18,16 +18,16 @@ module.exports = function(dataSourceFactory, connectorCapabilities) {
}, connectorCapabilities); }, connectorCapabilities);
describe('KeyValue API', function loadAllTestFiles() { describe('KeyValue API', function loadAllTestFiles() {
var testRoot = path.resolve(__dirname, 'kvao'); const testRoot = path.resolve(__dirname, 'kvao');
var testFiles = fs.readdirSync(testRoot); let testFiles = fs.readdirSync(testRoot);
testFiles = testFiles.filter(function(it) { testFiles = testFiles.filter(function(it) {
return !!require.extensions[path.extname(it).toLowerCase()] && return !!require.extensions[path.extname(it).toLowerCase()] &&
/\.suite\.[^.]+$/.test(it); /\.suite\.[^.]+$/.test(it);
}); });
for (var ix in testFiles) { for (const ix in testFiles) {
var name = testFiles[ix]; const name = testFiles[ix];
var fullPath = path.resolve(testRoot, name); const fullPath = path.resolve(testRoot, name);
debug('Loading test suite %s (%s)', name, fullPath); debug('Loading test suite %s (%s)', name, fullPath);
require(fullPath)(dataSourceFactory, connectorCapabilities); require(fullPath)(dataSourceFactory, connectorCapabilities);
} }

View File

@ -23,7 +23,7 @@ function givenModel(dataSourceFactory, modelName,
} }
function givenKeys(Model, keys, cb) { function givenKeys(Model, keys, cb) {
var p = Promise.all( let p = Promise.all(
keys.map(function(k) { keys.map(function(k) {
return Model.set(k, 'value-' + k); return Model.set(k, 'value-' + k);
}) })

View File

@ -5,7 +5,7 @@ const helpers = require('./_helpers');
const should = require('should'); const should = require('should');
module.exports = function(dataSourceFactory, connectorCapabilities) { module.exports = function(dataSourceFactory, connectorCapabilities) {
var supportsDeleteAll = 'deleteAll' in dataSourceFactory().connector; const supportsDeleteAll = 'deleteAll' in dataSourceFactory().connector;
bdd.describeIf(supportsDeleteAll, 'deleteAll', () => { bdd.describeIf(supportsDeleteAll, 'deleteAll', () => {
let CacheItem; let CacheItem;

View File

@ -1,18 +1,18 @@
'use strict'; 'use strict';
var bdd = require('../helpers/bdd-if'); const bdd = require('../helpers/bdd-if');
var should = require('should'); const should = require('should');
var helpers = require('./_helpers'); const helpers = require('./_helpers');
module.exports = function(dataSourceFactory, connectorCapabilities) { module.exports = function(dataSourceFactory, connectorCapabilities) {
// While we support millisecond precision, for the purpose of tests // While we support millisecond precision, for the purpose of tests
// it's better to use intervals at least 10ms long. // 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() { bdd.describeIf(canExpire, 'expire', function() {
var CacheItem; let CacheItem;
beforeEach(setupCacheItem); beforeEach(setupCacheItem);
it('sets key ttl - Callback API', function(done) { it('sets key ttl - Callback API', function(done) {

View File

@ -1,13 +1,13 @@
'use strict'; 'use strict';
var should = require('should'); const should = require('should');
var helpers = require('./_helpers'); const helpers = require('./_helpers');
module.exports = function(dataSourceFactory, connectorCapabilities) { module.exports = function(dataSourceFactory, connectorCapabilities) {
var TTL_PRECISION = connectorCapabilities.ttlPrecision; const TTL_PRECISION = connectorCapabilities.ttlPrecision;
describe('get/set', function() { describe('get/set', function() {
var CacheItem; let CacheItem;
beforeEach(setupCacheItem); beforeEach(setupCacheItem);
it('works for string values - Callback API', function(done) { it('works for string values - Callback API', function(done) {

View File

@ -1,21 +1,21 @@
'use strict'; 'use strict';
var asyncIterators = require('async-iterators'); const asyncIterators = require('async-iterators');
var bdd = require('../helpers/bdd-if'); const bdd = require('../helpers/bdd-if');
var helpers = require('./_helpers'); const helpers = require('./_helpers');
var should = require('should'); const should = require('should');
module.exports = function(dataSourceFactory, connectorCapabilities) { module.exports = function(dataSourceFactory, connectorCapabilities) {
var canIterateKeys = connectorCapabilities.canIterateKeys !== false; const canIterateKeys = connectorCapabilities.canIterateKeys !== false;
bdd.describeIf(canIterateKeys, 'iterateKeys', function() { bdd.describeIf(canIterateKeys, 'iterateKeys', function() {
var CacheItem; let CacheItem;
beforeEach(setupCacheItem); beforeEach(setupCacheItem);
it('returns AsyncIterator covering all keys', function() { it('returns AsyncIterator covering all keys', function() {
return helpers.givenKeys(CacheItem, ['key1', 'key2']) return helpers.givenKeys(CacheItem, ['key1', 'key2'])
.then(function() { .then(function() {
var it = CacheItem.iterateKeys(); const it = CacheItem.iterateKeys();
should(it).have.property('next'); should(it).have.property('next');
return toArray(it); return toArray(it);
}) })
@ -26,7 +26,7 @@ module.exports = function(dataSourceFactory, connectorCapabilities) {
}); });
it('returns AsyncIterator supporting Promises', function() { it('returns AsyncIterator supporting Promises', function() {
var iterator; let iterator;
return helpers.givenKeys(CacheItem, ['key']) return helpers.givenKeys(CacheItem, ['key'])
.then(function() { .then(function() {
iterator = CacheItem.iterateKeys(); iterator = CacheItem.iterateKeys();

View File

@ -1,11 +1,11 @@
'use strict'; 'use strict';
var bdd = require('../helpers/bdd-if'); const bdd = require('../helpers/bdd-if');
var helpers = require('./_helpers'); const helpers = require('./_helpers');
var should = require('should'); const should = require('should');
module.exports = function(dataSourceFactory, connectorCapabilities) { module.exports = function(dataSourceFactory, connectorCapabilities) {
var canIterateKeys = connectorCapabilities.canIterateKeys !== false; const canIterateKeys = connectorCapabilities.canIterateKeys !== false;
bdd.describeIf(canIterateKeys, 'keys', function() { bdd.describeIf(canIterateKeys, 'keys', function() {
let CacheItem; let CacheItem;
@ -52,10 +52,10 @@ module.exports = function(dataSourceFactory, connectorCapabilities) {
.then(keys => should(keys).eql(['key1', 'key2'])); .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() { bdd.itIf(largeKeySets, 'handles large key set', function() {
var expectedKeys = []; const expectedKeys = [];
for (var ix = 0; ix < 1000; ix++) for (let ix = 0; ix < 1000; ix++)
expectedKeys.push('key-' + ix); expectedKeys.push('key-' + ix);
expectedKeys.sort(); expectedKeys.sort();

View File

@ -1,22 +1,22 @@
'use strict'; 'use strict';
var bdd = require('../helpers/bdd-if'); const bdd = require('../helpers/bdd-if');
var should = require('should'); const should = require('should');
var helpers = require('./_helpers'); const helpers = require('./_helpers');
module.exports = function(dataSourceFactory, connectorCapabilities) { module.exports = function(dataSourceFactory, connectorCapabilities) {
var TTL_PRECISION = connectorCapabilities.ttlPrecision; const TTL_PRECISION = connectorCapabilities.ttlPrecision;
// Use ~1s for stores with precision of 1 ms, // Use ~1s for stores with precision of 1 ms,
// about 3s for stores with precision of 1s. // 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 // A small delay to allow the backend to process the request, run any
// TTL/expire checks, etc. Use 1ms for backends supporting sub-10ms // TTL/expire checks, etc. Use 1ms for backends supporting sub-10ms
// resolution to ensure the delay is not too short.. // 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() { bdd.describeIf(canQueryTtl, 'ttl', function() {
let CacheItem; let CacheItem;

View File

@ -5,8 +5,8 @@
'use strict'; 'use strict';
var should = require('./init.js'); const should = require('./init.js');
var List = require('../lib/list'); const List = require('../lib/list');
/** /**
* Phone as a class * Phone as a class
@ -40,31 +40,31 @@ function PhoneCtor(label, num) {
describe('list of items typed by a class', function() { describe('list of items typed by a class', function() {
it('allows itemType to be 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.should.be.an.instanceOf(Array);
list.toJSON().should.be.eql(phones); list.toJSON().should.be.eql(phones);
}); });
it('converts items of plain json to the itemType', function() { 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); list[0].should.be.an.instanceOf(Phone);
}); });
it('converts stringified items to the itemType', function() { 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); list[0].should.be.an.instanceOf(Phone);
}); });
it('converts items of plain json to the itemType with push', function() { 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.push(phones[0]);
list[0].should.be.an.instanceOf(Phone); 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() { describe('list of items typed by a ctor', function() {
it('allows itemType to be 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.should.be.an.instanceOf(Array);
list.toJSON().should.be.eql(phones); list.toJSON().should.be.eql(phones);
}); });
it('converts items of plain json to the itemType', function() { 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); list[0].should.be.an.instanceOf(PhoneCtor);
}); });
it('converts stringified items to the itemType', function() { 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); list[0].should.be.an.instanceOf(PhoneCtor);
}); });
it('converts items of plain json to the itemType with push', function() { 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.push(phones[0]);
list[0].should.be.an.instanceOf(PhoneCtor); list[0].should.be.an.instanceOf(PhoneCtor);
}); });

View File

@ -5,9 +5,9 @@
// This test written in mocha+should.js // This test written in mocha+should.js
'use strict'; 'use strict';
var should = require('./init.js'); const should = require('./init.js');
var loopbackData = require('../'); const loopbackData = require('../');
describe('loopback-datasource-juggler', function() { describe('loopback-datasource-juggler', function() {
it('should expose version', function() { it('should expose version', function() {

File diff suppressed because it is too large Load Diff

View File

@ -7,15 +7,15 @@
'use strict'; 'use strict';
/* global getSchema:false, connectorCapabilities:false */ /* global getSchema:false, connectorCapabilities:false */
var async = require('async'); const async = require('async');
var bdd = require('./helpers/bdd-if'); const bdd = require('./helpers/bdd-if');
var should = require('./init.js'); const should = require('./init.js');
var uid = require('./helpers/uid-generator'); const uid = require('./helpers/uid-generator');
var db, Person; let db, Person;
var ValidationError = require('..').ValidationError; 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() { describe('manipulation', function() {
before(function(done) { before(function(done) {
@ -36,19 +36,19 @@ describe('manipulation', function() {
// A simplified implementation of LoopBack's User model // A simplified implementation of LoopBack's User model
// to reproduce problems related to properties with dynamic setters // to reproduce problems related to properties with dynamic setters
// For the purpose of the tests, we use a counter instead of a hash fn. // For the purpose of the tests, we use a counter instead of a hash fn.
var StubUser; let StubUser;
var stubPasswordCounter; let stubPasswordCounter;
before(function setupStubUserModel(done) { before(function setupStubUserModel(done) {
StubUser = db.createModel('StubUser', {password: String}, {forceId: true}); StubUser = db.createModel('StubUser', {password: String}, {forceId: true});
StubUser.setter.password = function(plain) { StubUser.setter.password = function(plain) {
if (plain.length === 0) throw new Error('password cannot be empty'); if (plain.length === 0) throw new Error('password cannot be empty');
var hashed = false; let hashed = false;
if (!plain) return; if (!plain) return;
var pos = plain.indexOf('-'); const pos = plain.indexOf('-');
if (pos !== -1) { if (pos !== -1) {
var head = plain.substr(0, pos); const head = plain.substr(0, pos);
var tail = plain.substr(pos + 1, plain.length); const tail = plain.substr(pos + 1, plain.length);
hashed = head.toUpperCase() === tail; hashed = head.toUpperCase() === tail;
} }
if (hashed) return; if (hashed) return;
@ -67,7 +67,7 @@ describe('manipulation', function() {
}); });
describe('forceId', function() { describe('forceId', function() {
var TestForceId; let TestForceId;
before(function(done) { before(function(done) {
TestForceId = db.define('TestForceId'); TestForceId = db.define('TestForceId');
db.automigrate('TestForceId', done); db.automigrate('TestForceId', done);
@ -112,7 +112,7 @@ describe('manipulation', function() {
}); });
it('should instantiate an object', function(done) { 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.name.should.equal('Anatoliy');
p.isNewRecord().should.be.true; p.isNewRecord().should.be.true;
p.save(function(err, inst) { p.save(function(err, inst) {
@ -124,7 +124,7 @@ describe('manipulation', function() {
}); });
it('should instantiate an object (promise variant)', function(done) { 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.name.should.equal('Anatoliy');
p.isNewRecord().should.be.true; p.isNewRecord().should.be.true;
p.save() p.save()
@ -137,7 +137,7 @@ describe('manipulation', function() {
}); });
it('should not return instance of object', function(done) { it('should not return instance of object', function(done) {
var person = Person.create(function(err, p) { const person = Person.create(function(err, p) {
if (err) return done(err); if (err) return done(err);
should.exist(p.id); should.exist(p.id);
if (person) person.should.not.be.an.instanceOf(Person); if (person) person.should.not.be.an.instanceOf(Person);
@ -170,7 +170,7 @@ describe('manipulation', function() {
}); });
it('should not allow user-defined value for the id of object - save', function(done) { 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.isNewRecord().should.be.true;
p.save(function(err, inst) { p.save(function(err, inst) {
err.should.be.instanceof(ValidationError); 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) { 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.isNewRecord().should.be.true;
p.save() p.save()
.then(function(inst) { .then(function(inst) {
@ -249,12 +249,12 @@ describe('manipulation', function() {
}); });
it('should create batch of objects', function(done) { it('should create batch of objects', function(done) {
var batch = [ const batch = [
{name: 'Shaltay'}, {name: 'Shaltay'},
{name: 'Boltay'}, {name: 'Boltay'},
{}, {},
]; ];
var res = Person.create(batch, function(e, ps) { const res = Person.create(batch, function(e, ps) {
if (res) res.should.not.be.instanceOf(Array); if (res) res.should.not.be.instanceOf(Array);
should.not.exist(e); should.not.exist(e);
should.exist(ps); should.exist(ps);
@ -279,7 +279,7 @@ describe('manipulation', function() {
}); });
it('should create batch of objects (promise variant)', function(done) { it('should create batch of objects (promise variant)', function(done) {
var batch = [ const batch = [
{name: 'ShaltayPromise'}, {name: 'ShaltayPromise'},
{name: 'BoltayPromise'}, {name: 'BoltayPromise'},
{}, {},
@ -314,7 +314,7 @@ describe('manipulation', function() {
return next(); return next();
} }
}; };
var batch = [ const batch = [
{name: 'A'}, {name: 'A'},
{name: 'B'}, {name: 'B'},
undefined, undefined,
@ -342,7 +342,7 @@ describe('manipulation', function() {
Person.findById(created.id, function(err, found) { Person.findById(created.id, function(err, found) {
if (err) return done(err); if (err) return done(err);
var result = found.toObject(); const result = found.toObject();
result.should.containEql({ result.should.containEql({
id: created.id, id: created.id,
name: 'a-name', name: 'a-name',
@ -359,7 +359,7 @@ describe('manipulation', function() {
'object with duplicate id', function(done) { 'object with duplicate id', function(done) {
// NOTE(bajtos) We cannot reuse Person model here, // NOTE(bajtos) We cannot reuse Person model here,
// `settings.forceId` aborts the CREATE request at the validation step. // `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) { db.automigrate('ProductTest', function(err) {
if (err) return done(err); if (err) return done(err);
@ -379,7 +379,7 @@ describe('manipulation', function() {
describe('save', function() { describe('save', function() {
it('should save new object', function(done) { it('should save new object', function(done) {
var p = new Person; const p = new Person;
should.not.exist(p.id); should.not.exist(p.id);
p.save(function(err) { p.save(function(err) {
if (err) return done(err); if (err) return done(err);
@ -389,7 +389,7 @@ describe('manipulation', function() {
}); });
it('should save new object (promise variant)', function(done) { it('should save new object (promise variant)', function(done) {
var p = new Person; const p = new Person;
should.not.exist(p.id); should.not.exist(p.id);
p.save() p.save()
.then(function() { .then(function() {
@ -515,7 +515,7 @@ describe('manipulation', function() {
}); });
describe('updateAttributes', function() { describe('updateAttributes', function() {
var person; let person;
before(function(done) { before(function(done) {
Person.destroyAll(function(err) { Person.destroyAll(function(err) {
@ -727,7 +727,7 @@ describe('manipulation', function() {
it('should allow same stringified id value on updateAttributes', it('should allow same stringified id value on updateAttributes',
function(done) { function(done) {
var pid = person.id; let pid = person.id;
if (typeof person.id === 'object' || typeof person.id === 'number') { if (typeof person.id === 'object' || typeof person.id === 'number') {
// For example MongoDB ObjectId // For example MongoDB ObjectId
pid = person.id.toString(); pid = person.id.toString();
@ -785,7 +785,7 @@ describe('manipulation', function() {
}); });
it('should raises on connector error', function(done) { it('should raises on connector error', function(done) {
var fakeConnector = { const fakeConnector = {
updateAttributes: function(model, id, data, options, cb) { updateAttributes: function(model, id, data, options, cb) {
cb(new Error('Database Error')); cb(new Error('Database Error'));
}, },
@ -799,7 +799,7 @@ describe('manipulation', function() {
}); });
describe('updateOrCreate', function() { describe('updateOrCreate', function() {
var Post, Todo; let Post, Todo;
before('prepare "Post" and "Todo" models', function(done) { before('prepare "Post" and "Todo" models', function(done) {
Post = db.define('Post', { Post = db.define('Post', {
@ -896,7 +896,7 @@ describe('manipulation', function() {
it('should preserve properties with dynamic setters on update', function(done) { it('should preserve properties with dynamic setters on update', function(done) {
StubUser.create({password: 'foo'}, function(err, created) { StubUser.create({password: 'foo'}, function(err, created) {
if (err) return done(err); 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) { StubUser.updateOrCreate(data, function(err, updated) {
if (err) return done(err); if (err) return done(err);
updated.password.should.equal('bar-BAR'); updated.password.should.equal('bar-BAR');
@ -914,7 +914,7 @@ describe('manipulation', function() {
{name: 'a-name', gender: undefined}, {name: 'a-name', gender: undefined},
function(err, instance) { function(err, instance) {
if (err) return done(err); if (err) return done(err);
var result = instance.toObject(); const result = instance.toObject();
result.id.should.eql(instance.id); result.id.should.eql(instance.id);
should.equal(result.name, 'a-name'); should.equal(result.name, 'a-name');
should.equal(result.gender, undefined); should.equal(result.gender, undefined);
@ -923,7 +923,7 @@ describe('manipulation', function() {
{id: instance.id, name: 'updated name'}, {id: instance.id, name: 'updated name'},
function(err, updated) { function(err, updated) {
if (err) return done(err); if (err) return done(err);
var result = updated.toObject(); const result = updated.toObject();
result.id.should.eql(instance.id); result.id.should.eql(instance.id);
should.equal(result.name, 'updated name'); should.equal(result.name, 'updated name');
should.equal(result.gender, null); 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) { it('updates specific instances when PK is not an auto-generated id', function(done) {
// skip the test if the connector is mssql // skip the test if the connector is mssql
// https://github.com/strongloop/loopback-connector-mssql/pull/92#r72853474 // 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(); if (dsName === 'mssql') return done();
Post.create([ Post.create([
@ -952,7 +952,7 @@ describe('manipulation', function() {
}, function(err, instance) { }, function(err, instance) {
if (err) return done(err); if (err) return done(err);
var result = instance.toObject(); const result = instance.toObject();
result.should.have.properties({ result.should.have.properties({
title: 'postA', title: 'postA',
content: 'newContent', content: 'newContent',
@ -972,7 +972,7 @@ describe('manipulation', function() {
}); });
it('should allow save() of the created instance', function(done) { it('should allow save() of the created instance', function(done) {
var unknownId = uid.fromConnector(db) || 999; const unknownId = uid.fromConnector(db) || 999;
Person.updateOrCreate( Person.updateOrCreate(
{id: unknownId, name: 'a-name'}, {id: unknownId, name: 'a-name'},
function(err, inst) { function(err, inst) {
@ -985,9 +985,9 @@ describe('manipulation', function() {
bdd.describeIf(connectorCapabilities.supportForceId !== false, bdd.describeIf(connectorCapabilities.supportForceId !== false,
'updateOrCreate when forceId is true', function() { 'updateOrCreate when forceId is true', function() {
var Post; let Post;
before(function definePostModel(done) { before(function definePostModel(done) {
var ds = getSchema(); const ds = getSchema();
Post = ds.define('Post', { Post = ds.define('Post', {
title: {type: String, length: 255}, title: {type: String, length: 255},
content: {type: String}, content: {type: String},
@ -996,8 +996,8 @@ describe('manipulation', function() {
}); });
it('fails when id does not exist in db & validate is true', function(done) { it('fails when id does not exist in db & validate is true', function(done) {
var unknownId = uid.fromConnector(db) || 123; const unknownId = uid.fromConnector(db) || 123;
var post = {id: unknownId, title: 'a', content: 'AAA'}; const post = {id: unknownId, title: 'a', content: 'AAA'};
Post.updateOrCreate(post, {validate: true}, (err) => { Post.updateOrCreate(post, {validate: true}, (err) => {
should(err).have.property('statusCode', 404); should(err).have.property('statusCode', 404);
done(); done();
@ -1005,8 +1005,8 @@ describe('manipulation', function() {
}); });
it('fails when id does not exist in db & validate is false', function(done) { it('fails when id does not exist in db & validate is false', function(done) {
var unknownId = uid.fromConnector(db) || 123; const unknownId = uid.fromConnector(db) || 123;
var post = {id: unknownId, title: 'a', content: 'AAA'}; const post = {id: unknownId, title: 'a', content: 'AAA'};
Post.updateOrCreate(post, {validate: false}, (err) => { Post.updateOrCreate(post, {validate: false}, (err) => {
should(err).have.property('statusCode', 404); should(err).have.property('statusCode', 404);
done(); done();
@ -1015,8 +1015,8 @@ describe('manipulation', function() {
it('fails when id does not exist in db & validate is false when using updateAttributes', it('fails when id does not exist in db & validate is false when using updateAttributes',
function(done) { function(done) {
var unknownId = uid.fromConnector(db) || 123; const unknownId = uid.fromConnector(db) || 123;
var post = new Post({id: unknownId}); const post = new Post({id: unknownId});
post.updateAttributes({title: 'updated title', content: 'AAA'}, {validate: false}, (err) => { post.updateAttributes({title: 'updated title', content: 'AAA'}, {validate: false}, (err) => {
should(err).have.property('statusCode', 404); should(err).have.property('statusCode', 404);
done(); done();
@ -1024,7 +1024,7 @@ describe('manipulation', function() {
}); });
it('works on create if the request does not include an id', function(done) { 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) => { Post.updateOrCreate(post, (err, p) => {
if (err) return done(err); if (err) return done(err);
p.title.should.equal(post.title); 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; !!getSchema().connector.replaceById;
if (!hasReplaceById) { if (!hasReplaceById) {
describe.skip('replaceById - not implemented', function() {}); describe.skip('replaceById - not implemented', function() {});
} else { } else {
describe('replaceOrCreate', function() { describe('replaceOrCreate', function() {
var Post, unknownId; let Post, unknownId;
before(function(done) { before(function(done) {
db = getSchema(); db = getSchema();
unknownId = uid.fromConnector(db) || 123; unknownId = uid.fromConnector(db) || 123;
@ -1069,7 +1069,7 @@ describe('manipulation', function() {
}); });
it('works without options on create (promise variant)', function(done) { 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) Post.replaceOrCreate(post)
.then(function(p) { .then(function(p) {
should.exist(p); should.exist(p);
@ -1091,7 +1091,7 @@ describe('manipulation', function() {
}); });
it('works with options on create (promise variant)', function(done) { 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}) Post.replaceOrCreate(post, {validate: false})
.then(function(p) { .then(function(p) {
should.exist(p); should.exist(p);
@ -1113,7 +1113,7 @@ describe('manipulation', function() {
}); });
it('works without options on update (promise variant)', function(done) { 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) Post.create(post)
.then(function(created) { .then(function(created) {
created = created.toObject(); created = created.toObject();
@ -1144,7 +1144,7 @@ describe('manipulation', function() {
}); });
it('works with options on update (promise variant)', function(done) { 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) Post.create(post)
.then(function(created) { .then(function(created) {
created = created.toObject(); created = created.toObject();
@ -1234,7 +1234,7 @@ describe('manipulation', function() {
}); });
it('works without options on create (callback variant)', function(done) { 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) { Post.replaceOrCreate(post, function(err, p) {
if (err) return done(err); if (err) return done(err);
p.id.should.eql(post.id); p.id.should.eql(post.id);
@ -1254,7 +1254,7 @@ describe('manipulation', function() {
}); });
it('works with options on create (callback variant)', function(done) { 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) { Post.replaceOrCreate(post, {validate: false}, function(err, p) {
if (err) return done(err); if (err) return done(err);
p.id.should.eql(post.id); p.id.should.eql(post.id);
@ -1277,7 +1277,7 @@ describe('manipulation', function() {
bdd.describeIf(hasReplaceById && connectorCapabilities.supportForceId !== false, 'replaceOrCreate ' + bdd.describeIf(hasReplaceById && connectorCapabilities.supportForceId !== false, 'replaceOrCreate ' +
'when forceId is true', function() { 'when forceId is true', function() {
var Post, unknownId; let Post, unknownId;
before(function(done) { before(function(done) {
db = getSchema(); db = getSchema();
unknownId = uid.fromConnector(db) || 123; unknownId = uid.fromConnector(db) || 123;
@ -1289,7 +1289,7 @@ describe('manipulation', function() {
}); });
it('fails when id does not exist in db', function(done) { 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) { Post.replaceOrCreate(post, function(err, p) {
err.statusCode.should.equal(404); err.statusCode.should.equal(404);
@ -1299,7 +1299,7 @@ describe('manipulation', function() {
// eslint-disable-next-line mocha/no-identical-title // eslint-disable-next-line mocha/no-identical-title
it('works on create if the request does not include an id', function(done) { 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) { Post.replaceOrCreate(post, function(err, p) {
if (err) return done(err); if (err) return done(err);
p.title.should.equal(post.title); p.title.should.equal(post.title);
@ -1329,9 +1329,9 @@ describe('manipulation', function() {
describe.skip('replaceAttributes/replaceById - not implemented', function() {}); describe.skip('replaceAttributes/replaceById - not implemented', function() {});
} else { } else {
describe('replaceAttributes', function() { describe('replaceAttributes', function() {
var postInstance; let postInstance;
var Post; let Post;
var ds = getSchema(); const ds = getSchema();
before(function(done) { before(function(done) {
Post = ds.define('Post', { Post = ds.define('Post', {
title: {type: String, length: 255, index: true}, title: {type: String, length: 255, index: true},
@ -1486,12 +1486,12 @@ describe('manipulation', function() {
}); });
it('should fail when changing id', function(done) { 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) { Post.findById(postInstance.id, function(err, p) {
if (err) return done(err); if (err) return done(err);
p.replaceAttributes({title: 'b', id: unknownId}, function(err, p) { p.replaceAttributes({title: 'b', id: unknownId}, function(err, p) {
should.exist(err); 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; postInstance.id + ' to ' + unknownId;
err.message.should.equal(expectedErrMsg); err.message.should.equal(expectedErrMsg);
done(); done();
@ -1533,7 +1533,7 @@ describe('manipulation', function() {
} }
bdd.describeIf(hasReplaceById, 'replaceById', function() { bdd.describeIf(hasReplaceById, 'replaceById', function() {
var Post; let Post;
before(function(done) { before(function(done) {
db = getSchema(); db = getSchema();
Post = db.define('Post', { Post = db.define('Post', {
@ -1545,8 +1545,8 @@ describe('manipulation', function() {
bdd.itIf(connectorCapabilities.supportForceId !== false, 'fails when id does not exist in db ' + bdd.itIf(connectorCapabilities.supportForceId !== false, 'fails when id does not exist in db ' +
'using replaceById', function(done) { 'using replaceById', function(done) {
var unknownId = uid.fromConnector(db) || 123; const unknownId = uid.fromConnector(db) || 123;
var post = {id: unknownId, title: 'a', content: 'AAA'}; const post = {id: unknownId, title: 'a', content: 'AAA'};
Post.replaceById(post.id, post, function(err, p) { Post.replaceById(post.id, post, function(err, p) {
err.statusCode.should.equal(404); err.statusCode.should.equal(404);
done(); done();
@ -1590,8 +1590,8 @@ describe('manipulation', function() {
should.exist(res); should.exist(res);
res.should.be.instanceOf(Array); res.should.be.instanceOf(Array);
res.should.have.lengthOf(2); res.should.have.lengthOf(2);
var p = res[0]; const p = res[0];
var created = res[1]; const created = res[1];
p.should.be.instanceOf(Person); p.should.be.instanceOf(Person);
p.name.should.equal('Jed'); p.name.should.equal('Jed');
p.gender.should.equal('male'); p.gender.should.equal('male');
@ -1609,8 +1609,8 @@ describe('manipulation', function() {
.then(function(res) { .then(function(res) {
res.should.be.instanceOf(Array); res.should.be.instanceOf(Array);
res.should.have.lengthOf(2); res.should.have.lengthOf(2);
var p = res[0]; const p = res[0];
var created = res[1]; const created = res[1];
p.should.be.instanceOf(Person); p.should.be.instanceOf(Person);
p.name.should.equal('Jed'); p.name.should.equal('Jed');
p.gender.should.equal('male'); p.gender.should.equal('male');
@ -1757,7 +1757,7 @@ describe('manipulation', function() {
bdd.describeIf(connectorCapabilities.reportDeletedCount === false && bdd.describeIf(connectorCapabilities.reportDeletedCount === false &&
connectorCapabilities.deleteWithOtherThanId === false, 'deleteAll/destroyAll case 2', function() { connectorCapabilities.deleteWithOtherThanId === false, 'deleteAll/destroyAll case 2', function() {
var idJohn, idJane; let idJohn, idJane;
beforeEach(function clearOldData(done) { beforeEach(function clearOldData(done) {
Person.deleteAll(done); Person.deleteAll(done);
}); });
@ -1807,7 +1807,7 @@ describe('manipulation', function() {
// eslint-disable-next-line mocha/no-identical-title // eslint-disable-next-line mocha/no-identical-title
it('should report zero deleted instances when no matches are found', it('should report zero deleted instances when no matches are found',
function(done) { function(done) {
var unknownId = uid.fromConnector(db) || 1234567890; const unknownId = uid.fromConnector(db) || 1234567890;
Person.deleteAll({id: unknownId}, function(err, info) { Person.deleteAll({id: unknownId}, function(err, info) {
if (err) return done(err); if (err) return done(err);
should.not.exist(info.count); should.not.exist(info.count);
@ -1855,7 +1855,7 @@ describe('manipulation', function() {
}); });
it('should allow deleteById(id) - fail', function(done) { 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.settings.strictDelete = false;
Person.deleteById(unknownId, function(err, info) { Person.deleteById(unknownId, function(err, info) {
if (err) return done(err); if (err) return done(err);
@ -1869,8 +1869,8 @@ describe('manipulation', function() {
}); });
it('should allow deleteById(id) - fail with error', function(done) { it('should allow deleteById(id) - fail with error', function(done) {
var unknownId = uid.fromConnector(db) || 9999; const unknownId = uid.fromConnector(db) || 9999;
var errMsg = 'No instance with id ' + unknownId.toString() + ' found for Person'; const errMsg = 'No instance with id ' + unknownId.toString() + ' found for Person';
Person.settings.strictDelete = true; Person.settings.strictDelete = true;
Person.deleteById(unknownId, function(err) { Person.deleteById(unknownId, function(err) {
should.exist(err); should.exist(err);
@ -1949,7 +1949,7 @@ describe('manipulation', function() {
describe('initialize', function() { describe('initialize', function() {
it('should initialize object properly', function() { it('should initialize object properly', function() {
var hw = 'Hello word', const hw = 'Hello word',
now = Date.now(), now = Date.now(),
person = new Person({name: hw}); person = new Person({name: hw});
@ -1960,7 +1960,7 @@ describe('manipulation', function() {
}); });
describe('Date $now function (type: Date)', function() { describe('Date $now function (type: Date)', function() {
var CustomModel; let CustomModel;
before(function(done) { before(function(done) {
CustomModel = db.define('CustomModel1', { CustomModel = db.define('CustomModel1', {
@ -1971,7 +1971,7 @@ describe('manipulation', function() {
it('should report current date as default value for date property', it('should report current date as default value for date property',
function(done) { function(done) {
var now = Date.now(); const now = Date.now();
CustomModel.create(function(err, model) { CustomModel.create(function(err, model) {
should.not.exists(err); should.not.exists(err);
@ -1984,7 +1984,7 @@ describe('manipulation', function() {
}); });
describe('Date $now function (type: String)', function() { describe('Date $now function (type: String)', function() {
var CustomModel; let CustomModel;
before(function(done) { before(function(done) {
CustomModel = db.define('CustomModel2', { CustomModel = db.define('CustomModel2', {
@ -2006,7 +2006,7 @@ describe('manipulation', function() {
}); });
describe('now defaultFn', function() { describe('now defaultFn', function() {
var CustomModel; let CustomModel;
before(function(done) { before(function(done) {
CustomModel = db.define('CustomModel3', { CustomModel = db.define('CustomModel3', {
@ -2017,7 +2017,7 @@ describe('manipulation', function() {
it('should generate current time when "defaultFn" is "now"', it('should generate current time when "defaultFn" is "now"',
function(done) { function(done) {
var now = Date.now(); const now = Date.now();
CustomModel.create(function(err, model) { CustomModel.create(function(err, model) {
if (err) return done(err); if (err) return done(err);
model.now.should.be.instanceOf(Date); model.now.should.be.instanceOf(Date);
@ -2028,7 +2028,7 @@ describe('manipulation', function() {
}); });
describe('guid defaultFn', function() { describe('guid defaultFn', function() {
var CustomModel; let CustomModel;
before(function(done) { before(function(done) {
CustomModel = db.define('CustomModel4', { CustomModel = db.define('CustomModel4', {
@ -2047,7 +2047,7 @@ describe('manipulation', function() {
}); });
describe('uuid defaultFn', function() { describe('uuid defaultFn', function() {
var CustomModel; let CustomModel;
before(function(done) { before(function(done) {
CustomModel = db.define('CustomModel5', { CustomModel = db.define('CustomModel5', {
@ -2066,7 +2066,7 @@ describe('manipulation', function() {
}); });
describe('uuidv4 defaultFn', function() { describe('uuidv4 defaultFn', function() {
var CustomModel; let CustomModel;
before(function(done) { before(function(done) {
CustomModel = db.define('CustomModel5', { CustomModel = db.define('CustomModel5', {
@ -2085,11 +2085,11 @@ describe('manipulation', function() {
}); });
describe('shortid defaultFn', function() { describe('shortid defaultFn', function() {
var ModelWithShortId; let ModelWithShortId;
before(createModelWithShortId); before(createModelWithShortId);
it('should generate a new id when "defaultFn" is "shortid"', function(done) { 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) { ModelWithShortId.create(function(err, modelWithShortId) {
if (err) return done(err); if (err) return done(err);
modelWithShortId.shortid.should.match(SHORTID_REGEXP); modelWithShortId.shortid.should.match(SHORTID_REGEXP);
@ -2114,7 +2114,7 @@ describe('manipulation', function() {
describe('property value coercion', function() { describe('property value coercion', function() {
it('should coerce boolean types properly', 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.married.should.equal(false);
p1 = new Person({name: 'John', married: 'true'}); p1 = new Person({name: 'John', married: 'true'});
@ -2155,7 +2155,7 @@ describe('manipulation', function() {
}); });
it('should coerce date types properly', 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.dob.should.eql(new Date('2/1/2015'));
p1 = new Person({name: 'John', dob: '2/1/2015'}); p1 = new Person({name: 'John', dob: '2/1/2015'});
@ -2180,8 +2180,8 @@ describe('manipulation', function() {
}); });
describe('update/updateAll', function() { describe('update/updateAll', function() {
var idBrett, idCarla, idDonna, idFrank, idGrace, idHarry; let idBrett, idCarla, idDonna, idFrank, idGrace, idHarry;
var filterBrett, filterHarry; let filterBrett, filterHarry;
beforeEach(function clearOldData(done) { beforeEach(function clearOldData(done) {
db = getSchema(); db = getSchema();
@ -2230,7 +2230,7 @@ describe('manipulation', function() {
it('should not update instances that do not satisfy the where condition', it('should not update instances that do not satisfy the where condition',
function(done) { function(done) {
idHarry = uid.fromConnector(db) || undefined; idHarry = uid.fromConnector(db) || undefined;
var filter = connectorCapabilities.updateWithOtherThanId === false ? const filter = connectorCapabilities.updateWithOtherThanId === false ?
{id: idHarry} : {name: 'Harry Hoe'}; {id: idHarry} : {name: 'Harry Hoe'};
Person.update(filter, {name: 'Marta Moe'}, function(err, Person.update(filter, {name: 'Marta Moe'}, function(err,
info) { info) {
@ -2250,7 +2250,7 @@ describe('manipulation', function() {
it('should only update instances that satisfy the where condition', it('should only update instances that satisfy the where condition',
function(done) { function(done) {
var filter = connectorCapabilities.deleteWithOtherThanId === false ? const filter = connectorCapabilities.deleteWithOtherThanId === false ?
{id: idBrett} : {name: 'Brett Boe'}; {id: idBrett} : {name: 'Brett Boe'};
Person.update(filter, {name: 'Harry Hoe'}, function(err, Person.update(filter, {name: 'Harry Hoe'}, function(err,
info) { info) {
@ -2325,7 +2325,7 @@ describe('manipulation', function() {
}); });
describe('upsertWithWhere', function() { describe('upsertWithWhere', function() {
var ds, Person; let ds, Person;
before('prepare "Person" model', function(done) { before('prepare "Person" model', function(done) {
ds = getSchema(); ds = getSchema();
Person = ds.define('Person', { Person = ds.define('Person', {
@ -2355,7 +2355,7 @@ describe('manipulation', function() {
it('should preserve properties with dynamic setters on update', function(done) { it('should preserve properties with dynamic setters on update', function(done) {
StubUser.create({password: 'foo'}, function(err, created) { StubUser.create({password: 'foo'}, function(err, created) {
if (err) return done(err); if (err) return done(err);
var data = {password: 'bar'}; const data = {password: 'bar'};
StubUser.upsertWithWhere({id: created.id}, data, function(err, updated) { StubUser.upsertWithWhere({id: created.id}, data, function(err, updated) {
if (err) return done(err); if (err) return done(err);
updated.password.should.equal('bar-BAR'); updated.password.should.equal('bar-BAR');
@ -2383,7 +2383,7 @@ describe('manipulation', function() {
{name: 'updated name'}, {name: 'updated name'},
function(err, updated) { function(err, updated) {
if (err) return done(err); if (err) return done(err);
var result = updated.toObject(); const result = updated.toObject();
result.should.have.properties({ result.should.have.properties({
id: instance.id, id: instance.id,
name: 'updated name', name: 'updated name',
@ -2406,7 +2406,7 @@ describe('manipulation', function() {
}); });
it('works without options on create (promise variant)', function(done) { 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) Person.upsertWithWhere({id: 123}, person)
.then(function(p) { .then(function(p) {
should.exist(p); should.exist(p);
@ -2428,7 +2428,7 @@ describe('manipulation', function() {
}); });
it('works with options on create (promise variant)', function(done) { 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}) Person.upsertWithWhere({id: 234}, person, {validate: false})
.then(function(p) { .then(function(p) {
should.exist(p); should.exist(p);
@ -2450,7 +2450,7 @@ describe('manipulation', function() {
}); });
it('works without options on update (promise variant)', function(done) { 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) Person.create(person)
.then(function(created) { .then(function(created) {
created = created.toObject(); created = created.toObject();
@ -2477,7 +2477,7 @@ describe('manipulation', function() {
}); });
it('works with options on update (promise variant)', function(done) { 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) Person.create(person)
.then(function(created) { .then(function(created) {
created = created.toObject(); created = created.toObject();
@ -2504,7 +2504,7 @@ describe('manipulation', function() {
}); });
it('fails the upsertWithWhere operation when data object is empty', function(done) { it('fails the upsertWithWhere operation when data object is empty', function(done) {
var options = {}; const options = {};
Person.upsertWithWhere({name: 'John Lennon'}, {}, options, Person.upsertWithWhere({name: 'John Lennon'}, {}, options,
function(err) { function(err) {
err.message.should.equal('data object cannot be empty!'); err.message.should.equal('data object cannot be empty!');
@ -2567,7 +2567,7 @@ describe('manipulation', function() {
}); });
function givenSomePeople(done) { function givenSomePeople(done) {
var beatles = [ const beatles = [
{name: 'John Lennon', gender: 'male'}, {name: 'John Lennon', gender: 'male'},
{name: 'Paul McCartney', gender: 'male'}, {name: 'Paul McCartney', gender: 'male'},
{name: 'George Harrison', gender: 'male'}, {name: 'George Harrison', gender: 'male'},

View File

@ -4,21 +4,21 @@
// License text available at https://opensource.org/licenses/MIT // License text available at https://opensource.org/licenses/MIT
'use strict'; 'use strict';
var jdb = require('../'); const jdb = require('../');
var DataSource = jdb.DataSource; const DataSource = jdb.DataSource;
var path = require('path'); const path = require('path');
var fs = require('fs'); const fs = require('fs');
var assert = require('assert'); const assert = require('assert');
var async = require('async'); const async = require('async');
var should = require('./init.js'); const should = require('./init.js');
var Memory = require('../lib/connectors/memory').Memory; const Memory = require('../lib/connectors/memory').Memory;
describe('Memory connector', function() { describe('Memory connector', function() {
var file = path.join(__dirname, 'memory.json'); const file = path.join(__dirname, 'memory.json');
function readModels(done) { function readModels(done) {
fs.readFile(file, function(err, data) { fs.readFile(file, function(err, data) {
var json = JSON.parse(data.toString()); const json = JSON.parse(data.toString());
assert(json.models); assert(json.models);
assert(json.ids.User); assert(json.ids.User);
done(err, json); done(err, json);
@ -34,15 +34,15 @@ describe('Memory connector', function() {
}); });
describe('with file', function() { describe('with file', function() {
var ds; let ds;
function createUserModel() { function createUserModel() {
var ds = new DataSource({ const ds = new DataSource({
connector: 'memory', connector: 'memory',
file: file, file: file,
}); });
var User = ds.createModel('User', { const User = ds.createModel('User', {
id: { id: {
type: Number, type: Number,
id: true, id: true,
@ -57,8 +57,8 @@ describe('Memory connector', function() {
return User; return User;
} }
var User; let User;
var ids = []; const ids = [];
before(function() { before(function() {
User = createUserModel(); User = createUserModel();
@ -73,7 +73,7 @@ describe('Memory connector', function() {
}); });
it('should persist create', function(done) { it('should persist create', function(done) {
var count = 0; let count = 0;
async.eachSeries(['John1', 'John2', 'John3'], function(item, cb) { async.eachSeries(['John1', 'John2', 'John3'], function(item, cb) {
User.create({name: item}, function(err, result) { User.create({name: item}, function(err, result) {
ids.push(result.id); ids.push(result.id);
@ -95,8 +95,8 @@ describe('Memory connector', function() {
it('should not have out of sequence read/write', function(done) { it('should not have out of sequence read/write', function(done) {
// Create the new data source with the same file to simulate // Create the new data source with the same file to simulate
// existing records // existing records
var User = createUserModel(); const User = createUserModel();
var ds = User.dataSource; const ds = User.dataSource;
async.times(10, function(n, next) { async.times(10, function(n, next) {
if (n === 10) { if (n === 10) {
@ -107,7 +107,7 @@ describe('Memory connector', function() {
next(); next();
}, function(err) { }, function(err) {
async.eachSeries(['John4', 'John5'], function(item, cb) { async.eachSeries(['John4', 'John5'], function(item, cb) {
var count = 0; const count = 0;
User.create({name: item}, function(err, result) { User.create({name: item}, function(err, result) {
ids.push(result.id); ids.push(result.id);
cb(err); cb(err);
@ -152,7 +152,7 @@ describe('Memory connector', function() {
return done(err); return done(err);
} }
assert.equal(Object.keys(json.models.User).length, 4); 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.equal(user.name, 'John');
assert(user.id === ids[1]); assert(user.id === ids[1]);
done(); done();
@ -171,7 +171,7 @@ describe('Memory connector', function() {
return done(err); return done(err);
} }
assert.equal(Object.keys(json.models.User).length, 4); 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.equal(user.name, 'John1');
assert(user.id === ids[1]); assert(user.id === ids[1]);
done(); done();
@ -190,11 +190,11 @@ describe('Memory connector', function() {
}); });
describe('Query for memory connector', function() { describe('Query for memory connector', function() {
var ds = new DataSource({ const ds = new DataSource({
connector: 'memory', connector: 'memory',
}); });
var User = ds.define('User', { const User = ds.define('User', {
seq: {type: Number, index: true}, seq: {type: Number, index: true},
name: {type: String, index: true, sort: true}, name: {type: String, index: true, sort: true},
email: {type: String, index: true}, email: {type: String, index: true},
@ -471,7 +471,7 @@ describe('Memory connector', function() {
User.find({where: {seq: {neq: 4}}}, function(err, users) { User.find({where: {seq: {neq: 4}}}, function(err, users) {
should.not.exist(err); should.not.exist(err);
users.length.should.be.equal(5); 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); users[i].seq.should.not.be.equal(4);
} }
done(); done();
@ -482,7 +482,7 @@ describe('Memory connector', function() {
User.find({where: {role: {neq: 'lead'}}}, function(err, users) { User.find({where: {role: {neq: 'lead'}}}, function(err, users) {
should.not.exist(err); should.not.exist(err);
users.length.should.be.equal(4); 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) { if (users[i].role) {
users[i].role.not.be.equal('lead'); users[i].role.not.be.equal('lead');
} }
@ -495,7 +495,7 @@ describe('Memory connector', function() {
User.find({where: {role: {neq: null}}}, function(err, users) { User.find({where: {role: {neq: null}}}, function(err, users) {
should.not.exist(err); should.not.exist(err);
users.length.should.be.equal(2); 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); should.exist(users[i].role);
} }
done(); done();
@ -554,7 +554,7 @@ describe('Memory connector', function() {
}); });
function seed(done) { function seed(done) {
var beatles = [ const beatles = [
{ {
seq: 0, seq: 0,
name: 'John Lennon', name: 'John Lennon',
@ -616,19 +616,19 @@ describe('Memory connector', function() {
}); });
it('should use collection setting', function(done) { it('should use collection setting', function(done) {
var ds = new DataSource({ const ds = new DataSource({
connector: 'memory', connector: 'memory',
}); });
var Product = ds.createModel('Product', { const Product = ds.createModel('Product', {
name: String, name: String,
}); });
var Tool = ds.createModel('Tool', { const Tool = ds.createModel('Tool', {
name: String, name: String,
}, {memory: {collection: 'Product'}}); }, {memory: {collection: 'Product'}});
var Widget = ds.createModel('Widget', { const Widget = ds.createModel('Widget', {
name: String, name: String,
}, {memory: {collection: 'Product'}}); }, {memory: {collection: 'Product'}});
@ -658,8 +658,8 @@ describe('Memory connector', function() {
}); });
it('should refuse to create object with duplicate id', function(done) { it('should refuse to create object with duplicate id', function(done) {
var ds = new DataSource({connector: 'memory'}); const ds = new DataSource({connector: 'memory'});
var Product = ds.define('ProductTest', {name: String}, {forceId: false}); const Product = ds.define('ProductTest', {name: String}, {forceId: false});
ds.automigrate('ProductTest', function(err) { ds.automigrate('ProductTest', function(err) {
if (err) return done(err); if (err) return done(err);
@ -678,7 +678,7 @@ describe('Memory connector', function() {
}); });
describe('automigrate', function() { describe('automigrate', function() {
var ds; let ds;
beforeEach(function() { beforeEach(function() {
ds = new DataSource({ ds = new DataSource({
connector: 'memory', connector: 'memory',
@ -757,7 +757,7 @@ describe('Memory connector', function() {
}); });
describe('findOrCreate', function() { describe('findOrCreate', function() {
var ds, Cars; let ds, Cars;
before(function() { before(function() {
ds = new DataSource({connector: 'memory'}); ds = new DataSource({connector: 'memory'});
Cars = ds.define('Cars', { 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) { 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) { async.times(100, function(n, next) {
var initialData = {color: 'white'}; const initialData = {color: 'white'};
var query = {'where': initialData}; const query = {'where': initialData};
Cars.findOrCreate(query, initialData, function(err, car, created) { Cars.findOrCreate(query, initialData, function(err, car, created) {
if (created) creationNum++; if (created) creationNum++;
next(err, car); next(err, car);
@ -788,7 +788,7 @@ describe('Memory connector', function() {
}); });
describe('automigrate when NO models are attached', function() { describe('automigrate when NO models are attached', function() {
var ds; let ds;
beforeEach(function() { beforeEach(function() {
ds = new DataSource({ ds = new DataSource({
connector: 'memory', connector: 'memory',
@ -811,7 +811,7 @@ describe('Memory connector', function() {
}); });
describe('With mocked autoupdate', function() { describe('With mocked autoupdate', function() {
var ds, model; let ds, model;
beforeEach(function() { beforeEach(function() {
ds = new DataSource({ ds = new DataSource({
connector: 'memory', connector: 'memory',
@ -902,7 +902,7 @@ describe('Memory connector', function() {
}); });
describe('Optimized connector', function() { describe('Optimized connector', function() {
var ds = new DataSource({connector: Memory}); const ds = new DataSource({connector: Memory});
require('./persistence-hooks.suite')(ds, should, { require('./persistence-hooks.suite')(ds, should, {
replaceOrCreateReportsNewInstance: true, replaceOrCreateReportsNewInstance: true,
@ -910,7 +910,7 @@ describe('Optimized connector', function() {
}); });
describe('Unoptimized connector', function() { describe('Unoptimized connector', function() {
var ds = new DataSource({connector: Memory}); const ds = new DataSource({connector: Memory});
// disable optimized methods // disable optimized methods
ds.connector.updateOrCreate = false; ds.connector.updateOrCreate = false;
@ -923,7 +923,8 @@ describe('Unoptimized connector', function() {
}); });
describe('Memory connector with options', function() { describe('Memory connector with options', function() {
var ds, savedOptions = {}, Post; const savedOptions = {};
let ds, Post;
before(function() { before(function() {
ds = new DataSource({connector: 'memory'}); ds = new DataSource({connector: 'memory'});
@ -955,7 +956,7 @@ describe('Memory connector with options', function() {
}); });
it('should receive options from the find method', function(done) { 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) { Post.find({where: {title: 't1'}}, opts, function(err, p) {
savedOptions.find.should.be.eql(opts); savedOptions.find.should.be.eql(opts);
done(err); done(err);
@ -963,7 +964,7 @@ describe('Memory connector with options', function() {
}); });
it('should treat first object arg as filter for find', function(done) { 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) { Post.find(filter, function(err, p) {
savedOptions.find.should.be.eql({}); savedOptions.find.should.be.eql({});
done(err); done(err);
@ -971,7 +972,7 @@ describe('Memory connector with options', function() {
}); });
it('should receive options from the create method', function(done) { 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) { Post.create({title: 't1', content: 'c1'}, opts, function(err, p) {
savedOptions.create.should.be.eql(opts); savedOptions.create.should.be.eql(opts);
done(err); done(err);
@ -979,7 +980,7 @@ describe('Memory connector with options', function() {
}); });
it('should receive options from the update method', function(done) { 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'}, Post.update({title: 't1'}, {content: 'c1 --> c2'},
opts, function(err, p) { opts, function(err, p) {
savedOptions.update.should.be.eql(opts); savedOptions.update.should.be.eql(opts);
@ -989,7 +990,7 @@ describe('Memory connector with options', function() {
}); });
describe('Memory connector with observers', function() { describe('Memory connector with observers', function() {
var ds = new DataSource({ const ds = new DataSource({
connector: 'memory', connector: 'memory',
}); });
@ -999,10 +1000,10 @@ describe('Memory connector with observers', function() {
}); });
it('should notify observers', function(done) { it('should notify observers', function(done) {
var events = []; const events = [];
ds.connector.execute = function(command, params, options, cb) { ds.connector.execute = function(command, params, options, cb) {
var self = this; const self = this;
var context = {command: command, params: params, options: options}; const context = {command: command, params: params, options: options};
self.notifyObserversOf('before execute', context, function(err) { self.notifyObserversOf('before execute', context, function(err) {
process.nextTick(function() { process.nextTick(function() {
if (err) return cb(err); if (err) return cb(err);

View File

@ -5,21 +5,21 @@
// This test written in mocha+should.js // This test written in mocha+should.js
'use strict'; 'use strict';
var should = require('./init.js'); const should = require('./init.js');
var jdb = require('../'); const jdb = require('../');
var ModelBuilder = jdb.ModelBuilder; const ModelBuilder = jdb.ModelBuilder;
var DataSource = jdb.DataSource; const DataSource = jdb.DataSource;
var Memory = require('../lib/connectors/memory'); const Memory = require('../lib/connectors/memory');
var modelBuilder = new ModelBuilder(); const modelBuilder = new ModelBuilder();
var mixins = modelBuilder.mixins; const mixins = modelBuilder.mixins;
function timestamps(Model, options) { function timestamps(Model, options) {
Model.defineProperty('createdAt', {type: Date}); Model.defineProperty('createdAt', {type: Date});
Model.defineProperty('updatedAt', {type: Date}); Model.defineProperty('updatedAt', {type: Date});
var originalBeforeSave = Model.beforeSave; const originalBeforeSave = Model.beforeSave;
Model.beforeSave = function(next, data) { Model.beforeSave = function(next, data) {
Model.applyTimestamps(data, this.isNewRecord()); Model.applyTimestamps(data, this.isNewRecord());
if (data.createdAt) { if (data.createdAt) {
@ -62,24 +62,24 @@ describe('Model class', function() {
}); });
it('should apply a mixin class', function() { it('should apply a mixin class', function() {
var Address = modelBuilder.define('Address', { const Address = modelBuilder.define('Address', {
street: {type: 'string', required: true}, street: {type: 'string', required: true},
city: {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);
var Item = memory.createModel('Item', {name: 'string'}, { const Item = memory.createModel('Item', {name: 'string'}, {
mixins: {Address: true}, mixins: {Address: true},
}); });
var properties = Item.definition.properties; const properties = Item.definition.properties;
properties.street.should.eql({type: String, required: true}); properties.street.should.eql({type: String, required: true});
properties.city.should.eql({type: String, required: true}); properties.city.should.eql({type: String, required: true});
}); });
it('should fail to apply an undefined mixin class', function() { 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() { function applyMixin() {
memory.createModel('Item', {name: 'string'}, { memory.createModel('Item', {name: 'string'}, {
mixins: {UndefinedMixin: true}, mixins: {UndefinedMixin: true},
@ -89,8 +89,8 @@ describe('Model class', function() {
}); });
it('should apply mixins', function(done) { it('should apply mixins', function(done) {
var memory = new DataSource('mem', {connector: Memory}, modelBuilder); const memory = new DataSource('mem', {connector: Memory}, modelBuilder);
var Item = memory.createModel('Item', {name: 'string'}, { const Item = memory.createModel('Item', {name: 'string'}, {
mixins: { mixins: {
TimeStamp: true, TimeStamp: true,
Demo: {value: true}, Demo: {value: true},
@ -108,7 +108,7 @@ describe('Model class', function() {
Item.multiMixin.foo.should.equal('bar'); Item.multiMixin.foo.should.equal('bar');
Item.multiMixin.fox.should.equal('baz'); Item.multiMixin.fox.should.equal('baz');
var properties = Item.definition.properties; const properties = Item.definition.properties;
properties.createdAt.should.eql({type: Date}); properties.createdAt.should.eql({type: Date});
properties.updatedAt.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() { it('should fail to apply undefined mixin', function() {
var memory = new DataSource('mem', {connector: Memory}, modelBuilder); const memory = new DataSource('mem', {connector: Memory}, modelBuilder);
var Item = memory.createModel('Item', {name: 'string'}); const Item = memory.createModel('Item', {name: 'string'});
function applyMixin() { function applyMixin() {
Item.mixin('UndefinedMixin', {foo: 'bar'}); Item.mixin('UndefinedMixin', {foo: 'bar'});
@ -131,14 +131,14 @@ describe('Model class', function() {
}); });
describe('#mixin()', function() { describe('#mixin()', function() {
var Person, Author, Address; let Person, Author, Address;
beforeEach(function() { beforeEach(function() {
Address = modelBuilder.define('Address', { Address = modelBuilder.define('Address', {
street: {type: 'string', required: true}, street: {type: 'string', required: true},
city: {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'}); Person = memory.createModel('Person', {name: 'string'});
Author = memory.createModel('Author', {name: 'string'}); Author = memory.createModel('Author', {name: 'string'});
}); });

View File

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

View File

@ -5,26 +5,26 @@
// This test written in mocha+should.js // This test written in mocha+should.js
'use strict'; 'use strict';
var should = require('./init.js'); const should = require('./init.js');
var assert = require('assert'); const assert = require('assert');
var jdb = require('../'); const jdb = require('../');
var ModelBuilder = jdb.ModelBuilder; const ModelBuilder = jdb.ModelBuilder;
var DataSource = jdb.DataSource; const DataSource = jdb.DataSource;
var Memory = require('../lib/connectors/memory'); const Memory = require('../lib/connectors/memory');
var ModelDefinition = require('../lib/model-definition'); const ModelDefinition = require('../lib/model-definition');
describe('ModelDefinition class', function() { describe('ModelDefinition class', function() {
var memory; let memory;
beforeEach(function() { beforeEach(function() {
memory = new DataSource({connector: Memory}); memory = new DataSource({connector: Memory});
}); });
it('should be able to define plain models', function(done) { 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', name: 'string',
bio: ModelBuilder.Text, bio: ModelBuilder.Text,
approved: Boolean, approved: Boolean,
@ -39,7 +39,7 @@ describe('ModelDefinition class', function() {
assert.equal(User.properties.joinedAt.type, Date); assert.equal(User.properties.joinedAt.type, Date);
assert.equal(User.properties.age.type, Number); assert.equal(User.properties.age.type, Number);
var json = User.toJSON(); const json = User.toJSON();
assert.equal(json.name, 'User'); assert.equal(json.name, 'User');
assert.equal(json.properties.name.type, 'String'); assert.equal(json.properties.name.type, 'String');
assert.equal(json.properties.bio.type, 'Text'); 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) { 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', name: 'string',
bio: ModelBuilder.Text, bio: ModelBuilder.Text,
approved: Boolean, approved: Boolean,
@ -65,7 +65,7 @@ describe('ModelDefinition class', function() {
User.build(); User.build();
var json = User.toJSON(); let json = User.toJSON();
User.defineProperty('id', {type: 'number', id: true}); User.defineProperty('id', {type: 'number', id: true});
assert.equal(User.properties.name.type, String); assert.equal(User.properties.name.type, String);
@ -83,9 +83,9 @@ describe('ModelDefinition class', function() {
}); });
it('should be able to define nesting models', function(done) { 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, name: String,
bio: ModelBuilder.Text, bio: ModelBuilder.Text,
approved: Boolean, approved: Boolean,
@ -107,7 +107,7 @@ describe('ModelDefinition class', function() {
assert.equal(User.properties.age.type, Number); assert.equal(User.properties.age.type, Number);
assert.equal(typeof User.properties.address.type, 'function'); assert.equal(typeof User.properties.address.type, 'function');
var json = User.toJSON(); const json = User.toJSON();
assert.equal(json.name, 'User'); assert.equal(json.name, 'User');
assert.equal(json.properties.name.type, 'String'); assert.equal(json.properties.name.type, 'String');
assert.equal(json.properties.bio.type, 'Text'); 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) { 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, street: String,
city: String, city: String,
zipCode: String, zipCode: String,
state: String, state: String,
}); });
var User = new ModelDefinition(modelBuilder, 'User', { const User = new ModelDefinition(modelBuilder, 'User', {
name: String, name: String,
bio: ModelBuilder.Text, bio: ModelBuilder.Text,
approved: Boolean, approved: Boolean,
@ -150,7 +150,7 @@ describe('ModelDefinition class', function() {
assert.equal(User.properties.age.type, Number); assert.equal(User.properties.age.type, Number);
assert.equal(User.properties.address.type, Address); assert.equal(User.properties.address.type, Address);
var json = User.toJSON(); const json = User.toJSON();
assert.equal(json.name, 'User'); assert.equal(json.name, 'User');
assert.equal(json.properties.name.type, 'String'); assert.equal(json.properties.name.type, 'String');
assert.equal(json.properties.bio.type, 'Text'); 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) { 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, street: String,
city: String, city: String,
zipCode: String, zipCode: String,
state: String, state: String,
}); });
var User = new ModelDefinition(modelBuilder, 'User', { const User = new ModelDefinition(modelBuilder, 'User', {
name: String, name: String,
bio: ModelBuilder.Text, bio: ModelBuilder.Text,
approved: Boolean, approved: Boolean,
@ -190,7 +190,7 @@ describe('ModelDefinition class', function() {
assert.equal(User.properties.age.type, Number); assert.equal(User.properties.age.type, Number);
assert.equal(User.properties.address.type, Address); assert.equal(User.properties.address.type, Address);
var json = User.toJSON(); const json = User.toJSON();
assert.equal(json.name, 'User'); assert.equal(json.name, 'User');
assert.equal(json.properties.name.type, 'String'); assert.equal(json.properties.name.type, 'String');
assert.equal(json.properties.bio.type, 'Text'); assert.equal(json.properties.bio.type, 'Text');
@ -204,9 +204,9 @@ describe('ModelDefinition class', function() {
}); });
it('should report correct id names', function(done) { 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}, userId: {type: String, id: true},
name: 'string', name: 'string',
bio: ModelBuilder.Text, bio: ModelBuilder.Text,
@ -221,9 +221,9 @@ describe('ModelDefinition class', function() {
}); });
it('should sort id properties by its index', 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}, userId: {type: String, id: 2},
userType: {type: String, id: 1}, userType: {type: String, id: 1},
name: 'string', name: 'string',
@ -233,7 +233,7 @@ describe('ModelDefinition class', function() {
age: 'number', age: 'number',
}); });
var ids = User.ids(); const ids = User.ids();
assert.ok(Array.isArray(ids)); assert.ok(Array.isArray(ids));
assert.equal(ids.length, 2); assert.equal(ids.length, 2);
assert.equal(ids[0].id, 1); assert.equal(ids[0].id, 1);
@ -243,9 +243,9 @@ describe('ModelDefinition class', function() {
}); });
it('should report correct table/column names', function(done) { 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'}}, userId: {type: String, id: true, oracle: {column: 'ID'}},
name: 'string', name: 'string',
}, {oracle: {table: 'USER'}}); }, {oracle: {table: 'USER'}});
@ -259,11 +259,11 @@ describe('ModelDefinition class', function() {
describe('maxDepthOfQuery', function() { describe('maxDepthOfQuery', function() {
it('should report errors for deep query than maxDepthOfQuery', function(done) { 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, maxDepthOfQuery: 5,
}); });
var filter = givenComplexFilter(); const filter = givenComplexFilter();
MyModel.find(filter, function(err) { MyModel.find(filter, function(err) {
should.exist(err); should.exist(err);
@ -273,11 +273,11 @@ describe('ModelDefinition class', function() {
}); });
it('should honor maxDepthOfQuery setting', function(done) { it('should honor maxDepthOfQuery setting', function(done) {
var MyModel = memory.createModel('my-model', {}, { const MyModel = memory.createModel('my-model', {}, {
maxDepthOfQuery: 20, maxDepthOfQuery: 20,
}); });
var filter = givenComplexFilter(); const filter = givenComplexFilter();
MyModel.find(filter, function(err) { MyModel.find(filter, function(err) {
should.not.exist(err); should.not.exist(err);
@ -286,11 +286,11 @@ describe('ModelDefinition class', function() {
}); });
it('should honor maxDepthOfQuery in options', function(done) { it('should honor maxDepthOfQuery in options', function(done) {
var MyModel = memory.createModel('my-model', {}, { const MyModel = memory.createModel('my-model', {}, {
maxDepthOfQuery: 5, maxDepthOfQuery: 5,
}); });
var filter = givenComplexFilter(); const filter = givenComplexFilter();
MyModel.find(filter, {maxDepthOfQuery: 20}, function(err) { MyModel.find(filter, {maxDepthOfQuery: 20}, function(err) {
should.not.exist(err); should.not.exist(err);
@ -299,28 +299,28 @@ describe('ModelDefinition class', function() {
}); });
function givenComplexFilter() { 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}]}]}]}]}]}]}]}]}]}}; [{and: [{and: [{and: [{x: 1}]}]}]}]}]}]}]}]}]}};
return filter; return filter;
} }
}); });
it('should serialize protected properties into JSON', function() { it('should serialize protected properties into JSON', function() {
var ProtectedModel = memory.createModel('protected', {}, { const ProtectedModel = memory.createModel('protected', {}, {
protected: ['protectedProperty'], protected: ['protectedProperty'],
}); });
var pm = new ProtectedModel({ const pm = new ProtectedModel({
id: 1, foo: 'bar', protectedProperty: 'protected', id: 1, foo: 'bar', protectedProperty: 'protected',
}); });
var serialized = pm.toJSON(); const serialized = pm.toJSON();
assert.deepEqual(serialized, { assert.deepEqual(serialized, {
id: 1, foo: 'bar', protectedProperty: 'protected', id: 1, foo: 'bar', protectedProperty: 'protected',
}); });
}); });
it('should not serialize protected properties of nested models into JSON', function(done) { it('should not serialize protected properties of nested models into JSON', function(done) {
var Parent = memory.createModel('parent'); const Parent = memory.createModel('parent');
var Child = memory.createModel('child', {}, {protected: ['protectedProperty']}); const Child = memory.createModel('child', {}, {protected: ['protectedProperty']});
Parent.hasMany(Child); Parent.hasMany(Child);
Parent.create({ Parent.create({
name: 'parent', name: 'parent',
@ -333,8 +333,8 @@ describe('ModelDefinition class', function() {
if (err) return done(err); if (err) return done(err);
Parent.find({include: 'children'}, function(err, parents) { Parent.find({include: 'children'}, function(err, parents) {
if (err) return done(err); if (err) return done(err);
var serialized = parents[0].toJSON(); const serialized = parents[0].toJSON();
var child = serialized.children[0]; const child = serialized.children[0];
assert.equal(child.name, 'child'); assert.equal(child.name, 'child');
assert.notEqual(child.protectedProperty, 'protectedValue'); assert.notEqual(child.protectedProperty, 'protectedValue');
done(); done();
@ -344,15 +344,15 @@ describe('ModelDefinition class', function() {
}); });
it('should not serialize hidden properties into JSON', function() { it('should not serialize hidden properties into JSON', function() {
var HiddenModel = memory.createModel('hidden', {}, { const HiddenModel = memory.createModel('hidden', {}, {
hidden: ['secret'], hidden: ['secret'],
}); });
var hm = new HiddenModel({ const hm = new HiddenModel({
id: 1, id: 1,
foo: 'bar', foo: 'bar',
secret: 'secret', secret: 'secret',
}); });
var serialized = hm.toJSON(); const serialized = hm.toJSON();
assert.deepEqual(serialized, { assert.deepEqual(serialized, {
id: 1, id: 1,
foo: 'bar', foo: 'bar',
@ -360,8 +360,8 @@ describe('ModelDefinition class', function() {
}); });
it('should not serialize hidden properties of nested models into JSON', function(done) { it('should not serialize hidden properties of nested models into JSON', function(done) {
var Parent = memory.createModel('parent'); const Parent = memory.createModel('parent');
var Child = memory.createModel('child', {}, {hidden: ['secret']}); const Child = memory.createModel('child', {}, {hidden: ['secret']});
Parent.hasMany(Child); Parent.hasMany(Child);
Parent.create({ Parent.create({
name: 'parent', name: 'parent',
@ -374,8 +374,8 @@ describe('ModelDefinition class', function() {
if (err) return done(err); if (err) return done(err);
Parent.find({include: 'children'}, function(err, parents) { Parent.find({include: 'children'}, function(err, parents) {
if (err) return done(err); if (err) return done(err);
var serialized = parents[0].toJSON(); const serialized = parents[0].toJSON();
var child = serialized.children[0]; const child = serialized.children[0];
assert.equal(child.name, 'child'); assert.equal(child.name, 'child');
assert.notEqual(child.secret, 'secret'); assert.notEqual(child.secret, 'secret');
done(); done();
@ -385,7 +385,7 @@ describe('ModelDefinition class', function() {
}); });
describe('hidden properties', function() { describe('hidden properties', function() {
var Child; let Child;
describe('with hidden array', function() { describe('with hidden array', function() {
beforeEach(function() { givenChildren(); }); beforeEach(function() { givenChildren(); });
@ -493,7 +493,7 @@ describe('ModelDefinition class', function() {
}; };
describe('hidden nested properties', function() { describe('hidden nested properties', function() {
var Child; let Child;
beforeEach(givenChildren); beforeEach(givenChildren);
it('should be removed if used in where as a composite key - x.secret', function() { 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() { function givenChildren() {
var hiddenProps = {hidden: ['secret']}; const hiddenProps = {hidden: ['secret']};
Child = memory.createModel('child', { Child = memory.createModel('child', {
name: String, name: String,
x: { x: {
@ -555,8 +555,8 @@ describe('ModelDefinition class', function() {
} }
describe('protected properties', function() { describe('protected properties', function() {
var Parent; let Parent;
var Child; let Child;
beforeEach(givenParentAndChild); beforeEach(givenParentAndChild);
it('should be removed if used in include scope', function() { it('should be removed if used in include scope', function() {
@ -614,8 +614,8 @@ describe('ModelDefinition class', function() {
}); });
describe('hidden properties in include', function() { describe('hidden properties in include', function() {
var Parent; let Parent;
var Child; let Child;
beforeEach(givenParentAndChildWithHiddenProperty); beforeEach(givenParentAndChildWithHiddenProperty);
it('should be rejected if used in scope', function() { 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() { 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; }); process.once('deprecation', function(err) { message = err.message; });
memory.createModel('Ctor', {'constructor': String}); memory.createModel('Ctor', {'constructor': String});
@ -663,7 +663,7 @@ describe('ModelDefinition class', function() {
it('should throw error for dynamic property names containing dot', it('should throw error for dynamic property names containing dot',
function(done) { function(done) {
var Model = memory.createModel('DynamicDotted'); const Model = memory.createModel('DynamicDotted');
Model.create({'dot.name': 'dot.value'}, function(err) { Model.create({'dot.name': 'dot.value'}, function(err) {
err.should.be.instanceOf(Error); err.should.be.instanceOf(Error);
err.message.should.match(/dot\(s\).*DynamicDotted.*dot\.name/); 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) { 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) { Model.create({'constructor': 'myCtor'}, function(err) {
assert.equal(err.message, 'Property name "constructor" is not allowed in DynamicCtor data'); assert.equal(err.message, 'Property name "constructor" is not allowed in DynamicCtor data');
done(); done();
@ -680,18 +680,18 @@ describe('ModelDefinition class', function() {
}); });
it('should support "array" type shortcut', function() { it('should support "array" type shortcut', function() {
var Model = memory.createModel('TwoArrays', { const Model = memory.createModel('TwoArrays', {
regular: Array, regular: Array,
sugar: 'array', sugar: 'array',
}); });
var props = Model.definition.properties; const props = Model.definition.properties;
props.regular.type.should.equal(props.sugar.type); props.regular.type.should.equal(props.sugar.type);
}); });
context('hasPK', function() { context('hasPK', function() {
context('with primary key defined', function() { context('with primary key defined', function() {
var Todo; let Todo;
before(function prepModel() { before(function prepModel() {
Todo = new ModelDefinition(new ModelBuilder(), 'Todo', { Todo = new ModelDefinition(new ModelBuilder(), 'Todo', {
content: 'string', content: 'string',
@ -709,7 +709,7 @@ describe('ModelDefinition class', function() {
}); });
context('without primary key defined', function() { context('without primary key defined', function() {
var Todo; let Todo;
before(function prepModel() { before(function prepModel() {
Todo = new ModelDefinition(new ModelBuilder(), 'Todo', { Todo = new ModelDefinition(new ModelBuilder(), 'Todo', {
content: 'string', content: 'string',

View File

@ -74,7 +74,7 @@ describe('Model class inheritance', function() {
}; };
// saving original getMergePolicy method // saving original getMergePolicy method
let originalGetMergePolicy = base.getMergePolicy; const originalGetMergePolicy = base.getMergePolicy;
// the injected getMergePolicy method captures the provided configureModelMerge option // the injected getMergePolicy method captures the provided configureModelMerge option
base.getMergePolicy = function(options) { base.getMergePolicy = function(options) {
@ -154,9 +154,9 @@ describe('Model class inheritance', function() {
}); });
it('allows model extension', function(done) { 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, name: String,
bio: ModelBuilder.Text, bio: ModelBuilder.Text,
approved: Boolean, approved: Boolean,
@ -164,9 +164,9 @@ describe('Model class inheritance', function() {
age: Number, 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.be.type('object').and.have.property('name', 'Joe');
customer.should.have.property('name', 'Joe'); customer.should.have.property('name', 'Joe');
@ -179,8 +179,8 @@ describe('Model class inheritance', function() {
// Remove internal properties // Remove internal properties
return k.indexOf('__') === -1; return k.indexOf('__') === -1;
}).length, 0); }).length, 0);
var count = 0; let count = 0;
for (var p in customer.toObject()) { for (const p in customer.toObject()) {
if (p.indexOf('__') === 0) { if (p.indexOf('__') === 0) {
continue; continue;
} }
@ -198,9 +198,9 @@ describe('Model class inheritance', function() {
}); });
it('allows model extension with merged settings', function(done) { 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, name: String,
}, { }, {
defaultPermission: 'ALLOW', 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}}, { {customerId: {type: String, id: true}}, {
defaultPermission: 'DENY', defaultPermission: 'DENY',
acls: [ acls: [

View File

@ -4,23 +4,23 @@
// License text available at https://opensource.org/licenses/MIT // License text available at https://opensource.org/licenses/MIT
'use strict'; 'use strict';
var jdb = require('../'); const jdb = require('../');
var DataSource = jdb.DataSource; const DataSource = jdb.DataSource;
var path = require('path'); const path = require('path');
var fs = require('fs'); const fs = require('fs');
var assert = require('assert'); const assert = require('assert');
var async = require('async'); const async = require('async');
var should = require('./init.js'); const should = require('./init.js');
var Memory = require('../lib/connectors/memory').Memory; const Memory = require('../lib/connectors/memory').Memory;
describe('normalizeUndefinedInQuery', function() { describe('normalizeUndefinedInQuery', function() {
describe('with setting "throw"', function() { describe('with setting "throw"', function() {
var ds = new DataSource({ const ds = new DataSource({
connector: 'memory', connector: 'memory',
normalizeUndefinedInQuery: 'throw', normalizeUndefinedInQuery: 'throw',
}); });
var User = ds.define('User', { const User = ds.define('User', {
seq: {type: Number, index: true}, seq: {type: Number, index: true},
name: {type: String, index: true, sort: true}, name: {type: String, index: true, sort: true},
email: {type: String, index: true}, email: {type: String, index: true},
@ -87,11 +87,11 @@ describe('normalizeUndefinedInQuery', function() {
}); });
describe('with setting "nullify"', function() { describe('with setting "nullify"', function() {
var ds = new DataSource({ const ds = new DataSource({
connector: 'memory', connector: 'memory',
}); });
var User = ds.define('User', { const User = ds.define('User', {
seq: {type: Number, index: true}, seq: {type: Number, index: true},
name: {type: String, index: true, sort: true}, name: {type: String, index: true, sort: true},
email: {type: String, index: true}, email: {type: String, index: true},
@ -165,11 +165,11 @@ describe('normalizeUndefinedInQuery', function() {
}); });
describe('with setting "ignore"', function() { describe('with setting "ignore"', function() {
var ds = new DataSource({ const ds = new DataSource({
connector: 'memory', connector: 'memory',
}); });
var User = ds.define('User', { const User = ds.define('User', {
seq: {type: Number, index: true}, seq: {type: Number, index: true},
name: {type: String, index: true, sort: true}, name: {type: String, index: true, sort: true},
email: {type: String, index: true}, email: {type: String, index: true},
@ -244,7 +244,7 @@ describe('normalizeUndefinedInQuery', function() {
}); });
function seed(User, done) { function seed(User, done) {
var beatles = [ const beatles = [
{ {
seq: 0, seq: 0,
name: 'John Lennon', name: 'John Lennon',

View File

@ -5,18 +5,18 @@
'use strict'; 'use strict';
var ValidationError = require('../..').ValidationError; const ValidationError = require('../..').ValidationError;
var contextTestHelpers = require('../helpers/context-test-helpers'); const contextTestHelpers = require('../helpers/context-test-helpers');
var ContextRecorder = contextTestHelpers.ContextRecorder; const ContextRecorder = contextTestHelpers.ContextRecorder;
var aCtxForModel = contextTestHelpers.aCtxForModel; const aCtxForModel = contextTestHelpers.aCtxForModel;
var uid = require('../helpers/uid-generator'); const uid = require('../helpers/uid-generator');
var HookMonitor = require('../helpers/hook-monitor'); const HookMonitor = require('../helpers/hook-monitor');
module.exports = function(dataSource, should, connectorCapabilities) { module.exports = function(dataSource, should, connectorCapabilities) {
describe('EmbedsMany - create', function() { describe('EmbedsMany - create', function() {
var ctxRecorder, hookMonitor, expectedError; let ctxRecorder, hookMonitor, expectedError;
beforeEach(function setupHelpers() { beforeEach(function setupHelpers() {
ctxRecorder = new ContextRecorder('hook not called'); ctxRecorder = new ContextRecorder('hook not called');
@ -24,8 +24,8 @@ module.exports = function(dataSource, should, connectorCapabilities) {
expectedError = new Error('test error'); expectedError = new Error('test error');
}); });
var Owner, Embedded, ownerInstance; let Owner, Embedded, ownerInstance;
var migrated = false; let migrated = false;
beforeEach(function setupDatabase() { beforeEach(function setupDatabase() {
Embedded = dataSource.createModel('Embedded', { Embedded = dataSource.createModel('Embedded', {
@ -57,7 +57,7 @@ module.exports = function(dataSource, should, connectorCapabilities) {
}); });
function callCreate() { function callCreate() {
var item = new Embedded({name: 'created'}); const item = new Embedded({name: 'created'});
return ownerInstance.embeddedList.create(item); return ownerInstance.embeddedList.create(item);
} }

View File

@ -5,26 +5,26 @@
'use strict'; 'use strict';
var ValidationError = require('../..').ValidationError; const ValidationError = require('../..').ValidationError;
var contextTestHelpers = require('../helpers/context-test-helpers'); const contextTestHelpers = require('../helpers/context-test-helpers');
var ContextRecorder = contextTestHelpers.ContextRecorder; const ContextRecorder = contextTestHelpers.ContextRecorder;
var aCtxForModel = contextTestHelpers.aCtxForModel; const aCtxForModel = contextTestHelpers.aCtxForModel;
var uid = require('../helpers/uid-generator'); const uid = require('../helpers/uid-generator');
var HookMonitor = require('../helpers/hook-monitor'); const HookMonitor = require('../helpers/hook-monitor');
module.exports = function(dataSource, should, connectorCapabilities) { module.exports = function(dataSource, should, connectorCapabilities) {
describe('EmbedsMany - destroy', function() { describe('EmbedsMany - destroy', function() {
var ctxRecorder, hookMonitor, expectedError; let ctxRecorder, hookMonitor, expectedError;
beforeEach(function sharedSetup() { beforeEach(function sharedSetup() {
ctxRecorder = new ContextRecorder('hook not called'); ctxRecorder = new ContextRecorder('hook not called');
hookMonitor = new HookMonitor({includeModelName: true}); hookMonitor = new HookMonitor({includeModelName: true});
expectedError = new Error('test error'); expectedError = new Error('test error');
}); });
var Owner, Embedded; let Owner, Embedded;
var migrated = false; let migrated = false;
beforeEach(function setupDatabase() { beforeEach(function setupDatabase() {
Embedded = dataSource.createModel('Embedded', { Embedded = dataSource.createModel('Embedded', {
// Set id.generated to false to honor client side values // 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() { beforeEach(function setupData() {
return Owner.create({}) return Owner.create({})
.then(function(inst) { .then(function(inst) {
ownerInstance = inst; ownerInstance = inst;
}) })
.then(function() { .then(function() {
var item = new Embedded({name: 'created'}); const item = new Embedded({name: 'created'});
return ownerInstance.embeddedList.create(item).then(function(it) { return ownerInstance.embeddedList.create(item).then(function(it) {
existingItem = it; existingItem = it;
}); });

View File

@ -5,26 +5,26 @@
'use strict'; 'use strict';
var ValidationError = require('../..').ValidationError; const ValidationError = require('../..').ValidationError;
var contextTestHelpers = require('../helpers/context-test-helpers'); const contextTestHelpers = require('../helpers/context-test-helpers');
var ContextRecorder = contextTestHelpers.ContextRecorder; const ContextRecorder = contextTestHelpers.ContextRecorder;
var aCtxForModel = contextTestHelpers.aCtxForModel; const aCtxForModel = contextTestHelpers.aCtxForModel;
var uid = require('../helpers/uid-generator'); const uid = require('../helpers/uid-generator');
var HookMonitor = require('../helpers/hook-monitor'); const HookMonitor = require('../helpers/hook-monitor');
module.exports = function(dataSource, should, connectorCapabilities) { module.exports = function(dataSource, should, connectorCapabilities) {
describe('EmbedsMany - update', function() { describe('EmbedsMany - update', function() {
var ctxRecorder, hookMonitor, expectedError; let ctxRecorder, hookMonitor, expectedError;
beforeEach(function setupHelpers() { beforeEach(function setupHelpers() {
ctxRecorder = new ContextRecorder('hook not called'); ctxRecorder = new ContextRecorder('hook not called');
hookMonitor = new HookMonitor({includeModelName: true}); hookMonitor = new HookMonitor({includeModelName: true});
expectedError = new Error('test error'); expectedError = new Error('test error');
}); });
var Owner, Embedded; let Owner, Embedded;
var migrated = false; let migrated = false;
beforeEach(function setupDatabase() { beforeEach(function setupDatabase() {
Embedded = dataSource.createModel('Embedded', { Embedded = dataSource.createModel('Embedded', {
// Set id.generated to false to honor client side values // 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() { beforeEach(function setupData() {
return Owner.create({}) return Owner.create({})
.then(function(inst) { .then(function(inst) {
ownerInstance = inst; ownerInstance = inst;
}) })
.then(function() { .then(function() {
var item = new Embedded({name: 'created'}); const item = new Embedded({name: 'created'});
return ownerInstance.embeddedList.create(item).then(function(it) { return ownerInstance.embeddedList.create(item).then(function(it) {
existingItem = it; existingItem = it;
}); });

View File

@ -5,18 +5,18 @@
'use strict'; 'use strict';
var ValidationError = require('../..').ValidationError; const ValidationError = require('../..').ValidationError;
var contextTestHelpers = require('../helpers/context-test-helpers'); const contextTestHelpers = require('../helpers/context-test-helpers');
var ContextRecorder = contextTestHelpers.ContextRecorder; const ContextRecorder = contextTestHelpers.ContextRecorder;
var aCtxForModel = contextTestHelpers.aCtxForModel; const aCtxForModel = contextTestHelpers.aCtxForModel;
var uid = require('../helpers/uid-generator'); const uid = require('../helpers/uid-generator');
var HookMonitor = require('../helpers/hook-monitor'); const HookMonitor = require('../helpers/hook-monitor');
module.exports = function(dataSource, should, connectorCapabilities) { module.exports = function(dataSource, should, connectorCapabilities) {
describe('EmbedsOne - create', function() { describe('EmbedsOne - create', function() {
var ctxRecorder, hookMonitor, expectedError; let ctxRecorder, hookMonitor, expectedError;
beforeEach(function setupHelpers() { beforeEach(function setupHelpers() {
ctxRecorder = new ContextRecorder('hook not called'); ctxRecorder = new ContextRecorder('hook not called');
@ -24,8 +24,8 @@ module.exports = function(dataSource, should, connectorCapabilities) {
expectedError = new Error('test error'); expectedError = new Error('test error');
}); });
var Owner, Embedded, ownerInstance; let Owner, Embedded, ownerInstance;
var migrated = false; let migrated = false;
beforeEach(function setupDatabase() { beforeEach(function setupDatabase() {
Embedded = dataSource.createModel('Embedded', { Embedded = dataSource.createModel('Embedded', {
@ -57,7 +57,7 @@ module.exports = function(dataSource, should, connectorCapabilities) {
}); });
function callCreate() { function callCreate() {
var item = new Embedded({name: 'created'}); const item = new Embedded({name: 'created'});
return ownerInstance.embeddedItem.create(item); return ownerInstance.embeddedItem.create(item);
} }

View File

@ -5,26 +5,26 @@
'use strict'; 'use strict';
var ValidationError = require('../..').ValidationError; const ValidationError = require('../..').ValidationError;
var contextTestHelpers = require('../helpers/context-test-helpers'); const contextTestHelpers = require('../helpers/context-test-helpers');
var ContextRecorder = contextTestHelpers.ContextRecorder; const ContextRecorder = contextTestHelpers.ContextRecorder;
var aCtxForModel = contextTestHelpers.aCtxForModel; const aCtxForModel = contextTestHelpers.aCtxForModel;
var uid = require('../helpers/uid-generator'); const uid = require('../helpers/uid-generator');
var HookMonitor = require('../helpers/hook-monitor'); const HookMonitor = require('../helpers/hook-monitor');
module.exports = function(dataSource, should, connectorCapabilities) { module.exports = function(dataSource, should, connectorCapabilities) {
describe('EmbedsOne - destroy', function() { describe('EmbedsOne - destroy', function() {
var ctxRecorder, hookMonitor, expectedError; let ctxRecorder, hookMonitor, expectedError;
beforeEach(function sharedSetup() { beforeEach(function sharedSetup() {
ctxRecorder = new ContextRecorder('hook not called'); ctxRecorder = new ContextRecorder('hook not called');
hookMonitor = new HookMonitor({includeModelName: true}); hookMonitor = new HookMonitor({includeModelName: true});
expectedError = new Error('test error'); expectedError = new Error('test error');
}); });
var Owner, Embedded; let Owner, Embedded;
var migrated = false; let migrated = false;
beforeEach(function setupDatabase() { beforeEach(function setupDatabase() {
Embedded = dataSource.createModel('Embedded', { Embedded = dataSource.createModel('Embedded', {
// Set id.generated to false to honor client side values // 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() { beforeEach(function setupData() {
return Owner.create({}) return Owner.create({})
.then(function(inst) { .then(function(inst) {
ownerInstance = inst; ownerInstance = inst;
}) })
.then(function() { .then(function() {
var item = new Embedded({name: 'created'}); const item = new Embedded({name: 'created'});
return ownerInstance.embeddedItem.create(item).then(function(it) { return ownerInstance.embeddedItem.create(item).then(function(it) {
existingItem = it; existingItem = it;
}); });

View File

@ -5,26 +5,26 @@
'use strict'; 'use strict';
var ValidationError = require('../..').ValidationError; const ValidationError = require('../..').ValidationError;
var contextTestHelpers = require('../helpers/context-test-helpers'); const contextTestHelpers = require('../helpers/context-test-helpers');
var ContextRecorder = contextTestHelpers.ContextRecorder; const ContextRecorder = contextTestHelpers.ContextRecorder;
var aCtxForModel = contextTestHelpers.aCtxForModel; const aCtxForModel = contextTestHelpers.aCtxForModel;
var uid = require('../helpers/uid-generator'); const uid = require('../helpers/uid-generator');
var HookMonitor = require('../helpers/hook-monitor'); const HookMonitor = require('../helpers/hook-monitor');
module.exports = function(dataSource, should, connectorCapabilities) { module.exports = function(dataSource, should, connectorCapabilities) {
describe('EmbedsOne - update', function() { describe('EmbedsOne - update', function() {
var ctxRecorder, hookMonitor, expectedError; let ctxRecorder, hookMonitor, expectedError;
beforeEach(function setupHelpers() { beforeEach(function setupHelpers() {
ctxRecorder = new ContextRecorder('hook not called'); ctxRecorder = new ContextRecorder('hook not called');
hookMonitor = new HookMonitor({includeModelName: true}); hookMonitor = new HookMonitor({includeModelName: true});
expectedError = new Error('test error'); expectedError = new Error('test error');
}); });
var Owner, Embedded; let Owner, Embedded;
var migrated = false; let migrated = false;
beforeEach(function setupDatabase() { beforeEach(function setupDatabase() {
Embedded = dataSource.createModel('Embedded', { Embedded = dataSource.createModel('Embedded', {
// Set id.generated to false to honor client side values // 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() { beforeEach(function setupData() {
return Owner.create({}) return Owner.create({})
.then(function(inst) { .then(function(inst) {
ownerInstance = inst; ownerInstance = inst;
}) })
.then(function() { .then(function() {
var item = new Embedded({name: 'created'}); const item = new Embedded({name: 'created'});
return ownerInstance.embeddedItem.create(item).then(function(it) { return ownerInstance.embeddedItem.create(item).then(function(it) {
existingItem = it; existingItem = it;
}); });

View File

@ -1,18 +1,18 @@
'use strict'; 'use strict';
var debug = require('debug')('test'); const debug = require('debug')('test');
var fs = require('fs'); const fs = require('fs');
var path = require('path'); const path = require('path');
module.exports = function(dataSource, should, connectorCapabilities) { module.exports = function(dataSource, should, connectorCapabilities) {
var operations = fs.readdirSync(__dirname); let operations = fs.readdirSync(__dirname);
operations = operations.filter(function(it) { operations = operations.filter(function(it) {
return it !== path.basename(__filename) && return it !== path.basename(__filename) &&
!!require.extensions[path.extname(it).toLowerCase()]; !!require.extensions[path.extname(it).toLowerCase()];
}); });
for (var ix in operations) { for (const ix in operations) {
var name = operations[ix]; const name = operations[ix];
var fullPath = require.resolve('./' + name); const fullPath = require.resolve('./' + name);
debug('Loading test suite %s (%s)', name, fullPath); debug('Loading test suite %s (%s)', name, fullPath);
require(fullPath).apply(this, arguments); require(fullPath).apply(this, arguments);
} }

View File

@ -7,16 +7,16 @@
'use strict'; 'use strict';
/* global getSchema:false */ /* global getSchema:false */
var async = require('async'); const async = require('async');
var should = require('./init.js'); const should = require('./init.js');
var db, User, options, ModelWithForceId, whereCount = 0; let db, User, options, ModelWithForceId, whereCount = 0;
var j = require('../'); const j = require('../');
var ValidationError = j.ValidationError; const ValidationError = j.ValidationError;
var INITIAL_NAME = 'Bert'; const INITIAL_NAME = 'Bert';
var NEW_NAME = 'Ernie'; const NEW_NAME = 'Ernie';
var INVALID_DATA = {name: null}; const INVALID_DATA = {name: null};
var VALID_DATA = {name: INITIAL_NAME}; const VALID_DATA = {name: INITIAL_NAME};
describe('optional-validation', function() { describe('optional-validation', function() {
before(function(done) { before(function(done) {
@ -103,7 +103,7 @@ describe('optional-validation', function() {
function callUpdateOrCreateWithExistingUserId(name, options, cb) { function callUpdateOrCreateWithExistingUserId(name, options, cb) {
User.create({'name': 'Groover'}, function(err, user) { User.create({'name': 'Groover'}, function(err, user) {
if (err) return cb(err); if (err) return cb(err);
var data = {name: name}; const data = {name: name};
data.id = user.id; data.id = user.id;
User.updateOrCreate(data, options, cb); User.updateOrCreate(data, options, cb);
}); });

View File

@ -4,35 +4,35 @@
// License text available at https://opensource.org/licenses/MIT // License text available at https://opensource.org/licenses/MIT
'use strict'; 'use strict';
var ValidationError = require('../').ValidationError; const ValidationError = require('../').ValidationError;
var async = require('async'); const async = require('async');
var contextTestHelpers = require('./helpers/context-test-helpers'); const contextTestHelpers = require('./helpers/context-test-helpers');
var ContextRecorder = contextTestHelpers.ContextRecorder; const ContextRecorder = contextTestHelpers.ContextRecorder;
var deepCloneToObject = contextTestHelpers.deepCloneToObject; const deepCloneToObject = contextTestHelpers.deepCloneToObject;
var aCtxForModel = contextTestHelpers.aCtxForModel; const aCtxForModel = contextTestHelpers.aCtxForModel;
var GeoPoint = require('../lib/geo.js').GeoPoint; const GeoPoint = require('../lib/geo.js').GeoPoint;
var uid = require('./helpers/uid-generator'); const uid = require('./helpers/uid-generator');
var getLastGeneratedUid = uid.last; const getLastGeneratedUid = uid.last;
var HookMonitor = require('./helpers/hook-monitor'); const HookMonitor = require('./helpers/hook-monitor');
var isNewInstanceFlag; let isNewInstanceFlag;
module.exports = function(dataSource, should, connectorCapabilities) { module.exports = function(dataSource, should, connectorCapabilities) {
isNewInstanceFlag = connectorCapabilities.replaceOrCreateReportsNewInstance; isNewInstanceFlag = connectorCapabilities.replaceOrCreateReportsNewInstance;
if (!connectorCapabilities) connectorCapabilities = {}; if (!connectorCapabilities) connectorCapabilities = {};
if (isNewInstanceFlag === undefined) { 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'; ' replaceOrCreateReportsNewInstance';
console.warn(warn); console.warn(warn);
} }
describe('Persistence hooks', function() { describe('Persistence hooks', function() {
var ctxRecorder, hookMonitor, expectedError; let ctxRecorder, hookMonitor, expectedError;
var TestModel, existingInstance, GeoModel; let TestModel, existingInstance, GeoModel;
var migrated = false; let migrated = false;
var undefinedValue = undefined; let undefinedValue = undefined;
beforeEach(function setupDatabase(done) { beforeEach(function setupDatabase(done) {
ctxRecorder = new ContextRecorder('hook not called'); ctxRecorder = new ContextRecorder('hook not called');
@ -82,8 +82,8 @@ module.exports = function(dataSource, should, connectorCapabilities) {
TestModel.create({name: 'second'}, function(err) { TestModel.create({name: 'second'}, function(err) {
if (err) return done(err); if (err) return done(err);
var location1 = new GeoPoint({lat: 10.2, lng: 6.7}); const location1 = new GeoPoint({lat: 10.2, lng: 6.7});
var location2 = new GeoPoint({lat: 10.3, lng: 6.8}); const location2 = new GeoPoint({lat: 10.3, lng: 6.8});
GeoModel.create([ GeoModel.create([
{name: 'Rome', location: location1}, {name: 'Rome', location: location1},
{name: 'Tokyo', location: location2}, {name: 'Tokyo', location: location2},
@ -143,8 +143,7 @@ module.exports = function(dataSource, should, connectorCapabilities) {
it('triggers the loaded hook multiple times when multiple instances exist when near filter is used', it('triggers the loaded hook multiple times when multiple instances exist when near filter is used',
function(done) { function(done) {
var hookMonitorGeoModel; const hookMonitorGeoModel = new HookMonitor({includeModelName: false});
hookMonitorGeoModel = new HookMonitor({includeModelName: false});
function monitorHookExecutionGeoModel(hookNames) { function monitorHookExecutionGeoModel(hookNames) {
hookMonitorGeoModel.install(GeoModel, hookNames); hookMonitorGeoModel.install(GeoModel, hookNames);
@ -152,7 +151,7 @@ module.exports = function(dataSource, should, connectorCapabilities) {
monitorHookExecutionGeoModel(); monitorHookExecutionGeoModel();
var query = { const query = {
where: {location: {near: '10,5'}}, where: {location: {near: '10,5'}},
}; };
GeoModel.find(query, function(err, list) { GeoModel.find(query, function(err, list) {
@ -170,7 +169,7 @@ module.exports = function(dataSource, should, connectorCapabilities) {
next(); next();
}); });
var query = { const query = {
where: {location: {near: '10,5'}}, where: {location: {near: '10,5'}},
}; };
@ -191,7 +190,7 @@ module.exports = function(dataSource, should, connectorCapabilities) {
next(); next();
}); });
var query = { const query = {
where: {location: {near: '10,5'}}, where: {location: {near: '10,5'}},
}; };
@ -1325,7 +1324,7 @@ module.exports = function(dataSource, should, connectorCapabilities) {
// The rationale behind passing { persisted: true } is to bypass the check // The rationale behind passing { persisted: true } is to bypass the check
// made by DAO to determine whether the instance should be saved via // made by DAO to determine whether the instance should be saved via
// PersistedModel.create and force it to call connector.save() // PersistedModel.create and force it to call connector.save()
var instance = new TestModel( const instance = new TestModel(
{id: 'new-id', name: 'created'}, {id: 'new-id', name: 'created'},
{persisted: true} {persisted: true}
); );
@ -1391,7 +1390,7 @@ module.exports = function(dataSource, should, connectorCapabilities) {
it('triggers `before save` hook', function(done) { it('triggers `before save` hook', function(done) {
TestModel.observe('before save', ctxRecorder.recordAndNext()); TestModel.observe('before save', ctxRecorder.recordAndNext());
var currentInstance = deepCloneToObject(existingInstance); const currentInstance = deepCloneToObject(existingInstance);
existingInstance.updateAttributes({name: 'changed'}, function(err) { existingInstance.updateAttributes({name: 'changed'}, function(err) {
if (err) return done(err); if (err) return done(err);
@ -1494,13 +1493,13 @@ module.exports = function(dataSource, should, connectorCapabilities) {
}); });
it('applies updates from `persist` hook - for nested model instance', function(done) { 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}, id: {type: String, id: true, default: 1},
city: {type: String, required: true}, city: {type: String, required: true},
country: {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}, id: {type: String, id: true, default: uid.next},
name: {type: String, required: true}, name: {type: String, required: true},
address: {type: Address, required: false}, address: {type: Address, required: false},
@ -1512,7 +1511,7 @@ module.exports = function(dataSource, should, connectorCapabilities) {
User.create({name: 'Joe'}, function(err, instance) { User.create({name: 'Joe'}, function(err, instance) {
if (err) return done(err); if (err) return done(err);
var existingUser = instance; const existingUser = instance;
User.observe('persist', ctxRecorder.recordAndNext(function(ctx) { User.observe('persist', ctxRecorder.recordAndNext(function(ctx) {
should.exist(ctx.data.address); should.exist(ctx.data.address);
@ -1762,13 +1761,13 @@ module.exports = function(dataSource, should, connectorCapabilities) {
}); });
it('applies updates from `persist` hook - for nested model instance', function(done) { 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}, id: {type: String, id: true, default: 1},
city: {type: String, required: true}, city: {type: String, required: true},
country: {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}, id: {type: String, id: true, default: uid.next},
name: {type: String, required: true}, name: {type: String, required: true},
address: {type: Address, required: false}, address: {type: Address, required: false},
@ -1780,7 +1779,7 @@ module.exports = function(dataSource, should, connectorCapabilities) {
User.create({name: 'Joe'}, function(err, instance) { User.create({name: 'Joe'}, function(err, instance) {
if (err) return done(err); if (err) return done(err);
var existingUser = instance; const existingUser = instance;
User.observe('persist', ctxRecorder.recordAndNext(function(ctx) { User.observe('persist', ctxRecorder.recordAndNext(function(ctx) {
should.exist(ctx.data.address); should.exist(ctx.data.address);
@ -2215,7 +2214,7 @@ module.exports = function(dataSource, should, connectorCapabilities) {
function(err, instance) { function(err, instance) {
if (err) return done(err); if (err) return done(err);
var expectedContext = aCtxForModel(TestModel, { const expectedContext = aCtxForModel(TestModel, {
where: {id: existingInstance.id}, where: {id: existingInstance.id},
data: { data: {
id: existingInstance.id, id: existingInstance.id,
@ -2504,7 +2503,7 @@ module.exports = function(dataSource, should, connectorCapabilities) {
if (err) if (err)
return done(err); return done(err);
var expectedContext = aCtxForModel(TestModel, { const expectedContext = aCtxForModel(TestModel, {
instance: instance, instance: instance,
}); });
@ -2522,7 +2521,7 @@ module.exports = function(dataSource, should, connectorCapabilities) {
function(err, instance) { function(err, instance) {
if (err) return done(err); if (err) return done(err);
var expectedContext = aCtxForModel(TestModel, { const expectedContext = aCtxForModel(TestModel, {
instance: { instance: {
id: existingInstance.id, id: existingInstance.id,
name: 'replaced name', name: 'replaced name',
@ -2548,7 +2547,7 @@ module.exports = function(dataSource, should, connectorCapabilities) {
function(err, instance) { function(err, instance) {
if (err) return done(err); if (err) return done(err);
var expectedContext = aCtxForModel(TestModel, { const expectedContext = aCtxForModel(TestModel, {
instance: { instance: {
id: 'new-id', id: 'new-id',
name: 'a name', name: 'a name',
@ -2603,7 +2602,7 @@ module.exports = function(dataSource, should, connectorCapabilities) {
function(err, instance) { function(err, instance) {
if (err) return done(err); if (err) return done(err);
var expectedContext = aCtxForModel(TestModel, { const expectedContext = aCtxForModel(TestModel, {
currentInstance: { currentInstance: {
id: 'new-id', id: 'new-id',
name: 'a name', name: 'a name',
@ -2637,7 +2636,7 @@ module.exports = function(dataSource, should, connectorCapabilities) {
function(err, instance) { function(err, instance) {
if (err) return done(err); if (err) return done(err);
var expected = { const expected = {
where: {id: existingInstance.id}, where: {id: existingInstance.id},
data: { data: {
id: existingInstance.id, id: existingInstance.id,
@ -2650,7 +2649,7 @@ module.exports = function(dataSource, should, connectorCapabilities) {
}, },
}; };
var expectedContext = aCtxForModel(TestModel, expected); const expectedContext = aCtxForModel(TestModel, expected);
if (!dataSource.connector.replaceOrCreate) { if (!dataSource.connector.replaceOrCreate) {
expectedContext.isNewInstance = false; expectedContext.isNewInstance = false;
@ -2718,7 +2717,7 @@ module.exports = function(dataSource, should, connectorCapabilities) {
function(err, instance) { function(err, instance) {
if (err) return done(err); if (err) return done(err);
var expected = { const expected = {
data: { data: {
id: 'new-id', id: 'new-id',
name: 'a name', name: 'a name',
@ -2743,7 +2742,7 @@ module.exports = function(dataSource, should, connectorCapabilities) {
function(err, instance) { function(err, instance) {
if (err) return done(err); if (err) return done(err);
var expected = { const expected = {
data: { data: {
id: existingInstance.id, id: existingInstance.id,
name: 'replaced name', name: 'replaced name',
@ -2779,7 +2778,7 @@ module.exports = function(dataSource, should, connectorCapabilities) {
function(err, instance) { function(err, instance) {
if (err) return done(err); if (err) return done(err);
var expected = { const expected = {
instance: { instance: {
id: existingInstance.id, id: existingInstance.id,
name: 'replaced name', name: 'replaced name',
@ -2805,7 +2804,7 @@ module.exports = function(dataSource, should, connectorCapabilities) {
function(err, instance) { function(err, instance) {
if (err) return done(err); if (err) return done(err);
var expected = { const expected = {
instance: { instance: {
id: instance.id, id: instance.id,
name: 'a name', name: 'a name',
@ -3498,7 +3497,7 @@ module.exports = function(dataSource, should, connectorCapabilities) {
{id: existingInstance.id, name: 'updated name'}, {id: existingInstance.id, name: 'updated name'},
function(err, instance) { function(err, instance) {
if (err) return done(err); if (err) return done(err);
var expectedContext = aCtxForModel(TestModel, { const expectedContext = aCtxForModel(TestModel, {
where: {id: existingInstance.id}, where: {id: existingInstance.id},
data: { data: {
id: existingInstance.id, id: existingInstance.id,
@ -3525,7 +3524,7 @@ module.exports = function(dataSource, should, connectorCapabilities) {
{id: 'new-id', name: 'a name'}, {id: 'new-id', name: 'a name'},
function(err, instance) { function(err, instance) {
if (err) return done(err); if (err) return done(err);
var expectedContext = aCtxForModel(TestModel, {}); const expectedContext = aCtxForModel(TestModel, {});
if (dataSource.connector.upsertWithWhere) { if (dataSource.connector.upsertWithWhere) {
expectedContext.data = {id: 'new-id', name: 'a name'}; expectedContext.data = {id: 'new-id', name: 'a name'};
@ -3607,7 +3606,7 @@ module.exports = function(dataSource, should, connectorCapabilities) {
function(err, instance) { function(err, instance) {
if (err) return done(err); if (err) return done(err);
var expectedContext = aCtxForModel(TestModel, { const expectedContext = aCtxForModel(TestModel, {
data: {id: 'new-id', name: 'a name'}, data: {id: 'new-id', name: 'a name'},
currentInstance: { currentInstance: {
id: 'new-id', id: 'new-id',
@ -3633,7 +3632,7 @@ module.exports = function(dataSource, should, connectorCapabilities) {
{id: existingInstance.id, name: 'updated name'}, {id: existingInstance.id, name: 'updated name'},
function(err, instance) { function(err, instance) {
if (err) return done(err); if (err) return done(err);
var expectedContext = aCtxForModel(TestModel, { const expectedContext = aCtxForModel(TestModel, {
where: {id: existingInstance.id}, where: {id: existingInstance.id},
data: { data: {
id: existingInstance.id, id: existingInstance.id,
@ -3675,7 +3674,7 @@ module.exports = function(dataSource, should, connectorCapabilities) {
{id: existingInstance.id, name: 'updated name'}, {id: existingInstance.id, name: 'updated name'},
function(err, instance) { function(err, instance) {
if (err) return done(err); if (err) return done(err);
var expectedContext = aCtxForModel(TestModel, { const expectedContext = aCtxForModel(TestModel, {
data: { data: {
id: existingInstance.id, id: existingInstance.id,
name: 'updated name', name: 'updated name',

File diff suppressed because it is too large Load Diff

View File

@ -7,15 +7,17 @@
'use strict'; 'use strict';
/* global getSchema:false */ /* global getSchema:false */
var should = require('./init.js'); const should = require('./init.js');
var db = getSchema(), slave = getSchema(), Model, SlaveModel; const db = getSchema();
const slave = getSchema();
let Model, SlaveModel;
describe('dataSource', function() { describe('dataSource', function() {
it('should define Model', function() { it('should define Model', function() {
Model = db.define('Model'); Model = db.define('Model');
Model.dataSource.should.eql(db); Model.dataSource.should.eql(db);
var m = new Model; const m = new Model;
m.getDataSource().should.eql(db); m.getDataSource().should.eql(db);
}); });
@ -23,7 +25,7 @@ describe('dataSource', function() {
SlaveModel = slave.copyModel(Model); SlaveModel = slave.copyModel(Model);
SlaveModel.dataSource.should.equal(slave); SlaveModel.dataSource.should.equal(slave);
slave.should.not.equal(db); slave.should.not.equal(db);
var sm = new SlaveModel; const sm = new SlaveModel;
sm.should.be.instanceOf(Model); sm.should.be.instanceOf(Model);
sm.getDataSource().should.not.equal(db); sm.getDataSource().should.not.equal(db);
sm.getDataSource().should.equal(slave); sm.getDataSource().should.equal(slave);
@ -34,10 +36,10 @@ describe('dataSource', function() {
}); });
it('should create transaction', function(done) { it('should create transaction', function(done) {
var tr = db.transaction(); const tr = db.transaction();
tr.connected.should.be.false; tr.connected.should.be.false;
tr.connecting.should.be.false; tr.connecting.should.be.false;
var called = false; let called = false;
tr.models.Model.create(Array(3), function() { tr.models.Model.create(Array(3), function() {
called = true; called = true;
}); });

View File

@ -7,9 +7,9 @@
'use strict'; 'use strict';
/* global getSchema:false */ /* global getSchema:false */
var should = require('./init.js'); const should = require('./init.js');
var db, Railway, Station; let db, Railway, Station;
describe('scope', function() { describe('scope', function() {
before(function() { before(function() {
@ -161,7 +161,7 @@ describe('scope - order', function() {
}); });
describe('scope - filtered count, updateAll and destroyAll', function() { describe('scope - filtered count, updateAll and destroyAll', function() {
var stationA; let stationA;
before(function() { before(function() {
db = getSchema(); db = getSchema();
@ -284,13 +284,13 @@ describe('scope - filtered count, updateAll and destroyAll', function() {
verify(); verify();
}); });
var verify = function() { function verify() {
Station.flagged.count(function(err, count) { Station.flagged.count(function(err, count) {
if (err) return done(err); if (err) return done(err);
count.should.equal(2); count.should.equal(2);
done(); done();
}); });
}; }
}); });
it('should allow filtered updateAll', function(done) { it('should allow filtered updateAll', function(done) {
@ -300,13 +300,13 @@ describe('scope - filtered count, updateAll and destroyAll', function() {
verify(); verify();
}); });
var verify = function() { function verify() {
Station.flagged.count(function(err, count) { Station.flagged.count(function(err, count) {
if (err) return done(err); if (err) return done(err);
count.should.equal(2); count.should.equal(2);
done(); done();
}); });
}; }
}); });
it('should allow filtered destroyAll', function(done) { it('should allow filtered destroyAll', function(done) {
@ -315,7 +315,7 @@ describe('scope - filtered count, updateAll and destroyAll', function() {
verify(); verify();
}); });
var verify = function() { function verify() {
Station.ordered.count(function(err, count) { Station.ordered.count(function(err, count) {
if (err) return done(err); if (err) return done(err);
count.should.equal(2); count.should.equal(2);
@ -325,12 +325,12 @@ describe('scope - filtered count, updateAll and destroyAll', function() {
done(); done();
}); });
}); });
}; }
}); });
}); });
describe('scope - dynamic target class', function() { describe('scope - dynamic target class', function() {
var Collection, Image, Video; let Collection, Image, Video;
before(function() { before(function() {
db = getSchema(); db = getSchema();
@ -414,7 +414,7 @@ describe('scope - dynamic target class', function() {
}); });
describe('scope - dynamic function', function() { describe('scope - dynamic function', function() {
var Item, seed = 0; let Item, seed = 0;
before(function() { before(function() {
db = getSchema(); db = getSchema();

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