Run `eslint --fix` with config from master

This commit is contained in:
Miroslav Bajtoš 2016-04-14 16:41:19 +02:00
parent fd1afdf6e6
commit a5187765f6
64 changed files with 4954 additions and 4955 deletions

View File

@ -17,23 +17,23 @@ var application = {
name: 'MyApp1', name: 'MyApp1',
description: 'My first app', description: 'My first app',
pushSettings: [ pushSettings: [
{ "platform": "apns", { 'platform': 'apns',
"apns": { 'apns': {
"pushOptions": { 'pushOptions': {
"gateway": "gateway.sandbox.push.apple.com", 'gateway': 'gateway.sandbox.push.apple.com',
"cert": "credentials/apns_cert_dev.pem", 'cert': 'credentials/apns_cert_dev.pem',
"key": "credentials/apns_key_dev.pem" 'key': 'credentials/apns_key_dev.pem',
}, },
"feedbackOptions": { 'feedbackOptions': {
"gateway": "feedback.sandbox.push.apple.com", 'gateway': 'feedback.sandbox.push.apple.com',
"cert": "credentials/apns_cert_dev.pem", 'cert': 'credentials/apns_cert_dev.pem',
"key": "credentials/apns_key_dev.pem", 'key': 'credentials/apns_key_dev.pem',
"batchFeedback": true, 'batchFeedback': true,
"interval": 300 'interval': 300,
} },
}} }},
]} ] };
console.log(new Application(application).toObject()); console.log(new Application(application).toObject());
@ -55,14 +55,14 @@ var user = {
city: 'San Jose', city: 'San Jose',
state: 'CA', state: 'CA',
zipcode: '95131', zipcode: '95131',
country: 'US' country: 'US',
}, },
friends: ['John', 'Mary'], friends: ['John', 'Mary'],
emails: [ emails: [
{ label: 'work', id: 'x@sample.com' }, { label: 'work', id: 'x@sample.com' },
{label: 'home', id: 'x@home.com'} { label: 'home', id: 'x@home.com' },
], ],
tags: [] tags: [],
}; };
// Introspect the JSON document to generate a schema // Introspect the JSON document to generate a schema

View File

@ -13,7 +13,7 @@ var Post = modelBuilder.define('Post', {
return new Date(); return new Date();
} }, } },
timestamp: { type: Number, default: Date.now }, timestamp: { type: Number, default: Date.now },
published: { type: Boolean, default: false, index: true } published: { type: Boolean, default: false, index: true },
}); });
// simpler way to describe model // simpler way to describe model
@ -22,7 +22,7 @@ var User = modelBuilder.define('User', {
bio: ModelBuilder.Text, bio: ModelBuilder.Text,
approved: Boolean, approved: Boolean,
joinedAt: Date, joinedAt: Date,
age: Number age: Number,
}); });
var Group = modelBuilder.define('Group', { group: String }); var Group = modelBuilder.define('Group', { group: String });

View File

@ -15,7 +15,7 @@ var Post = ds.define('Post', {
return new Date; return new Date;
} }, } },
timestamp: { type: Number, default: Date.now }, timestamp: { type: Number, default: Date.now },
published: { type: Boolean, default: false, index: true } published: { type: Boolean, default: false, index: true },
}); });
// simplier way to describe model // simplier way to describe model
@ -24,7 +24,7 @@ var User = ds.define('User', {
bio: DataSource.Text, bio: DataSource.Text,
approved: Boolean, approved: Boolean,
joinedAt: Date, joinedAt: Date,
age: Number age: Number,
}); });
var Group = ds.define('Group', { name: String }); var Group = ds.define('Group', { name: String });
@ -106,7 +106,7 @@ Article.create(function (e, article) {
var modelBuilder = new ModelBuilder(); var modelBuilder = new ModelBuilder();
Color = modelBuilder.define('Color', { Color = modelBuilder.define('Color', {
name: String name: String,
}); });
// attach // attach

View File

@ -23,7 +23,7 @@ setup(function () {
}); });
Passport.find({ Passport.find({
include: {owner: {posts: 'author'}} include: { owner: { posts: 'author' }},
}, function(err, passports) { }, function(err, passports) {
console.log('passports.owner.posts.author', passports); console.log('passports.owner.posts.author', passports);
}); });
@ -41,13 +41,13 @@ function setup(done) {
Building = db.define('Building'); Building = db.define('Building');
User = db.define('User', { User = db.define('User', {
name: String, name: String,
age: Number age: Number,
}); });
Passport = db.define('Passport', { Passport = db.define('Passport', {
number: String number: String,
}); });
Post = db.define('Post', { Post = db.define('Post', {
title: String title: String,
}); });
Passport.belongsTo('owner', { model: User }); Passport.belongsTo('owner', { model: User });
@ -68,7 +68,7 @@ function setup(done) {
{ name: 'User B', age: 22 }, { name: 'User B', age: 22 },
{ name: 'User C', age: 23 }, { name: 'User C', age: 23 },
{ name: 'User D', age: 24 }, { name: 'User D', age: 24 },
{name: 'User E', age: 25} { name: 'User E', age: 25 },
], ],
function(items) { function(items) {
createdUsers = items; createdUsers = items;
@ -83,7 +83,7 @@ function setup(done) {
[ [
{ number: '1', ownerId: createdUsers[0].id }, { number: '1', ownerId: createdUsers[0].id },
{ number: '2', ownerId: createdUsers[1].id }, { number: '2', ownerId: createdUsers[1].id },
{number: '3'} { number: '3' },
], ],
function(items) { function(items) {
createdPassports = items; createdPassports = items;
@ -100,7 +100,7 @@ function setup(done) {
{ title: 'Post B', userId: createdUsers[0].id }, { title: 'Post B', userId: createdUsers[0].id },
{ title: 'Post C', userId: createdUsers[0].id }, { title: 'Post C', userId: createdUsers[0].id },
{ title: 'Post D', userId: createdUsers[1].id }, { title: 'Post D', userId: createdUsers[1].id },
{title: 'Post E'} { title: 'Post E' },
], ],
function(items) { function(items) {
createdPosts = items; createdPosts = items;

View File

@ -18,20 +18,20 @@ var User = modelBuilder.define('User', {
city: String, city: String,
state: String, state: String,
zipCode: String, zipCode: String,
country: String country: String,
}, },
emails: [ emails: [
{ {
label: String, label: String,
email: String email: String,
} },
], ],
friends: [String] friends: [String],
}); });
var user = new User({ name: 'Joe', age: 20, address: { street: '123 Main St', 'city': 'San Jose', state: 'CA' }, var user = new User({ name: 'Joe', age: 20, address: { street: '123 Main St', 'city': 'San Jose', state: 'CA' },
emails: [ emails: [
{label: 'work', email: 'xyz@sample.com'} { label: 'work', email: 'xyz@sample.com' },
], ],
friends: ['John', 'Mary'] }); friends: ['John', 'Mary'] });
console.log(user); console.log(user);

View File

@ -9,11 +9,11 @@ var ds = new DataSource('memory');
var Order = ds.createModel('Order', { var Order = ds.createModel('Order', {
items: [String], items: [String],
orderDate: Date, orderDate: Date,
qty: Number qty: Number,
}); });
var Customer = ds.createModel('Customer', { var Customer = ds.createModel('Customer', {
name: String name: String,
}); });
Order.belongsTo(Customer); Order.belongsTo(Customer);
@ -67,17 +67,17 @@ Customer.create({name: 'Ray'}, function (err, customer) {
}); });
var Physician = ds.createModel('Physician', { var Physician = ds.createModel('Physician', {
name: String name: String,
}); });
var Patient = ds.createModel('Patient', { var Patient = ds.createModel('Patient', {
name: String name: String,
}); });
var Appointment = ds.createModel('Appointment', { var Appointment = ds.createModel('Appointment', {
physicianId: Number, physicianId: Number,
patientId: Number, patientId: Number,
appointmentDate: Date appointmentDate: Date,
}); });
Appointment.belongsTo(Patient); Appointment.belongsTo(Patient);
@ -116,11 +116,11 @@ Physician.create({name: 'Dr John'}, function (err, physician1) {
}); });
var Assembly = ds.createModel('Assembly', { var Assembly = ds.createModel('Assembly', {
name: String name: String,
}); });
var Part = ds.createModel('Part', { var Part = ds.createModel('Part', {
partNumber: String partNumber: String,
}); });
Assembly.hasAndBelongsToMany(Part); Assembly.hasAndBelongsToMany(Part);

View File

@ -10,12 +10,12 @@ exports.GeoPoint = require('./lib/geo.js').GeoPoint;
exports.ValidationError = require('./lib/validations.js').ValidationError; exports.ValidationError = require('./lib/validations.js').ValidationError;
Object.defineProperty(exports, 'version', { Object.defineProperty(exports, 'version', {
get: function() {return require('./package.json').version;} get: function() { return require('./package.json').version; },
}); });
var commonTest = './test/common_test'; var commonTest = './test/common_test';
Object.defineProperty(exports, 'test', { Object.defineProperty(exports, 'test', {
get: function() {return require(commonTest);} get: function() { return require(commonTest); },
}); });
exports.Transaction = require('loopback-connector').Transaction; exports.Transaction = require('loopback-connector').Transaction;

View File

@ -81,12 +81,12 @@ Memory.prototype.getCollection = function(model) {
model = modelClass.settings.memory.collection || model; model = modelClass.settings.memory.collection || model;
} }
return model; return model;
} };
Memory.prototype.initCollection = function(model) { Memory.prototype.initCollection = function(model) {
this.collection(model, {}); this.collection(model, {});
this.collectionSeq(model, 1); this.collectionSeq(model, 1);
} };
Memory.prototype.collection = function(model, val) { Memory.prototype.collection = function(model, val) {
model = this.getCollection(model); model = this.getCollection(model);
@ -157,7 +157,7 @@ Memory.prototype.saveToFile = function (result, callback) {
// Flush out the models/ids // Flush out the models/ids
var data = JSON.stringify({ var data = JSON.stringify({
ids: self.ids, ids: self.ids,
models: self.cache models: self.cache,
}, null, ' '); }, null, ' ');
fs.writeFile(self.settings.file, data, function(err) { fs.writeFile(self.settings.file, data, function(err) {
@ -169,13 +169,13 @@ Memory.prototype.saveToFile = function (result, callback) {
// Enqueue the write // Enqueue the write
self.writeQueue.push({ self.writeQueue.push({
data: result, data: result,
callback: callback callback: callback,
}); });
} else if (localStorage) { } else if (localStorage) {
// Flush out the models/ids // Flush out the models/ids
var data = JSON.stringify({ var data = JSON.stringify({
ids: self.ids, ids: self.ids,
models: self.cache models: self.cache,
}, null, ' '); }, null, ' ');
window.localStorage.setItem(localStorage, data); window.localStorage.setItem(localStorage, data);
process.nextTick(function() { process.nextTick(function() {
@ -371,7 +371,7 @@ Memory.prototype._findAllSkippingIncludes = function(model, filter) {
// do we need some sorting? // do we need some sorting?
if (filter.order) { if (filter.order) {
var orders = filter.order; var 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) {
@ -381,7 +381,7 @@ Memory.prototype._findAllSkippingIncludes = function(model, filter) {
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;
} }
orders[i] = {"key": key, "reverse": reverse}; orders[i] = { 'key': key, 'reverse': reverse };
}); });
nodes = nodes.sort(sorting.bind(orders)); nodes = nodes.sort(sorting.bind(orders));
} }
@ -500,7 +500,7 @@ function applyFilter(filter) {
return false; return false;
}); });
} };
function toRegExp(pattern) { function toRegExp(pattern) {
if (pattern instanceof RegExp) { if (pattern instanceof RegExp) {
@ -509,7 +509,7 @@ function applyFilter(filter) {
var regex = ''; var 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 (var i = 0, n = pattern.length; i < n; i++) {
var char = pattern.charAt(i); var char = pattern.charAt(i);
if (char === '\\') { if (char === '\\') {
@ -797,7 +797,7 @@ Memory.prototype.exec = function (callback) {
Memory.prototype.buildNearFilter = function(filter) { Memory.prototype.buildNearFilter = function(filter) {
// noop // noop
} };
Memory.prototype.automigrate = function(models, cb) { Memory.prototype.automigrate = function(models, cb) {
var self = this; var self = this;
@ -831,7 +831,7 @@ Memory.prototype.automigrate = function (models, cb) {
self.initCollection(m); self.initCollection(m);
}); });
if (cb) process.nextTick(cb); if (cb) process.nextTick(cb);
} };
function merge(base, update) { function merge(base, update) {
if (!base) { if (!base) {

View File

@ -177,7 +177,7 @@ DataAccessObject.lookupModel = function(data) {
*/ */
DataAccessObject.getConnector = function() { DataAccessObject.getConnector = function() {
return this.getDataSource().connector; return this.getDataSource().connector;
} };
// Empty callback function // Empty callback function
function noCallback(err, result) { function noCallback(err, result) {
@ -296,7 +296,7 @@ DataAccessObject.create = function (data, options, cb) {
instance: obj, instance: obj,
isNewInstance: true, isNewInstance: true,
hookState: hookState, hookState: hookState,
options: options options: options,
}; };
Model.notifyObserversOf('before save', context, function(err) { Model.notifyObserversOf('before save', context, function(err) {
if (err) return cb(err); if (err) return cb(err);
@ -347,7 +347,7 @@ DataAccessObject.create = function (data, options, cb) {
data: val, data: val,
isNewInstance: true, isNewInstance: true,
hookState: hookState, hookState: hookState,
options: options options: options,
}; };
Model.notifyObserversOf('loaded', context, function(err) { Model.notifyObserversOf('loaded', context, function(err) {
if (err) return cb(err); if (err) return cb(err);
@ -369,7 +369,7 @@ DataAccessObject.create = function (data, options, cb) {
instance: obj, instance: obj,
isNewInstance: true, isNewInstance: true,
hookState: hookState, hookState: hookState,
options: options options: options,
}; };
Model.notifyObserversOf('after save', context, function(err) { Model.notifyObserversOf('after save', context, function(err) {
@ -387,7 +387,7 @@ DataAccessObject.create = function (data, options, cb) {
isNewInstance: true, isNewInstance: true,
currentInstance: obj, currentInstance: obj,
hookState: hookState, hookState: hookState,
options: options options: options,
}; };
Model.notifyObserversOf('persist', context, function(err) { Model.notifyObserversOf('persist', context, function(err) {
if (err) return cb(err); if (err) return cb(err);
@ -415,7 +415,7 @@ function stillConnecting(dataSource, obj, args) {
// promise variant // promise variant
var promiseArgs = Array.prototype.slice.call(args); var promiseArgs = Array.prototype.slice.call(args);
promiseArgs.callee = args.callee promiseArgs.callee = args.callee;
var cb = utils.createPromiseCallback(); var cb = utils.createPromiseCallback();
promiseArgs.push(cb); promiseArgs.push(cb);
if (dataSource.ready(obj, promiseArgs)) { if (dataSource.ready(obj, promiseArgs)) {
@ -483,21 +483,21 @@ DataAccessObject.upsert = function(data, options, cb) {
Model: Model, Model: Model,
query: byIdQuery(Model, id), query: byIdQuery(Model, id),
hookState: hookState, hookState: hookState,
options: options options: options,
}; };
Model.notifyObserversOf('access', context, doUpdateOrCreate); Model.notifyObserversOf('access', context, doUpdateOrCreate);
function doUpdateOrCreate(err, ctx) { function doUpdateOrCreate(err, ctx) {
if (err) return cb(err); if (err) return cb(err);
var isOriginalQuery = isWhereByGivenId(Model, ctx.query.where, id) var isOriginalQuery = isWhereByGivenId(Model, ctx.query.where, id);
if (connector.updateOrCreate && isOriginalQuery) { if (connector.updateOrCreate && isOriginalQuery) {
var context = { var context = {
Model: Model, Model: Model,
where: ctx.query.where, where: ctx.query.where,
data: data, data: data,
hookState: hookState, hookState: hookState,
options: options options: options,
}; };
Model.notifyObserversOf('before save', context, function(err, ctx) { Model.notifyObserversOf('before save', context, function(err, ctx) {
if (err) return cb(err); if (err) return cb(err);
@ -522,7 +522,7 @@ DataAccessObject.upsert = function(data, options, cb) {
doValidate = Model.settings.automaticValidation; doValidate = Model.settings.automaticValidation;
} }
} else { } else {
doValidate = Model.settings.validateUpsert doValidate = Model.settings.validateUpsert;
} }
} else { } else {
doValidate = options.validate; doValidate = options.validate;
@ -554,7 +554,7 @@ DataAccessObject.upsert = function(data, options, cb) {
data: update, data: update,
currentInstance: inst, currentInstance: inst,
hookState: ctx.hookState, hookState: ctx.hookState,
options: options options: options,
}; };
Model.notifyObserversOf('persist', context, function(err) { Model.notifyObserversOf('persist', context, function(err) {
if (err) return done(err); if (err) return done(err);
@ -570,7 +570,7 @@ DataAccessObject.upsert = function(data, options, cb) {
Model: Model, Model: Model,
data: data, data: data,
hookState: ctx.hookState, hookState: ctx.hookState,
options: options options: options,
}; };
Model.notifyObserversOf('loaded', context, function(err) { Model.notifyObserversOf('loaded', context, function(err) {
if (err) return cb(err); if (err) return cb(err);
@ -593,7 +593,7 @@ DataAccessObject.upsert = function(data, options, cb) {
instance: obj, instance: obj,
isNewInstance: info ? info.isNewInstance : undefined, isNewInstance: info ? info.isNewInstance : undefined,
hookState: hookState, hookState: hookState,
options: options options: options,
}; };
Model.notifyObserversOf('after save', context, function(err) { Model.notifyObserversOf('after save', context, function(err) {
@ -687,7 +687,7 @@ DataAccessObject.replaceOrCreate = function replaceOrCreate(data, options, cb) {
Model: Model, Model: Model,
query: byIdQuery(Model, id), query: byIdQuery(Model, id),
hookState: hookState, hookState: hookState,
options: options options: options,
}; };
Model.notifyObserversOf('access', context, doReplaceOrCreate); Model.notifyObserversOf('access', context, doReplaceOrCreate);
@ -701,7 +701,7 @@ DataAccessObject.replaceOrCreate = function replaceOrCreate(data, options, cb) {
Model: Model, Model: Model,
instance: inst, instance: inst,
hookState: hookState, hookState: hookState,
options: options options: options,
}; };
Model.notifyObserversOf('before save', context, function(err, ctx) { Model.notifyObserversOf('before save', context, function(err, ctx) {
if (err) return cb(err); if (err) return cb(err);
@ -741,7 +741,7 @@ DataAccessObject.replaceOrCreate = function replaceOrCreate(data, options, cb) {
data: update, data: update,
currentInstance: inst, currentInstance: inst,
hookState: ctx.hookState, hookState: ctx.hookState,
options: options options: options,
}; };
Model.notifyObserversOf('persist', context, function(err) { Model.notifyObserversOf('persist', context, function(err) {
if (err) return done(err); if (err) return done(err);
@ -755,7 +755,7 @@ DataAccessObject.replaceOrCreate = function replaceOrCreate(data, options, cb) {
data: data, data: data,
isNewInstance: info ? info.isNewInstance : undefined, isNewInstance: info ? info.isNewInstance : undefined,
hookState: ctx.hookState, hookState: ctx.hookState,
options: options options: options,
}; };
Model.notifyObserversOf('loaded', context, function(err) { Model.notifyObserversOf('loaded', context, function(err) {
if (err) return cb(err); if (err) return cb(err);
@ -775,7 +775,7 @@ DataAccessObject.replaceOrCreate = function replaceOrCreate(data, options, cb) {
instance: obj, instance: obj,
isNewInstance: info ? info.isNewInstance : undefined, isNewInstance: info ? info.isNewInstance : undefined,
hookState: hookState, hookState: hookState,
options: options options: options,
}; };
Model.notifyObserversOf('after save', context, function(err) { Model.notifyObserversOf('after save', context, function(err) {
@ -879,7 +879,7 @@ DataAccessObject.findOrCreate = function findOrCreate(query, data, options, cb)
data: data, data: data,
isNewInstance: created, isNewInstance: created,
hookState: hookState, hookState: hookState,
options: options options: options,
}; };
Model.notifyObserversOf('loaded', context, function(err) { Model.notifyObserversOf('loaded', context, function(err) {
if (err) return cb(err); if (err) return cb(err);
@ -897,7 +897,7 @@ DataAccessObject.findOrCreate = function findOrCreate(query, data, options, cb)
instance: obj, instance: obj,
isNewInstance: true, isNewInstance: true,
hookState: hookState, hookState: hookState,
options: options options: options,
}; };
Model.notifyObserversOf('after save', context, function(err) { Model.notifyObserversOf('after save', context, function(err) {
if (cb.promise) { if (cb.promise) {
@ -926,7 +926,7 @@ DataAccessObject.findOrCreate = function findOrCreate(query, data, options, cb)
isNewInstance: true, isNewInstance: true,
currentInstance : currentInstance, currentInstance : currentInstance,
hookState: hookState, hookState: hookState,
options: options options: options,
}; };
Model.notifyObserversOf('persist', context, function(err) { Model.notifyObserversOf('persist', context, function(err) {
@ -958,7 +958,7 @@ DataAccessObject.findOrCreate = function findOrCreate(query, data, options, cb)
Model: Model, Model: Model,
query: query, query: query,
hookState: hookState, hookState: hookState,
options: options options: options,
}; };
Model.notifyObserversOf('access', context, function(err, ctx) { Model.notifyObserversOf('access', context, function(err, ctx) {
if (err) return cb(err); if (err) return cb(err);
@ -977,7 +977,7 @@ DataAccessObject.findOrCreate = function findOrCreate(query, data, options, cb)
instance: obj, instance: obj,
isNewInstance: true, isNewInstance: true,
hookState: hookState, hookState: hookState,
options: options options: options,
}; };
Model.notifyObserversOf('before save', context, function(err, ctx) { Model.notifyObserversOf('before save', context, function(err, ctx) {
if (err) return cb(err); if (err) return cb(err);
@ -1216,7 +1216,7 @@ DataAccessObject._getSetting = function(key) {
// Check for settings in model // Check for settings in model
var m = this.definition; var m = this.definition;
if (m && m.settings && m.settings[key]) { if (m && m.settings && m.settings[key]) {
return m.settings[key] return m.settings[key];
} }
// Check for settings in connector // Check for settings in connector
@ -1239,7 +1239,7 @@ var operators = {
neq: '!=', neq: '!=',
like: 'LIKE', like: 'LIKE',
nlike: 'NOT LIKE', nlike: 'NOT LIKE',
regexp: 'REGEXP' regexp: 'REGEXP',
}; };
/* /*
@ -1636,7 +1636,7 @@ DataAccessObject.find = function find(query, options, cb) {
Model: self, Model: self,
query: query, query: query,
hookState: hookState, hookState: hookState,
options: options options: options,
}; };
self.notifyObserversOf('access', context, function(err, ctx) { self.notifyObserversOf('access', context, function(err, ctx) {
if (err) return cb(err); if (err) return cb(err);
@ -1651,7 +1651,7 @@ DataAccessObject.find = function find(query, options, cb) {
memory.define({ memory.define({
properties: self.dataSource.definitions[self.modelName].properties, properties: self.dataSource.definitions[self.modelName].properties,
settings: self.dataSource.definitions[self.modelName].settings, settings: self.dataSource.definitions[self.modelName].settings,
model: self model: self,
}); });
data.forEach(function(obj) { data.forEach(function(obj) {
@ -1723,7 +1723,7 @@ DataAccessObject.find = function find(query, options, cb) {
instance: obj, instance: obj,
isNewInstance: false, isNewInstance: false,
hookState: hookState, hookState: hookState,
options: options options: options,
}; };
Model.notifyObserversOf('loaded', context, function(err) { Model.notifyObserversOf('loaded', context, function(err) {
@ -1765,7 +1765,7 @@ DataAccessObject.find = function find(query, options, cb) {
Model: this, Model: this,
query: query, query: query,
hookState: hookState, hookState: hookState,
options: options options: options,
}; };
this.notifyObserversOf('access', context, function(err, ctx) { this.notifyObserversOf('access', context, function(err, ctx) {
if (err) return cb(err); if (err) return cb(err);
@ -1876,7 +1876,7 @@ DataAccessObject.remove = DataAccessObject.deleteAll = DataAccessObject.destroyA
Model: Model, Model: Model,
where: whereIsEmpty(where) ? {} : where, where: whereIsEmpty(where) ? {} : where,
hookState: hookState, hookState: hookState,
options: options options: options,
}; };
if (options.notify === false) { if (options.notify === false) {
@ -1887,7 +1887,7 @@ DataAccessObject.remove = DataAccessObject.deleteAll = DataAccessObject.destroyA
Model: Model, Model: Model,
query: query, query: query,
hookState: hookState, hookState: hookState,
options: options options: options,
}; };
Model.notifyObserversOf('access', context, function(err, ctx) { Model.notifyObserversOf('access', context, function(err, ctx) {
if (err) return cb(err); if (err) return cb(err);
@ -1895,7 +1895,7 @@ DataAccessObject.remove = DataAccessObject.deleteAll = DataAccessObject.destroyA
Model: Model, Model: Model,
where: ctx.query.where, where: ctx.query.where,
hookState: hookState, hookState: hookState,
options: options options: options,
}; };
Model.notifyObserversOf('before delete', context, function(err, ctx) { Model.notifyObserversOf('before delete', context, function(err, ctx) {
if (err) return cb(err); if (err) return cb(err);
@ -1941,7 +1941,7 @@ DataAccessObject.remove = DataAccessObject.deleteAll = DataAccessObject.destroyA
Model: Model, Model: Model,
where: where, where: where,
hookState: hookState, hookState: hookState,
options: options options: options,
}; };
Model.notifyObserversOf('after delete', context, function(err) { Model.notifyObserversOf('after delete', context, function(err) {
cb(err, info); cb(err, info);
@ -1955,7 +1955,7 @@ DataAccessObject.remove = DataAccessObject.deleteAll = DataAccessObject.destroyA
function whereIsEmpty(where) { function whereIsEmpty(where) {
return !where || return !where ||
(typeof where === 'object' && Object.keys(where).length === 0) (typeof where === 'object' && Object.keys(where).length === 0);
} }
/** /**
@ -2085,7 +2085,7 @@ DataAccessObject.count = function (where, options, cb) {
Model: Model, Model: Model,
query: { where: where }, query: { where: where },
hookState: hookState, hookState: hookState,
options: options options: options,
}; };
this.notifyObserversOf('access', context, function(err, ctx) { this.notifyObserversOf('access', context, function(err, ctx) {
if (err) return cb(err); if (err) return cb(err);
@ -2158,7 +2158,7 @@ DataAccessObject.prototype.save = function (options, cb) {
Model: Model, Model: Model,
instance: inst, instance: inst,
hookState: hookState, hookState: hookState,
options: options options: options,
}; };
Model.notifyObserversOf('before save', context, function(err) { Model.notifyObserversOf('before save', context, function(err) {
if (err) return cb(err); if (err) return cb(err);
@ -2200,7 +2200,7 @@ DataAccessObject.prototype.save = function (options, cb) {
data: data, data: data,
isNewInstance: result && result.isNewInstance, isNewInstance: result && result.isNewInstance,
hookState: hookState, hookState: hookState,
options: options options: options,
}; };
Model.notifyObserversOf('loaded', context, function(err) { Model.notifyObserversOf('loaded', context, function(err) {
if (err) return cb(err); if (err) return cb(err);
@ -2212,7 +2212,7 @@ DataAccessObject.prototype.save = function (options, cb) {
instance: inst, instance: inst,
isNewInstance: result && result.isNewInstance, isNewInstance: result && result.isNewInstance,
hookState: hookState, hookState: hookState,
options: options options: options,
}; };
Model.notifyObserversOf('after save', context, function(err) { Model.notifyObserversOf('after save', context, function(err) {
if (err) return cb(err, inst); if (err) return cb(err, inst);
@ -2234,7 +2234,7 @@ DataAccessObject.prototype.save = function (options, cb) {
where: byIdQuery(Model, getIdValue(Model, inst)).where, where: byIdQuery(Model, getIdValue(Model, inst)).where,
currentInstance: inst, currentInstance: inst,
hookState: hookState, hookState: hookState,
options: options options: options,
}; };
Model.notifyObserversOf('persist', context, function(err) { Model.notifyObserversOf('persist', context, function(err) {
@ -2328,7 +2328,7 @@ DataAccessObject.updateAll = function (where, data, options, cb) {
Model: Model, Model: Model,
query: { where: where }, query: { where: where },
hookState: hookState, hookState: hookState,
options: options options: options,
}; };
Model.notifyObserversOf('access', context, function(err, ctx) { Model.notifyObserversOf('access', context, function(err, ctx) {
if (err) return cb(err); if (err) return cb(err);
@ -2337,7 +2337,7 @@ DataAccessObject.updateAll = function (where, data, options, cb) {
where: ctx.query.where, where: ctx.query.where,
data: data, data: data,
hookState: hookState, hookState: hookState,
options: options options: options,
}; };
Model.notifyObserversOf('before save', context, Model.notifyObserversOf('before save', context,
function(err, ctx) { function(err, ctx) {
@ -2366,7 +2366,7 @@ DataAccessObject.updateAll = function (where, data, options, cb) {
where: where, where: where,
data: data, data: data,
hookState: hookState, hookState: hookState,
options: options options: options,
}; };
Model.notifyObserversOf('after save', context, function(err, ctx) { Model.notifyObserversOf('after save', context, function(err, ctx) {
return cb(err, info); return cb(err, info);
@ -2378,7 +2378,7 @@ DataAccessObject.updateAll = function (where, data, options, cb) {
where: where, where: where,
data: data, data: data,
hookState: hookState, hookState: hookState,
options: options options: options,
}; };
Model.notifyObserversOf('persist', context, function(err, ctx) { Model.notifyObserversOf('persist', context, function(err, ctx) {
if (err) return cb (err); if (err) return cb (err);
@ -2446,7 +2446,7 @@ DataAccessObject.prototype.remove =
Model: Model, Model: Model,
query: byIdQuery(Model, id), query: byIdQuery(Model, id),
hookState: hookState, hookState: hookState,
options: options options: options,
}; };
Model.notifyObserversOf('access', context, function(err, ctx) { Model.notifyObserversOf('access', context, function(err, ctx) {
@ -2456,7 +2456,7 @@ DataAccessObject.prototype.remove =
where: ctx.query.where, where: ctx.query.where,
instance: inst, instance: inst,
hookState: hookState, hookState: hookState,
options: options options: options,
}; };
Model.notifyObserversOf('before delete', context, function(err, ctx) { Model.notifyObserversOf('before delete', context, function(err, ctx) {
if (err) return cb(err); if (err) return cb(err);
@ -2483,7 +2483,7 @@ DataAccessObject.prototype.remove =
where: where, where: where,
instance: inst, instance: inst,
hookState: hookState, hookState: hookState,
options: options options: options,
}; };
Model.notifyObserversOf('after delete', context, function(err) { Model.notifyObserversOf('after delete', context, function(err) {
cb(err, info); cb(err, info);
@ -2510,7 +2510,7 @@ DataAccessObject.prototype.remove =
where: where, where: where,
instance: inst, instance: inst,
hookState: hookState, hookState: hookState,
options: options options: options,
}; };
Model.notifyObserversOf('after delete', context, function(err) { Model.notifyObserversOf('after delete', context, function(err) {
cb(err, info); cb(err, info);
@ -2656,7 +2656,7 @@ DataAccessObject.replaceById = function(id, data, options, cb) {
instance: inst, instance: inst,
isNewInstance: false, isNewInstance: false,
hookState: hookState, hookState: hookState,
options: options options: options,
}; };
Model.notifyObserversOf('before save', context, function(err, ctx) { Model.notifyObserversOf('before save', context, function(err, ctx) {
@ -2715,7 +2715,7 @@ DataAccessObject.replaceById = function(id, data, options, cb) {
hookState: hookState, hookState: hookState,
data: context.data, data: context.data,
isNewInstance:false, isNewInstance:false,
options: options options: options,
}; };
Model.notifyObserversOf('loaded', ctx, function(err) { Model.notifyObserversOf('loaded', ctx, function(err) {
if (err) return cb(err); if (err) return cb(err);
@ -2728,7 +2728,7 @@ DataAccessObject.replaceById = function(id, data, options, cb) {
instance: inst, instance: inst,
isNewInstance: false, isNewInstance: false,
hookState: hookState, hookState: hookState,
options: options options: options,
}; };
Model.notifyObserversOf('after save', context, function(err) { Model.notifyObserversOf('after save', context, function(err) {
if (!err) Model.emit('changed', inst); if (!err) Model.emit('changed', inst);
@ -2745,7 +2745,7 @@ DataAccessObject.replaceById = function(id, data, options, cb) {
isNewInstance:false, isNewInstance:false,
currentInstance: inst, currentInstance: inst,
hookState: hookState, hookState: hookState,
options: options options: options,
}; };
Model.notifyObserversOf('persist', ctx, function(err) { Model.notifyObserversOf('persist', ctx, function(err) {
connector.replaceById(model, id, connector.replaceById(model, id,
@ -2841,7 +2841,7 @@ function(data, options, cb) {
data: data, data: data,
currentInstance: inst, currentInstance: inst,
hookState: hookState, hookState: hookState,
options: options options: options,
}; };
Model.notifyObserversOf('before save', context, function(err, ctx) { Model.notifyObserversOf('before save', context, function(err, ctx) {
@ -2895,7 +2895,7 @@ function(data, options, cb) {
Model: Model, Model: Model,
data: context.data, data: context.data,
hookState: hookState, hookState: hookState,
options: options options: options,
}; };
Model.notifyObserversOf('loaded', ctx, function(err) { Model.notifyObserversOf('loaded', ctx, function(err) {
if (err) return cb(err); if (err) return cb(err);
@ -2918,7 +2918,7 @@ function(data, options, cb) {
instance: inst, instance: inst,
isNewInstance: false, isNewInstance: false,
hookState: hookState, hookState: hookState,
options: options options: options,
}; };
Model.notifyObserversOf('after save', context, function(err) { Model.notifyObserversOf('after save', context, function(err) {
if (!err) Model.emit('changed', inst); if (!err) Model.emit('changed', inst);
@ -2936,7 +2936,7 @@ function(data, options, cb) {
currentInstance: inst, currentInstance: inst,
isNewInstance: false, isNewInstance: false,
hookState: hookState, hookState: hookState,
options: options options: options,
}; };
Model.notifyObserversOf('persist', ctx, function(err) { Model.notifyObserversOf('persist', ctx, function(err) {
if (connector.updateAttributes.length === 5) { if (connector.updateAttributes.length === 5) {
@ -2984,7 +2984,7 @@ function defineReadonlyProp(obj, key, value) {
writable: false, writable: false,
enumerable: true, enumerable: true,
configurable: true, configurable: true,
value: value value: value,
}); });
} }

View File

@ -135,7 +135,7 @@ function DataSource(name, settings, modelBuilder) {
http: fn.http, http: fn.http,
remoteEnabled: fn.shared ? true : false, remoteEnabled: fn.shared ? true : false,
scope: this.DataAccessObject, scope: this.DataAccessObject,
fnName: name fnName: name,
}); });
} }
}.bind(this)); }.bind(this));
@ -152,7 +152,7 @@ function DataSource(name, settings, modelBuilder) {
http: fn.http, http: fn.http,
remoteEnabled: fn.shared ? true : false, remoteEnabled: fn.shared ? true : false,
scope: this.DataAccessObject.prototype, scope: this.DataAccessObject.prototype,
fnName: name fnName: name,
}); });
} }
}.bind(this)); }.bind(this));
@ -244,7 +244,7 @@ DataSource._resolveConnector = function (name, loader) {
} }
return { return {
connector: connector, connector: connector,
error: error error: error,
}; };
}; };
@ -455,7 +455,7 @@ DataSource.prototype.defineRelations = function (modelClass, relations) {
if (relations) { if (relations) {
Object.keys(relations).forEach(function(rn) { Object.keys(relations).forEach(function(rn) {
var r = relations[rn]; var r = relations[rn];
assert(DataSource.relationTypes.indexOf(r.type) !== -1, "Invalid relation type: " + r.type); assert(DataSource.relationTypes.indexOf(r.type) !== -1, 'Invalid relation type: ' + r.type);
var targetModel, polymorphicName; var targetModel, polymorphicName;
if (r.polymorphic && r.type !== 'belongsTo' && !r.model) { if (r.polymorphic && r.type !== 'belongsTo' && !r.model) {
@ -523,7 +523,7 @@ DataSource.prototype.setupDataAccess = function (modelClass, settings) {
this.connector.define({ this.connector.define({
model: modelClass, model: modelClass,
properties: modelClass.definition.properties, properties: modelClass.definition.properties,
settings: settings settings: settings,
}); });
} }
} }
@ -665,7 +665,7 @@ DataSource.prototype.mixin = function (ModelCtor) {
return ~[ return ~[
'scope', 'scope',
'fnName', 'fnName',
'prototype' 'prototype',
].indexOf(key); ].indexOf(key);
}) })
.forEach(function(key) { .forEach(function(key) {
@ -1337,14 +1337,14 @@ DataSource.prototype.discoverSchemas = function (modelName, options, cb) {
var schema = { var 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
}, },
properties: {} properties: {},
}; };
schema.options[dbType] = { schema.options[dbType] = {
schema: columns[0].owner, schema: columns[0].owner,
table: modelName table: modelName,
}; };
columns.forEach(function(item) { columns.forEach(function(item) {
@ -1357,7 +1357,7 @@ DataSource.prototype.discoverSchemas = function (modelName, options, cb) {
|| item.nullable === 0 || item.nullable === false), || item.nullable === 0 || item.nullable === false),
length: item.dataLength, length: item.dataLength,
precision: item.dataPrecision, precision: item.dataPrecision,
scale: item.dataScale scale: item.dataScale,
}; };
if (pks[item.columnName]) { if (pks[item.columnName]) {
@ -1369,7 +1369,7 @@ DataSource.prototype.discoverSchemas = function (modelName, options, cb) {
dataLength: i.dataLength, dataLength: i.dataLength,
dataPrecision: item.dataPrecision, dataPrecision: item.dataPrecision,
dataScale: item.dataScale, dataScale: item.dataScale,
nullable: i.nullable nullable: i.nullable,
}; };
}); });
@ -1393,7 +1393,7 @@ DataSource.prototype.discoverSchemas = function (modelName, options, cb) {
keySeq: fk.keySeq, keySeq: fk.keySeq,
owner: fk.pkOwner, owner: fk.pkOwner,
tableName: fk.pkTableName, tableName: fk.pkTableName,
columnName: fk.pkColumnName columnName: fk.pkColumnName,
}; };
if (fks[fk.fkName]) { if (fks[fk.fkName]) {
fks[fk.fkName].push(fkInfo); fks[fk.fkName].push(fkInfo);
@ -1412,7 +1412,7 @@ DataSource.prototype.discoverSchemas = function (modelName, options, cb) {
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; var key = fk.pkOwner + '.' + fk.pkTableName;
@ -1488,14 +1488,14 @@ DataSource.prototype.discoverSchemasSync = function (modelName, options) {
var schema = { var 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
}, },
properties: {} properties: {},
}; };
schema.options[dbType] = { schema.options[dbType] = {
schema: columns.length > 0 && columns[0].owner, schema: columns.length > 0 && columns[0].owner,
table: modelName table: modelName,
}; };
columns.forEach(function(item) { columns.forEach(function(item) {
@ -1507,7 +1507,7 @@ DataSource.prototype.discoverSchemasSync = function (modelName, options) {
required: (item.nullable === 'N'), required: (item.nullable === 'N'),
length: item.dataLength, length: item.dataLength,
precision: item.dataPrecision, precision: item.dataPrecision,
scale: item.dataScale scale: item.dataScale,
}; };
if (pks[item.columnName]) { if (pks[item.columnName]) {
@ -1519,7 +1519,7 @@ DataSource.prototype.discoverSchemasSync = function (modelName, options) {
dataLength: i.dataLength, dataLength: i.dataLength,
dataPrecision: item.dataPrecision, dataPrecision: item.dataPrecision,
dataScale: item.dataScale, dataScale: item.dataScale,
nullable: i.nullable nullable: i.nullable,
}; };
}); });
@ -1544,7 +1544,7 @@ DataSource.prototype.discoverSchemasSync = function (modelName, options) {
keySeq: fk.keySeq, keySeq: fk.keySeq,
owner: fk.pkOwner, owner: fk.pkOwner,
tableName: fk.pkTableName, tableName: fk.pkTableName,
columnName: fk.pkColumnName columnName: fk.pkColumnName,
}; };
if (fks[fk.fkName]) { if (fks[fk.fkName]) {
fks[fk.fkName].push(fkInfo); fks[fk.fkName].push(fkInfo);
@ -1563,7 +1563,7 @@ DataSource.prototype.discoverSchemasSync = function (modelName, options) {
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; var key = fk.pkOwner + '.' + fk.pkTableName;
@ -1914,7 +1914,7 @@ DataSource.prototype.copyModel = function copyModel(Master) {
dataSource.connector.define({ dataSource.connector.define({
model: Slave, model: Slave,
properties: md.properties, properties: md.properties,
settings: md.settings settings: md.settings,
}); });
} }
@ -1973,7 +1973,7 @@ DataSource.prototype.enableRemote = function (operation) {
} else { } else {
throw new Error(operation + ' is not provided by the attached connector'); throw new Error(operation + ' is not provided by the attached connector');
} }
} };
/** /**
* Disable remote access to a data source operation. Each [connector](#connector) has its own set of set enabled * Disable remote access to a data source operation. Each [connector](#connector) has its own set of set enabled
@ -2002,7 +2002,7 @@ DataSource.prototype.disableRemote = function (operation) {
} else { } else {
throw new Error(operation + ' is not provided by the attached connector'); throw new Error(operation + ' is not provided by the attached connector');
} }
} };
/** /**
* Get an operation's metadata. * Get an operation's metadata.
@ -2020,7 +2020,7 @@ DataSource.prototype.getOperation = function (operation) {
return op; return op;
} }
} }
} };
/** /**
* Return JSON object describing all operations. * Return JSON object describing all operations.
@ -2047,7 +2047,7 @@ DataSource.prototype.getOperation = function (operation) {
*/ */
DataSource.prototype.operations = function() { DataSource.prototype.operations = function() {
return this._operations; return this._operations;
} };
/** /**
* Define an operation to the data source * Define an operation to the data source
@ -2171,7 +2171,7 @@ function hiddenProperty(obj, key, value) {
writable: false, writable: false,
enumerable: false, enumerable: false,
configurable: false, configurable: false,
value: value value: value,
}); });
} }
@ -2187,7 +2187,7 @@ function defineReadonlyProp(obj, key, value) {
writable: false, writable: false,
enumerable: true, enumerable: true,
configurable: true, configurable: true,
value: value value: value,
}); });
} }

View File

@ -21,14 +21,14 @@ exports.nearFilter = function nearFilter(where) {
near: ex.near, near: ex.near,
maxDistance: ex.maxDistance, maxDistance: ex.maxDistance,
unit: ex.unit, unit: ex.unit,
key: key key: key,
}; };
} }
}); });
} }
return result; return result;
} };
/*! /*!
* Filter a set of objects using the given `nearFilter`. * Filter a set of objects using the given `nearFilter`.
@ -81,7 +81,7 @@ exports.filter = function (arr, filter) {
return 0; return 0;
} }
}); });
} };
exports.GeoPoint = GeoPoint; exports.GeoPoint = GeoPoint;
@ -134,7 +134,7 @@ function GeoPoint(data) {
if (arguments.length === 2) { if (arguments.length === 2) {
data = { data = {
lat: arguments[0], lat: arguments[0],
lng: arguments[1] lng: arguments[1],
}; };
} }
@ -147,7 +147,7 @@ function GeoPoint(data) {
if (Array.isArray(data)) { if (Array.isArray(data)) {
data = { data = {
lat: Number(data[0]), lat: Number(data[0]),
lng: Number(data[1]) lng: Number(data[1]),
}; };
} else { } else {
data.lng = Number(data.lng); data.lng = Number(data.lng);
@ -255,7 +255,7 @@ var EARTH_RADIUS = {
miles: 3958.75, miles: 3958.75,
feet: 20902200, feet: 20902200,
radians: 1, radians: 1,
degrees: RAD2DEG degrees: RAD2DEG,
}; };
function geoDistance(x1, y1, x2, y2, options) { function geoDistance(x1, y1, x2, y2, options) {

View File

@ -36,10 +36,10 @@ Hookable.afterDestroy = null;
// TODO: Evaluate https://github.com/bnoguchi/hooks-js/ // TODO: Evaluate https://github.com/bnoguchi/hooks-js/
Hookable.prototype.trigger = function trigger(actionName, work, data, callback) { Hookable.prototype.trigger = function trigger(actionName, work, data, callback) {
var capitalizedName = capitalize(actionName); var capitalizedName = capitalize(actionName);
var beforeHook = this.constructor["before" + capitalizedName] var beforeHook = this.constructor['before' + capitalizedName]
|| this.constructor["pre" + capitalizedName]; || this.constructor['pre' + capitalizedName];
var afterHook = this.constructor["after" + capitalizedName] var 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;

View File

@ -321,10 +321,10 @@ 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 = { var throughFilter = {
where: {} where: {},
}; };
throughFilter.where[relation.keyTo] = { throughFilter.where[relation.keyTo] = {
inq: uniq(sourceIds) inq: uniq(sourceIds),
}; };
if (polymorphic) { if (polymorphic) {
//handle polymorphic hasMany (reverse) in which case we need to filter //handle polymorphic hasMany (reverse) in which case we need to filter
@ -367,7 +367,7 @@ Inclusion.include = function (objects, include, options, cb) {
//Polymorphic relation does not have idKey of modelTo. Find it manually //Polymorphic relation does not have idKey of modelTo. Find it manually
var modelToIdName = idName(relation.modelTo); var modelToIdName = idName(relation.modelTo);
filter.where[modelToIdName] = { filter.where[modelToIdName] = {
inq: uniq(targetIds) inq: uniq(targetIds),
}; };
//make sure that the modelToIdName is included if fields are specified //make sure that the modelToIdName is included if fields are specified
@ -450,7 +450,7 @@ Inclusion.include = function (objects, include, options, cb) {
obj.__cachedRelations[relationName] = []; obj.__cachedRelations[relationName] = [];
} }
filter.where[relation.keyTo] = { filter.where[relation.keyTo] = {
inq: uniq(allTargetIds) inq: uniq(allTargetIds),
}; };
relation.applyScope(null, filter); relation.applyScope(null, filter);
/** /**
@ -503,7 +503,7 @@ Inclusion.include = function (objects, include, options, cb) {
var objIdMap2 = includeUtils.buildOneToOneIdentityMapWithOrigKeys(objs, relation.keyFrom); var objIdMap2 = includeUtils.buildOneToOneIdentityMapWithOrigKeys(objs, relation.keyFrom);
filter.where[relation.keyTo] = { filter.where[relation.keyTo] = {
inq: uniq(objIdMap2.getKeys()) inq: uniq(objIdMap2.getKeys()),
}; };
relation.applyScope(null, filter); relation.applyScope(null, filter);
@ -545,7 +545,7 @@ Inclusion.include = function (objects, include, options, cb) {
obj.__cachedRelations[relationName] = []; obj.__cachedRelations[relationName] = [];
} }
filter.where[relation.keyTo] = { filter.where[relation.keyTo] = {
inq: uniq(sourceIds) inq: uniq(sourceIds),
}; };
relation.applyScope(null, filter); relation.applyScope(null, filter);
options.partitionBy = relation.keyTo; options.partitionBy = relation.keyTo;
@ -648,7 +648,7 @@ Inclusion.include = function (objects, include, options, cb) {
utils.mergeQuery(typeFilter, filter); utils.mergeQuery(typeFilter, filter);
var targetIds = targetIdsByType[modelType]; var targetIds = targetIdsByType[modelType];
typeFilter.where[relation.keyTo] = { typeFilter.where[relation.keyTo] = {
inq: uniq(targetIds) inq: uniq(targetIds),
}; };
var Model = lookupModel(relation.modelFrom.dataSource.modelBuilder. var Model = lookupModel(relation.modelFrom.dataSource.modelBuilder.
models, modelType); models, modelType);
@ -720,7 +720,7 @@ Inclusion.include = function (objects, include, options, cb) {
obj.__cachedRelations[relationName] = null; obj.__cachedRelations[relationName] = null;
} }
filter.where[relation.keyTo] = { filter.where[relation.keyTo] = {
inq: uniq(sourceIds) inq: uniq(sourceIds),
}; };
relation.applyScope(null, filter); relation.applyScope(null, filter);
relation.modelTo.find(filter, options, targetFetchHandler); relation.modelTo.find(filter, options, targetFetchHandler);
@ -787,7 +787,7 @@ Inclusion.include = function (objects, include, options, cb) {
obj.__cachedRelations[relationName] = null; obj.__cachedRelations[relationName] = null;
} }
filter.where[relation.keyTo] = { filter.where[relation.keyTo] = {
inq: uniq(targetIds) inq: uniq(targetIds),
}; };
relation.applyScope(null, filter); relation.applyScope(null, filter);
relation.modelTo.find(filter, options, targetFetchHandler); relation.modelTo.find(filter, options, targetFetchHandler);

View File

@ -66,7 +66,7 @@ function KVMap(){
var _originalKeyFieldName = 'originalKey'; var _originalKeyFieldName = 'originalKey';
var _valueKeyFieldName = 'value'; var _valueKeyFieldName = 'value';
var _dict = {}; var _dict = {};
var keyToString = function(key){ return key.toString() }; var keyToString = function(key) { return key.toString(); };
var mapImpl = { var mapImpl = {
set: function(key, value) { set: function(key, value) {
var recordObj = {}; var recordObj = {};
@ -97,7 +97,7 @@ function KVMap(){
result.push(_dict[key][_originalKeyFieldName]); result.push(_dict[key][_originalKeyFieldName]);
} }
return result; return result;
} },
}; };
return mapImpl; return mapImpl;

View File

@ -62,6 +62,6 @@ module.exports = function getIntrospector(ModelBuilder) {
ModelBuilder.introspect = introspectType; ModelBuilder.introspect = introspectType;
return introspectType; return introspectType;
} };

View File

@ -15,7 +15,7 @@ exports.inherits = function (newClass, baseClass, options) {
options = options || { options = options || {
staticProperties: true, staticProperties: true,
override: false override: false,
}; };
if (options.staticProperties) { if (options.staticProperties) {
@ -49,7 +49,7 @@ exports.mixin = function (newClass, mixinClass, options) {
staticProperties: true, staticProperties: true,
instanceProperties: true, instanceProperties: true,
override: false, override: false,
proxyFunctions: false proxyFunctions: false,
}; };
if (options.staticProperties === undefined) { if (options.staticProperties === undefined) {

View File

@ -49,14 +49,14 @@ function List(items, itemType, parent) {
Object.defineProperty(arr, 'itemType', { Object.defineProperty(arr, 'itemType', {
writable: true, writable: true,
enumerable: false, enumerable: false,
value: itemType value: itemType,
}); });
if (parent) { if (parent) {
Object.defineProperty(arr, 'parent', { Object.defineProperty(arr, 'parent', {
writable: true, writable: true,
enumerable: false, enumerable: false,
value: parent value: parent,
}); });
} }

View File

@ -302,7 +302,7 @@ ModelBuilder.prototype.define = function defineClass(className, properties, sett
return this.__data[idProp]; return this.__data[idProp];
}, },
configurable: true, configurable: true,
enumerable: false enumerable: false,
}); });
} }
} else { } else {
@ -318,7 +318,7 @@ ModelBuilder.prototype.define = function defineClass(className, properties, sett
return compositeId; return compositeId;
}, },
configurable: true, configurable: true,
enumerable: false enumerable: false,
}); });
} }
@ -474,7 +474,7 @@ ModelBuilder.prototype.define = function defineClass(className, properties, sett
} }
}, },
configurable: true, configurable: true,
enumerable: true enumerable: true,
}); });
// FIXME: [rfeng] Do we need to keep the raw data? // FIXME: [rfeng] Do we need to keep the raw data?
@ -490,7 +490,7 @@ ModelBuilder.prototype.define = function defineClass(className, properties, sett
this.__data[propertyName] = value; this.__data[propertyName] = value;
}, },
configurable: true, configurable: true,
enumerable: false enumerable: false,
}); });
}; };
@ -638,7 +638,7 @@ ModelBuilder.prototype.copyModel = function copyModel(Master) {
modelBuilder.models[className] = Slave; modelBuilder.models[className] = Slave;
modelBuilder.definitions[className] = { modelBuilder.definitions[className] = {
properties: md.properties, properties: md.properties,
settings: md.settings settings: md.settings,
}; };
} }
@ -653,7 +653,7 @@ function hiddenProperty(where, property, value) {
writable: true, writable: true,
enumerable: false, enumerable: false,
configurable: true, configurable: true,
value: value value: value,
}); });
} }
@ -740,8 +740,8 @@ ModelBuilder.prototype.buildModels = function (schemas, createModel) {
{ {
name: this.getSchemaName(), name: this.getSchemaName(),
properties: schemas, properties: schemas,
options: {anonymous: true} options: { anonymous: true },
} },
]; ];
} }
} }

View File

@ -229,11 +229,11 @@ ModelDefinition.prototype.build = function (forceRebuild) {
source: this.name, source: this.name,
target: type, target: type,
type: Array.isArray(prop) ? 'hasMany' : 'belongsTo', type: Array.isArray(prop) ? 'hasMany' : 'belongsTo',
as: p as: p,
}); });
} else { } else {
var typeDef = { var typeDef = {
type: type type: type,
}; };
if (typeof prop === 'object' && prop !== null) { if (typeof prop === 'object' && prop !== null) {
for (var a in prop) { for (var a in prop) {
@ -276,7 +276,7 @@ ModelDefinition.prototype.toJSON = function (forceRebuild) {
var json = { var json = {
name: this.name, name: this.name,
properties: {}, properties: {},
settings: this.settings settings: this.settings,
}; };
this.build(forceRebuild); this.build(forceRebuild);

View File

@ -31,7 +31,7 @@ var BASE_TYPES = {
'Number': true, 'Number': true,
'Date': true, 'Date': true,
'Text': true, 'Text': true,
'ObjectID': true 'ObjectID': true,
}; };
/** /**
@ -99,14 +99,14 @@ ModelBaseClass.prototype._initProperties = function (data, options) {
writable: true, writable: true,
enumerable: false, enumerable: false,
configurable: true, configurable: true,
value: {} value: {},
}, },
__data: { __data: {
writable: true, writable: true,
enumerable: false, enumerable: false,
configurable: true, configurable: true,
value: {} value: {},
}, },
// Instance level data source // Instance level data source
@ -114,7 +114,7 @@ ModelBaseClass.prototype._initProperties = function (data, options) {
writable: true, writable: true,
enumerable: false, enumerable: false,
configurable: true, configurable: true,
value: options.dataSource value: options.dataSource,
}, },
// Instance level strict mode // Instance level strict mode
@ -122,14 +122,14 @@ ModelBaseClass.prototype._initProperties = function (data, options) {
writable: true, writable: true,
enumerable: false, enumerable: false,
configurable: true, configurable: true,
value: strict value: strict,
}, },
__persisted: { __persisted: {
writable: true, writable: true,
enumerable: false, enumerable: false,
configurable: true, configurable: true,
value: false value: false,
}, },
}); });
@ -138,7 +138,7 @@ ModelBaseClass.prototype._initProperties = function (data, options) {
writable: true, writable: true,
enumerable: false, enumerable: false,
configrable: true, configrable: true,
value: [] value: [],
}); });
} }
} else { } else {
@ -587,7 +587,7 @@ ModelBaseClass.prototype.inspect = function (depth) {
return util.inspect(this.__data, { return util.inspect(this.__data, {
showHidden: false, showHidden: false,
depth: depth, depth: depth,
colors: false colors: false,
}); });
}; };

View File

@ -108,7 +108,7 @@ ObserverMixin.notifyObserversOf = function(operation, context, callback) {
); );
} }
}, },
function(err) { callback(err, context) } function(err) { callback(err, context); }
); );
}); });
return callback.promise; return callback.promise;

View File

@ -26,7 +26,7 @@ var RelationTypes = {
hasAndBelongsToMany: 'hasAndBelongsToMany', hasAndBelongsToMany: 'hasAndBelongsToMany',
referencesMany: 'referencesMany', referencesMany: 'referencesMany',
embedsOne: 'embedsOne', embedsOne: 'embedsOne',
embedsMany: 'embedsMany' embedsMany: 'embedsMany',
}; };
var RelationClasses = { var RelationClasses = {
@ -37,7 +37,7 @@ var RelationClasses = {
hasAndBelongsToMany: HasAndBelongsToMany, hasAndBelongsToMany: HasAndBelongsToMany,
referencesMany: ReferencesMany, referencesMany: ReferencesMany,
embedsOne: EmbedsOne, embedsOne: EmbedsOne,
embedsMany: EmbedsMany embedsMany: EmbedsMany,
}; };
exports.Relation = Relation; exports.Relation = Relation;
@ -151,7 +151,7 @@ RelationDefinition.prototype.toJSON = function () {
keyFrom: this.keyFrom, keyFrom: this.keyFrom,
modelTo: modelToName, modelTo: modelToName,
keyTo: this.keyTo, keyTo: this.keyTo,
multiple: this.multiple multiple: this.multiple,
}; };
if (this.modelThrough) { if (this.modelThrough) {
json.modelThrough = this.modelThrough.modelName; json.modelThrough = this.modelThrough.modelName;
@ -186,7 +186,7 @@ RelationDefinition.prototype.defineMethod = function(name, fn) {
method = function() { method = function() {
var rel = this[relationName]; var rel = this[relationName];
return rel[name].apply(rel, arguments); return rel[name].apply(rel, arguments);
} };
} }
if (method && fn.shared) { if (method && fn.shared) {
sharedMethod(definition, name, method, fn); sharedMethod(definition, name, method, fn);
@ -623,7 +623,7 @@ RelationDefinition.hasMany = function hasMany(modelFrom, modelTo, params) {
scope: params.scope, scope: params.scope,
options: params.options, options: params.options,
keyThrough: keyThrough, keyThrough: keyThrough,
polymorphic: polymorphic polymorphic: polymorphic,
}); });
definition.modelThrough = params.through; definition.modelThrough = params.through;
@ -641,7 +641,7 @@ RelationDefinition.hasMany = function hasMany(modelFrom, modelTo, params) {
findById: scopeMethod(definition, 'findById'), findById: scopeMethod(definition, 'findById'),
destroy: scopeMethod(definition, 'destroyById'), destroy: scopeMethod(definition, 'destroyById'),
updateById: scopeMethod(definition, 'updateById'), updateById: scopeMethod(definition, 'updateById'),
exists: scopeMethod(definition, 'exists') exists: scopeMethod(definition, 'exists'),
}; };
var findByIdFunc = scopeMethods.findById; var findByIdFunc = scopeMethods.findById;
@ -906,7 +906,7 @@ var throughKeys = function(definition) {
var fk2 = findBelongsTo(modelThrough, definition.modelTo, pk2)[0]; var fk2 = findBelongsTo(modelThrough, definition.modelTo, pk2)[0];
} }
return [fk1, fk2]; return [fk1, fk2];
} };
/** /**
* Find a related item by foreign key * Find a related item by foreign key
@ -1266,7 +1266,7 @@ RelationDefinition.belongsTo = function (modelFrom, modelTo, params) {
scope: params.scope, scope: params.scope,
options: params.options, options: params.options,
polymorphic: polymorphic, polymorphic: polymorphic,
methods: params.methods methods: params.methods,
}); });
// Define a property for the scope so that we have 'this' for the scoped methods // Define a property for the scope so that we have 'this' for the scoped methods
@ -1286,7 +1286,7 @@ RelationDefinition.belongsTo = function (modelFrom, modelTo, params) {
} }
bindRelationMethods(relation, relationMethod, definition); bindRelationMethods(relation, relationMethod, definition);
return relationMethod; return relationMethod;
} },
}); });
// FIXME: [rfeng] Wrap the property into a function for remoting // FIXME: [rfeng] Wrap the property into a function for remoting
@ -1531,7 +1531,7 @@ BelongsTo.prototype.getAsync = function (options, cb) {
cb = cb || utils.createPromiseCallback(); cb = cb || utils.createPromiseCallback();
this.related(true, options, cb); this.related(true, options, cb);
return cb.promise; return cb.promise;
} };
/** /**
@ -1632,7 +1632,7 @@ RelationDefinition.hasOne = function (modelFrom, modelTo, params) {
scope: params.scope, scope: params.scope,
options: params.options, options: params.options,
polymorphic: polymorphic, polymorphic: polymorphic,
methods: params.methods methods: params.methods,
}); });
modelTo.dataSource.defineForeignKey(modelTo.modelName, fk, modelFrom.modelName, pk); modelTo.dataSource.defineForeignKey(modelTo.modelName, fk, modelFrom.modelName, pk);
@ -1643,7 +1643,7 @@ RelationDefinition.hasOne = function (modelFrom, modelTo, params) {
configurable: true, configurable: true,
get: function() { get: function() {
var relation = new HasOne(definition, this); var relation = new HasOne(definition, this);
var relationMethod = relation.related.bind(relation) var relationMethod = relation.related.bind(relation);
relationMethod.getAsync = relation.getAsync.bind(relation); relationMethod.getAsync = relation.getAsync.bind(relation);
relationMethod.create = relation.create.bind(relation); relationMethod.create = relation.create.bind(relation);
relationMethod.build = relation.build.bind(relation); relationMethod.build = relation.build.bind(relation);
@ -1652,7 +1652,7 @@ RelationDefinition.hasOne = function (modelFrom, modelTo, params) {
relationMethod._targetClass = definition.modelTo.modelName; relationMethod._targetClass = definition.modelTo.modelName;
bindRelationMethods(relation, relationMethod, definition); bindRelationMethods(relation, relationMethod, definition);
return relationMethod; return relationMethod;
} },
}); });
// FIXME: [rfeng] Wrap the property into a function for remoting // FIXME: [rfeng] Wrap the property into a function for remoting
@ -1968,7 +1968,7 @@ RelationDefinition.embedsOne = function (modelFrom, modelTo, params) {
scope: params.scope, scope: params.scope,
options: params.options, options: params.options,
embed: true, embed: true,
methods: params.methods methods: params.methods,
}); });
var opts = { type: modelTo }; var opts = { type: modelTo };
@ -2015,7 +2015,7 @@ RelationDefinition.embedsOne = function (modelFrom, modelTo, params) {
relationMethod._targetClass = definition.modelTo.modelName; relationMethod._targetClass = definition.modelTo.modelName;
bindRelationMethods(relation, relationMethod, definition); bindRelationMethods(relation, relationMethod, definition);
return relationMethod; return relationMethod;
} },
}); });
// FIXME: [rfeng] Wrap the property into a function for remoting // FIXME: [rfeng] Wrap the property into a function for remoting
@ -2247,11 +2247,11 @@ RelationDefinition.embedsMany = function embedsMany(modelFrom, modelTo, params)
properties: params.properties, properties: params.properties,
scope: params.scope, scope: params.scope,
options: params.options, options: params.options,
embed: true embed: true,
}); });
modelFrom.dataSource.defineProperty(modelFrom.modelName, propertyName, { modelFrom.dataSource.defineProperty(modelFrom.modelName, propertyName, {
type: [modelTo], default: function() { return []; } type: [modelTo], default: function() { return []; },
}); });
if (typeof modelTo.dataSource.connector.generateId !== 'function') { if (typeof modelTo.dataSource.connector.generateId !== 'function') {
@ -2282,7 +2282,7 @@ RelationDefinition.embedsMany = function embedsMany(modelFrom, modelTo, params)
this.errors.add(propertyName, 'contains duplicate `' + idName + '`', 'uniqueness'); this.errors.add(propertyName, 'contains duplicate `' + idName + '`', 'uniqueness');
err(false); err(false);
} }
}, { code: 'uniqueness' }) }, { code: 'uniqueness' });
} }
// validate all embedded items // validate all embedded items
@ -2325,7 +2325,7 @@ RelationDefinition.embedsMany = function embedsMany(modelFrom, modelTo, params)
set: scopeMethod(definition, 'set'), set: scopeMethod(definition, 'set'),
unset: scopeMethod(definition, 'unset'), unset: scopeMethod(definition, 'unset'),
at: scopeMethod(definition, 'at'), at: scopeMethod(definition, 'at'),
value: scopeMethod(definition, 'embeddedValue') value: scopeMethod(definition, 'embeddedValue'),
}; };
var findByIdFunc = scopeMethods.findById; var findByIdFunc = scopeMethods.findById;
@ -2604,7 +2604,7 @@ EmbedsMany.prototype.destroyAll = function(where, options, cb) {
if (where && Object.keys(where).length > 0) { if (where && Object.keys(where).length > 0) {
var filter = applyFilter({ where: where }); var filter = applyFilter({ where: where });
var reject = function(v) { return !filter(v) }; var reject = function(v) { return !filter(v); };
embeddedList = embeddedList ? embeddedList.filter(reject) : embeddedList; embeddedList = embeddedList ? embeddedList.filter(reject) : embeddedList;
} else { } else {
embeddedList = []; embeddedList = [];
@ -2867,11 +2867,11 @@ RelationDefinition.referencesMany = function referencesMany(modelFrom, modelTo,
multiple: true, multiple: true,
properties: params.properties, properties: params.properties,
scope: params.scope, scope: params.scope,
options: params.options options: params.options,
}); });
modelFrom.dataSource.defineProperty(modelFrom.modelName, fk, { modelFrom.dataSource.defineProperty(modelFrom.modelName, fk, {
type: [idType], default: function() { return []; } type: [idType], default: function() { return []; },
}); });
modelFrom.validate(relationName, function(err) { modelFrom.validate(relationName, function(err) {
@ -2884,7 +2884,7 @@ RelationDefinition.referencesMany = function referencesMany(modelFrom, modelTo,
this.errors.add(relationName, msg, 'uniqueness'); this.errors.add(relationName, msg, 'uniqueness');
err(false); err(false);
} }
}, { code: 'uniqueness' }) }, { code: 'uniqueness' });
var scopeMethods = { var scopeMethods = {
findById: scopeMethod(definition, 'findById'), findById: scopeMethod(definition, 'findById'),
@ -2893,7 +2893,7 @@ RelationDefinition.referencesMany = function referencesMany(modelFrom, modelTo,
exists: scopeMethod(definition, 'exists'), exists: scopeMethod(definition, 'exists'),
add: scopeMethod(definition, 'add'), add: scopeMethod(definition, 'add'),
remove: scopeMethod(definition, 'remove'), remove: scopeMethod(definition, 'remove'),
at: scopeMethod(definition, 'at') at: scopeMethod(definition, 'at'),
}; };
var findByIdFunc = scopeMethods.findById; var findByIdFunc = scopeMethods.findById;
@ -3034,7 +3034,7 @@ ReferencesMany.prototype.exists = function (fkId, options, cb) {
var ids = this.modelInstance[fk] || []; var ids = this.modelInstance[fk] || [];
cb = cb || utils.createPromiseCallback(); cb = cb || utils.createPromiseCallback();
process.nextTick(function() { cb(null, utils.findIndexOf(ids, fkId, idEquals) > -1) }); process.nextTick(function() { cb(null, utils.findIndexOf(ids, fkId, idEquals) > -1); });
return cb.promise; return cb.promise;
}; };

View File

@ -97,7 +97,7 @@ ScopeDefinition.prototype.related = function(receiver, scopeParams, condOrRefres
cb(null, self.__cachedRelations[name]); cb(null, self.__cachedRelations[name]);
} }
return cb.promise; return cb.promise;
} };
/** /**
* Define a scope method * Define a scope method
@ -106,7 +106,7 @@ ScopeDefinition.prototype.related = function(receiver, scopeParams, condOrRefres
*/ */
ScopeDefinition.prototype.defineMethod = function(name, fn) { ScopeDefinition.prototype.defineMethod = function(name, fn) {
return this.methods[name] = fn; return this.methods[name] = fn;
} };
/** /**
* Define a scope to the class * Define a scope to the class
@ -143,7 +143,7 @@ function defineScope(cls, targetClass, name, params, methods, options) {
name: name, name: name,
params: params, params: params,
methods: methods, methods: methods,
options: options options: options,
}); });
if (isStatic) { if (isStatic) {
@ -192,7 +192,7 @@ function defineScope(cls, targetClass, name, params, methods, options) {
cb = options; cb = options;
options = {}; options = {};
} }
options = options || {} options = options || {};
// Check if there is a through model // Check if there is a through model
// see https://github.com/strongloop/loopback/issues/1076 // see https://github.com/strongloop/loopback/issues/1076
if (f._scope.collect && if (f._scope.collect &&
@ -208,7 +208,7 @@ function defineScope(cls, targetClass, name, params, methods, options) {
// the target model // the target model
f._scope.include = { f._scope.include = {
relation: f._scope.collect, relation: f._scope.collect,
scope: condOrRefresh scope: condOrRefresh,
}; };
condOrRefresh = {}; condOrRefresh = {};
} }
@ -237,9 +237,9 @@ function defineScope(cls, targetClass, name, params, methods, options) {
cb = options; cb = options;
options = {}; options = {};
} }
options = options || {} options = options || {};
return definition.related(self, f._scope, condOrRefresh, options, cb); return definition.related(self, f._scope, condOrRefresh, options, cb);
} };
f.build = build; f.build = build;
f.create = create; f.create = create;
@ -265,11 +265,11 @@ function defineScope(cls, targetClass, name, params, methods, options) {
get: function() { get: function() {
mergeQuery(f._scope, targetModel._scopeMeta[name]); mergeQuery(f._scope, targetModel._scopeMeta[name]);
return f; return f;
} },
}); });
}.bind(self)); }.bind(self));
return f; return f;
} },
}); });
// Wrap the property into a function for remoting // Wrap the property into a function for remoting

View File

@ -78,7 +78,7 @@ TransactionMixin.beginTransaction = function(options, cb) {
setTimeout(function() { setTimeout(function() {
var context = { var context = {
transaction: transaction, transaction: transaction,
operation: 'timeout' operation: 'timeout',
}; };
transaction.notifyObserversOf('timeout', context, function(err) { transaction.notifyObserversOf('timeout', context, function(err) {
if (!err) { if (!err) {
@ -121,7 +121,7 @@ if (Transaction) {
} }
var context = { var context = {
transaction: self, transaction: self,
operation: 'commit' operation: 'commit',
}; };
function work(done) { function work(done) {
@ -155,7 +155,7 @@ if (Transaction) {
} }
var context = { var context = {
transaction: self, transaction: self,
operation: 'rollback' operation: 'rollback',
}; };
function work(done) { function work(done) {

View File

@ -135,7 +135,7 @@ function convertToArray(include) {
if (typeof includeEntry === 'string') { if (typeof includeEntry === 'string') {
var obj = {}; var obj = {};
obj[includeEntry] = true; obj[includeEntry] = true;
normalized.push(obj) normalized.push(obj);
} }
else { else {
normalized.push(includeEntry); normalized.push(includeEntry);
@ -430,7 +430,7 @@ function defineCachedRelations(obj) {
writable: true, writable: true,
enumerable: false, enumerable: false,
configurable: true, configurable: true,
value: {} value: {},
}); });
} }
} }

View File

@ -292,7 +292,7 @@ function validateInclusion(attr, conf, err) {
if (nullCheck.call(this, attr, conf, err)) return; if (nullCheck.call(this, attr, conf, err)) return;
if (!~conf.in.indexOf(this[attr])) { if (!~conf.in.indexOf(this[attr])) {
err() err();
} }
} }
@ -303,7 +303,7 @@ function validateExclusion(attr, conf, err) {
if (nullCheck.call(this, attr, conf, err)) return; if (nullCheck.call(this, attr, conf, err)) return;
if (~conf.in.indexOf(this[attr])) { if (~conf.in.indexOf(this[attr])) {
err() err();
} }
} }
@ -372,7 +372,7 @@ var validators = {
exclusion: validateExclusion, exclusion: validateExclusion,
format: validateFormat, format: validateFormat,
custom: validateCustom, custom: validateCustom,
uniqueness: validateUniqueness uniqueness: validateUniqueness,
}; };
function getConfigurator(name, opts) { function getConfigurator(name, opts) {
@ -438,7 +438,7 @@ Validatable.prototype.isValid = function (callback, data) {
Object.defineProperty(this, 'errors', { Object.defineProperty(this, 'errors', {
enumerable: false, enumerable: false,
configurable: true, configurable: true,
value: new Errors value: new Errors,
}); });
this.trigger('validate', function(validationsDone) { this.trigger('validate', function(validationsDone) {
@ -511,7 +511,7 @@ function cleanErrors(inst) {
Object.defineProperty(inst, 'errors', { Object.defineProperty(inst, 'errors', {
enumerable: false, enumerable: false,
configurable: true, configurable: true,
value: false value: false,
}); });
} }
@ -593,19 +593,19 @@ var defaultMessages = {
length: { length: {
min: 'too short', min: 'too short',
max: 'too long', max: 'too long',
is: 'length is wrong' is: 'length is wrong',
}, },
common: { common: {
blank: 'is blank', blank: 'is blank',
'null': 'is null' 'null': 'is null',
}, },
numericality: { numericality: {
'int': 'is not an integer', 'int': 'is not an integer',
'number': 'is not a number' 'number': 'is not a number',
}, },
inclusion: 'is not included in the list', inclusion: 'is not included in the list',
exclusion: 'is reserved', exclusion: 'is reserved',
uniqueness: 'is not unique' uniqueness: 'is not unique',
}; };
function nullCheck(attr, conf, err) { function nullCheck(attr, conf, err) {
@ -647,7 +647,7 @@ function configure(cls, validation, args, opts) {
writable: true, writable: true,
configurable: true, configurable: true,
enumerable: false, enumerable: false,
value: {} value: {},
}); });
} }
args = [].slice.call(args); args = [].slice.call(args);
@ -675,7 +675,7 @@ function Errors() {
Object.defineProperty(this, 'codes', { Object.defineProperty(this, 'codes', {
enumerable: false, enumerable: false,
configurable: true, configurable: true,
value: {} value: {},
}); });
} }
@ -763,7 +763,7 @@ function ValidationError(obj) {
this.details = { this.details = {
context: context, context: context,
codes: obj.errors && obj.errors.codes, codes: obj.errors && obj.errors.codes,
messages: obj.errors messages: obj.errors,
}; };
if (Error.captureStackTrace) { if (Error.captureStackTrace) {
@ -813,7 +813,7 @@ function formatPropertyError(propertyName, propertyValue, errorMessage) {
showHidden: false, showHidden: false,
color: false, color: false,
// show top-level object properties only // show top-level object properties only
depth: Array.isArray(propertyValue) ? 1 : 0 depth: Array.isArray(propertyValue) ? 1 : 0,
}); });
formattedValue = truncatePropertyString(formattedValue); formattedValue = truncatePropertyString(formattedValue);
} else { } else {

View File

@ -17,12 +17,12 @@ var Memory = require('../lib/connectors/memory').Memory;
var HOOK_NAMES = [ var HOOK_NAMES = [
'access', 'access',
'before save', 'persist', 'after save', 'before save', 'persist', 'after save',
'before delete', 'after delete' 'before delete', 'after delete',
]; ];
var dataSources = [ var dataSources = [
createOptimizedDataSource(), createOptimizedDataSource(),
createUnoptimizedDataSource() createUnoptimizedDataSource(),
]; ];
var observedContexts = []; var observedContexts = [];
@ -134,7 +134,7 @@ function setupTestModels() {
var TestModel = ds.TestModel = ds.createModel('TestModel', { var 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 },
}); });
}); });
return Promise.resolve(); return Promise.resolve();
@ -155,7 +155,7 @@ function runner(fn) {
observedContexts.push({ observedContexts.push({
operation: fn.name, operation: fn.name,
connector: ds.name, connector: ds.name,
hooks: {} hooks: {},
}); });
return fn(ds); return fn(ds);
}); });
@ -171,11 +171,11 @@ function resetStorage(ds) {
}); });
return TestModel.deleteAll() return TestModel.deleteAll()
.then(function() { .then(function() {
return TestModel.create({ name: 'first' }) return TestModel.create({ name: 'first' });
}) })
.then(function(instance) { .then(function(instance) {
// Look it up from DB so that default values are retrieved // Look it up from DB so that default values are retrieved
return TestModel.findById(instance.id) return TestModel.findById(instance.id);
}) })
.then(function(instance) { .then(function(instance) {
ds.existingInstance = instance; ds.existingInstance = instance;
@ -193,7 +193,7 @@ function resetStorage(ds) {
} }
function report() { function report() {
console.log('<style>') console.log('<style>');
console.log('td { font-family: "monospace": }'); console.log('td { font-family: "monospace": }');
console.log('td, th {'); console.log('td, th {');
console.log(' vertical-align: text-top;'); console.log(' vertical-align: text-top;');

View File

@ -13,23 +13,23 @@ describe('Datasource-specific field types for foreign keys', function () {
before(function() { before(function() {
ds = new DataSource('memory'); ds = new DataSource('memory');
Item = ds.define('Item', { Item = ds.define('Item', {
"myProp": { 'myProp': {
"id": true, 'id': true,
"type": "string", 'type': 'string',
"memory": { 'memory': {
"dataType": "string" 'dataType': 'string',
} },
} },
}); });
Variant = ds.define('Variant', {}, { Variant = ds.define('Variant', {}, {
relations: { relations: {
"item": { 'item': {
"type": "belongsTo", 'type': 'belongsTo',
"as": "item", 'as': 'item',
"model": "Item", 'model': 'Item',
"foreignKey": "myProp" 'foreignKey': 'myProp',
} },
} },
}); });
}); });
@ -38,7 +38,7 @@ describe('Datasource-specific field types for foreign keys', function () {
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);
VariantDefinition.properties.myProp.memory.dataType.should.be.equal("string"); VariantDefinition.properties.myProp.memory.dataType.should.be.equal('string');
done(); done();
}); });
}) })

View File

@ -160,7 +160,7 @@ describe('async observer', function() {
it('passes context to final callback', function(done) { it('passes context to final callback', function(done) {
var context = {}; var 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();
}); });
}); });

View File

@ -19,7 +19,7 @@ describe('basic-querying', function () {
birthday: { type: Date, index: true }, birthday: { type: Date, index: true },
role: { type: String, index: true }, role: { type: String, index: true },
order: { type: Number, index: true, sort: true }, order: { type: Number, index: true, sort: true },
vip: {type: Boolean} vip: { type: Boolean },
}); });
db.automigrate(done); db.automigrate(done);
@ -73,7 +73,7 @@ describe('basic-querying', function () {
{ name: 'c' }, { name: 'c' },
{ name: 'd', vip: true }, { name: 'd', vip: true },
{ name: 'e' }, { name: 'e' },
{ name: 'f' } { name: 'f' },
]; ];
db.automigrate(['User'], function(err) { db.automigrate(['User'], function(err) {
User.create(people, function(err, users) { User.create(people, function(err, users) {
@ -223,7 +223,7 @@ describe('basic-querying', function () {
it('should support "and" operator that is satisfied', function(done) { it('should support "and" operator that is satisfied', function(done) {
User.find({ where: { and: [ User.find({ where: { and: [
{ name: 'John Lennon' }, { name: 'John Lennon' },
{role: 'lead'} { role: 'lead' },
] }}, function(err, users) { ] }}, function(err, users) {
should.not.exist(err); should.not.exist(err);
users.should.have.property('length', 1); users.should.have.property('length', 1);
@ -234,7 +234,7 @@ describe('basic-querying', function () {
it('should support "and" operator that is not satisfied', function(done) { it('should support "and" operator that is not satisfied', function(done) {
User.find({ where: { and: [ User.find({ where: { and: [
{ name: 'John Lennon' }, { name: 'John Lennon' },
{role: 'member'} { role: 'member' },
] }}, function(err, users) { ] }}, function(err, users) {
should.not.exist(err); should.not.exist(err);
users.should.have.property('length', 0); users.should.have.property('length', 0);
@ -245,7 +245,7 @@ describe('basic-querying', function () {
it('should support "or" that is satisfied', function(done) { it('should support "or" that is satisfied', function(done) {
User.find({ where: { or: [ User.find({ where: { or: [
{ name: 'John Lennon' }, { name: 'John Lennon' },
{role: 'lead'} { role: 'lead' },
] }}, 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);
@ -256,7 +256,7 @@ describe('basic-querying', function () {
it('should support "or" operator that is not satisfied', function(done) { it('should support "or" operator that is not satisfied', function(done) {
User.find({ where: { or: [ User.find({ where: { or: [
{ name: 'XYZ' }, { name: 'XYZ' },
{role: 'Hello1'} { role: 'Hello1' },
] }}, function(err, users) { ] }}, function(err, users) {
should.not.exist(err); should.not.exist(err);
users.should.have.property('length', 0); users.should.have.property('length', 0);
@ -265,7 +265,7 @@ describe('basic-querying', function () {
}); });
it('should support date "gte" that is satisfied', function(done) { it('should support date "gte" that is satisfied', function(done) {
User.find({order: 'seq', where: { birthday: { "gte": new Date('1980-12-08') } User.find({ order: 'seq', where: { birthday: { 'gte': new Date('1980-12-08') },
}}, function(err, users) { }}, function(err, users) {
should.not.exist(err); should.not.exist(err);
users.should.have.property('length', 1); users.should.have.property('length', 1);
@ -275,7 +275,7 @@ describe('basic-querying', function () {
}); });
it('should support date "gt" that is not satisfied', function(done) { it('should support date "gt" that is not satisfied', function(done) {
User.find({order: 'seq', where: { birthday: { "gt": new Date('1980-12-08') } User.find({ order: 'seq', where: { birthday: { 'gt': new Date('1980-12-08') },
}}, function(err, users) { }}, function(err, users) {
should.not.exist(err); should.not.exist(err);
users.should.have.property('length', 0); users.should.have.property('length', 0);
@ -284,7 +284,7 @@ describe('basic-querying', function () {
}); });
it('should support date "gt" that is satisfied', function(done) { it('should support date "gt" that is satisfied', function(done) {
User.find({order: 'seq', where: { birthday: { "gt": new Date('1980-12-07') } User.find({ order: 'seq', where: { birthday: { 'gt': new Date('1980-12-07') },
}}, function(err, users) { }}, function(err, users) {
should.not.exist(err); should.not.exist(err);
users.should.have.property('length', 1); users.should.have.property('length', 1);
@ -294,7 +294,7 @@ describe('basic-querying', function () {
}); });
it('should support date "lt" that is satisfied', function(done) { it('should support date "lt" that is satisfied', function(done) {
User.find({order: 'seq', where: { birthday: { "lt": new Date('1980-12-07') } User.find({ order: 'seq', where: { birthday: { 'lt': new Date('1980-12-07') },
}}, function(err, users) { }}, function(err, users) {
should.not.exist(err); should.not.exist(err);
users.should.have.property('length', 1); users.should.have.property('length', 1);
@ -304,7 +304,7 @@ describe('basic-querying', function () {
}); });
it('should support number "gte" that is satisfied', function(done) { it('should support number "gte" that is satisfied', function(done) {
User.find({order: 'seq', where: { order: { "gte": 3} User.find({ order: 'seq', where: { order: { 'gte': 3 },
}}, function(err, users) { }}, function(err, users) {
should.not.exist(err); should.not.exist(err);
users.should.have.property('length', 4); users.should.have.property('length', 4);
@ -314,7 +314,7 @@ describe('basic-querying', function () {
}); });
it('should support number "gt" that is not satisfied', function(done) { it('should support number "gt" that is not satisfied', function(done) {
User.find({order: 'seq', where: { order: { "gt": 6 } User.find({ order: 'seq', where: { order: { 'gt': 6 },
}}, function(err, users) { }}, function(err, users) {
should.not.exist(err); should.not.exist(err);
users.should.have.property('length', 0); users.should.have.property('length', 0);
@ -323,7 +323,7 @@ describe('basic-querying', function () {
}); });
it('should support number "gt" that is satisfied', function(done) { it('should support number "gt" that is satisfied', function(done) {
User.find({order: 'seq', where: { order: { "gt": 5 } User.find({ order: 'seq', where: { order: { 'gt': 5 },
}}, function(err, users) { }}, function(err, users) {
should.not.exist(err); should.not.exist(err);
users.should.have.property('length', 1); users.should.have.property('length', 1);
@ -333,7 +333,7 @@ describe('basic-querying', function () {
}); });
it('should support number "lt" that is satisfied', function(done) { it('should support number "lt" that is satisfied', function(done) {
User.find({order: 'seq', where: { order: { "lt": 2 } User.find({ order: 'seq', where: { order: { 'lt': 2 },
}}, function(err, users) { }}, function(err, users) {
should.not.exist(err); should.not.exist(err);
users.should.have.property('length', 1); users.should.have.property('length', 1);
@ -343,7 +343,7 @@ describe('basic-querying', function () {
}); });
it('should support number "gt" that is satisfied by null value', function(done) { it('should support number "gt" that is satisfied by null value', function(done) {
User.find({order: 'seq', where: { order: { "gt": null } User.find({ order: 'seq', where: { order: { 'gt': null },
}}, function(err, users) { }}, function(err, users) {
should.not.exist(err); should.not.exist(err);
users.should.have.property('length', 0); users.should.have.property('length', 0);
@ -352,7 +352,7 @@ describe('basic-querying', function () {
}); });
it('should support number "lt" that is not satisfied by null value', function(done) { it('should support number "lt" that is not satisfied by null value', function(done) {
User.find({order: 'seq', where: { order: { "lt": null } User.find({ order: 'seq', where: { order: { 'lt': null },
}}, function(err, users) { }}, function(err, users) {
should.not.exist(err); should.not.exist(err);
users.should.have.property('length', 0); users.should.have.property('length', 0);
@ -361,7 +361,7 @@ describe('basic-querying', function () {
}); });
it('should support string "gte" that is satisfied by null value', function(done) { it('should support string "gte" that is satisfied by null value', function(done) {
User.find({order: 'seq', where: { name: { "gte": null} User.find({ order: 'seq', where: { name: { 'gte': null },
}}, function(err, users) { }}, function(err, users) {
should.not.exist(err); should.not.exist(err);
users.should.have.property('length', 0); users.should.have.property('length', 0);
@ -370,7 +370,7 @@ describe('basic-querying', function () {
}); });
it('should support string "gte" that is satisfied', function(done) { it('should support string "gte" that is satisfied', function(done) {
User.find({order: 'seq', where: { name: { "gte": 'Paul McCartney'} User.find({ order: 'seq', where: { name: { 'gte': 'Paul McCartney' },
}}, function(err, users) { }}, function(err, users) {
should.not.exist(err); should.not.exist(err);
users.should.have.property('length', 4); users.should.have.property('length', 4);
@ -380,7 +380,7 @@ describe('basic-querying', function () {
}); });
it('should support string "gt" that is not satisfied', function(done) { it('should support string "gt" that is not satisfied', function(done) {
User.find({order: 'seq', where: { name: { "gt": 'xyz' } User.find({ order: 'seq', where: { name: { 'gt': 'xyz' },
}}, function(err, users) { }}, function(err, users) {
should.not.exist(err); should.not.exist(err);
users.should.have.property('length', 0); users.should.have.property('length', 0);
@ -389,7 +389,7 @@ describe('basic-querying', function () {
}); });
it('should support string "gt" that is satisfied', function(done) { it('should support string "gt" that is satisfied', function(done) {
User.find({order: 'seq', where: { name: { "gt": 'Paul McCartney' } User.find({ order: 'seq', where: { name: { 'gt': 'Paul McCartney' },
}}, 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);
@ -399,7 +399,7 @@ describe('basic-querying', function () {
}); });
it('should support string "lt" that is satisfied', function(done) { it('should support string "lt" that is satisfied', function(done) {
User.find({order: 'seq', where: { name: { "lt": 'Paul McCartney' } User.find({ order: 'seq', where: { name: { 'lt': 'Paul McCartney' },
}}, 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);
@ -409,7 +409,7 @@ describe('basic-querying', function () {
}); });
it('should support boolean "gte" that is satisfied', function(done) { it('should support boolean "gte" that is satisfied', function(done) {
User.find({order: 'seq', where: { vip: { "gte": true} User.find({ order: 'seq', where: { vip: { 'gte': true },
}}, 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);
@ -419,7 +419,7 @@ describe('basic-querying', function () {
}); });
it('should support boolean "gt" that is not satisfied', function(done) { it('should support boolean "gt" that is not satisfied', function(done) {
User.find({order: 'seq', where: { vip: { "gt": true } User.find({ order: 'seq', where: { vip: { 'gt': true },
}}, function(err, users) { }}, function(err, users) {
should.not.exist(err); should.not.exist(err);
users.should.have.property('length', 0); users.should.have.property('length', 0);
@ -428,7 +428,7 @@ describe('basic-querying', function () {
}); });
it('should support boolean "gt" that is satisfied', function(done) { it('should support boolean "gt" that is satisfied', function(done) {
User.find({order: 'seq', where: { vip: { "gt": false } User.find({ order: 'seq', where: { vip: { 'gt': false },
}}, 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);
@ -438,7 +438,7 @@ describe('basic-querying', function () {
}); });
it('should support boolean "lt" that is satisfied', function(done) { it('should support boolean "lt" that is satisfied', function(done) {
User.find({order: 'seq', where: { vip: { "lt": true } User.find({ order: 'seq', where: { vip: { 'lt': true },
}}, 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);
@ -482,8 +482,8 @@ describe('basic-querying', function () {
}); });
}); });
}); });
} },
} };
} }
sample({ name: true }).expect(['name']); sample({ name: true }).expect(['name']);
@ -558,7 +558,7 @@ describe('basic-querying', function () {
it('should find last record in filtered set', function(done) { it('should find last record in filtered set', function(done) {
User.findOne({ User.findOne({
where: { role: 'lead' }, where: { role: 'lead' },
order: 'order DESC' order: 'order DESC',
}, function(e, u) { }, function(e, u) {
should.not.exist(e); should.not.exist(e);
should.exist(u); should.exist(u);
@ -632,9 +632,9 @@ describe.skip('queries', function() {
var db = getSchema(); var db = getSchema();
Todo = db.define('Todo', { Todo = db.define('Todo', {
id: false, id: false,
content: {type: 'string'} content: { type: 'string' },
}, { }, {
idInjection: false idInjection: false,
}); });
db.automigrate(['Todo'], done); db.automigrate(['Todo'], done);
}); });
@ -643,7 +643,7 @@ describe.skip('queries', function() {
Todo.create([ Todo.create([
{ content: 'Buy eggs' }, { content: 'Buy eggs' },
{ content: 'Buy milk' }, { content: 'Buy milk' },
{content: 'Buy sausages'} { content: 'Buy sausages' },
], done); ], done);
}); });
}); });
@ -803,7 +803,7 @@ function seed(done) {
role: 'lead', role: 'lead',
birthday: new Date('1980-12-08'), birthday: new Date('1980-12-08'),
order: 2, order: 2,
vip: true vip: true,
}, },
{ {
seq: 1, seq: 1,
@ -812,18 +812,18 @@ function seed(done) {
role: 'lead', role: 'lead',
birthday: new Date('1942-06-18'), birthday: new Date('1942-06-18'),
order: 1, order: 1,
vip: true vip: true,
}, },
{ seq: 2, name: 'George Harrison', order: 5, vip: false }, { seq: 2, name: 'George Harrison', order: 5, vip: false },
{ seq: 3, name: 'Ringo Starr', order: 6, vip: false }, { seq: 3, name: 'Ringo Starr', order: 6, vip: false },
{ seq: 4, name: 'Pete Best', order: 4 }, { seq: 4, name: 'Pete Best', order: 4 },
{seq: 5, name: 'Stuart Sutcliffe', order: 3, vip: true} { seq: 5, name: 'Stuart Sutcliffe', order: 3, vip: true },
]; ];
async.series([ async.series([
User.destroyAll.bind(User), User.destroyAll.bind(User),
function(cb) { function(cb) {
async.each(beatles, User.create.bind(User), cb); async.each(beatles, User.create.bind(User), cb);
} },
], done); ], done);
} }

View File

@ -59,14 +59,14 @@ Object.defineProperty(module.exports, 'it', {
writable: true, writable: true,
enumerable: false, enumerable: false,
configurable: true, configurable: true,
value: it value: it,
}); });
Object.defineProperty(module.exports, 'skip', { Object.defineProperty(module.exports, 'skip', {
writable: true, writable: true,
enumerable: false, enumerable: false,
configurable: true, configurable: true,
value: skip value: skip,
}); });
function clearAndCreate(model, data, callback) { function clearAndCreate(model, data, callback) {
@ -104,23 +104,23 @@ function testOrm(dataSource) {
approved: Boolean, approved: Boolean,
joinedAt: Date, joinedAt: Date,
age: Number, age: Number,
passwd: { type: String, index: true } passwd: { type: String, index: true },
}); });
Dog = dataSource.define('Dog', { Dog = dataSource.define('Dog', {
name: { type: String, limit: 64, allowNull: false } name: { type: String, limit: 64, allowNull: false },
}); });
Log = dataSource.define('Log', { Log = dataSource.define('Log', {
ownerId: { type: Number, allowNull: true }, ownerId: { type: Number, allowNull: true },
name: { type: String, limit: 64, allowNull: false } name: { type: String, limit: 64, allowNull: false },
}); });
Log.belongsTo(Dog, { as: 'owner', foreignKey: 'ownerId' }); Log.belongsTo(Dog, { as: 'owner', foreignKey: 'ownerId' });
dataSource.extendModel('User', { dataSource.extendModel('User', {
settings: { type: Schema.JSON }, settings: { type: Schema.JSON },
extra: Object extra: Object,
}); });
var newuser = new User({ settings: { hey: 'you' }}); var newuser = new User({ settings: { hey: 'you' }});
@ -131,11 +131,11 @@ function testOrm(dataSource) {
subject: { type: String }, subject: { type: String },
content: { type: Text }, content: { type: Text },
date: { type: Date, default: function() { date: { type: Date, default: function() {
return new Date return new Date;
}, index: true }, }, index: true },
published: { type: Boolean, default: false, index: true }, published: { type: Boolean, default: false, index: true },
likes: [], likes: [],
related: [RelatedPost] related: [RelatedPost],
}, { table: 'posts' }); }, { table: 'posts' });
function RelatedPost() { function RelatedPost() {
@ -171,7 +171,7 @@ function testOrm(dataSource) {
// post.author(user) -- setter when called with object // post.author(user) -- setter when called with object
Passport = dataSource.define('Passport', { Passport = dataSource.define('Passport', {
number: String number: String,
}); });
Passport.belongsTo(User, { as: 'owner', foreignKey: 'ownerId' }); Passport.belongsTo(User, { as: 'owner', foreignKey: 'ownerId' });
@ -224,7 +224,7 @@ function testOrm(dataSource) {
Post.create({ Post.create({
title: title, title: title,
date: date date: date,
}, function(err, obj) { }, function(err, obj) {
test.ok(obj.id, 'Object id should present'); test.ok(obj.id, 'Object id should present');
test.equals(obj.title, title); test.equals(obj.title, title);
@ -258,7 +258,7 @@ function testOrm(dataSource) {
Post.create({ Post.create({
title: title, title: title,
date: date date: date,
}, function(err, obj) { }, function(err, obj) {
test.ok(obj.id); test.ok(obj.id);
test.equals(obj.title, title); test.equals(obj.title, title);
@ -597,12 +597,12 @@ function testOrm(dataSource) {
it('should handle ORDER clause', function(test) { it('should handle ORDER clause', function(test) {
var titles = [ var 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' },
{ title: 'Title A', subject: "A" }, { title: 'Title A', subject: 'A' },
{ 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'; var isRedis = Post.dataSource.name === 'redis';
var dates = isRedis ? [5, 9, 0, 17, 10, 9] : [ var dates = isRedis ? [5, 9, 0, 17, 10, 9] : [
@ -611,7 +611,7 @@ function testOrm(dataSource) {
new Date(1000 * 0), new Date(1000 * 0),
new Date(1000 * 17), new Date(1000 * 17),
new Date(1000 * 10), new Date(1000 * 10),
new Date(1000 * 9) new Date(1000 * 9),
]; ];
titles.forEach(function(t, i) { titles.forEach(function(t, i) {
Post.create({ title: t.title, subject: t.subject, date: dates[i] }, done); Post.create({ title: t.title, subject: t.subject, date: dates[i] }, done);
@ -697,28 +697,28 @@ function testOrm(dataSource) {
function doMultipleSortTest() { function doMultipleSortTest() {
tests += 1; tests += 1;
Post.all({order: "title ASC, subject ASC"}, function (err, posts) { Post.all({ order: 'title ASC, subject ASC' }, function(err, posts) {
if (err) console.log(err); if (err) console.log(err);
test.equal(posts.length, 6); test.equal(posts.length, 6);
test.equal(posts[0].title, "Title A"); test.equal(posts[0].title, 'Title A');
test.equal(posts[0].subject, "A"); test.equal(posts[0].subject, 'A');
test.equal(posts[1].title, "Title A"); test.equal(posts[1].title, 'Title A');
test.equal(posts[1].subject, "B"); test.equal(posts[1].subject, 'B');
test.equal(posts[5].title, "Title Z"); test.equal(posts[5].title, 'Title Z');
finished(); finished();
}); });
} }
function doMultipleReverseSortTest() { function doMultipleReverseSortTest() {
tests += 1; tests += 1;
Post.all({order: "title ASC, subject DESC"}, function (err, posts) { Post.all({ order: 'title ASC, subject DESC' }, function(err, posts) {
if (err) console.log(err); if (err) console.log(err);
test.equal(posts.length, 6); test.equal(posts.length, 6);
test.equal(posts[0].title, "Title A"); test.equal(posts[0].title, 'Title A');
test.equal(posts[0].subject, "B"); test.equal(posts[0].subject, 'B');
test.equal(posts[1].title, "Title A"); test.equal(posts[1].title, 'Title A');
test.equal(posts[1].subject, "A"); test.equal(posts[1].subject, 'A');
test.equal(posts[5].title, "Title Z"); test.equal(posts[5].title, 'Title Z');
finished(); finished();
}); });
} }
@ -886,7 +886,7 @@ function testOrm(dataSource) {
'tin@hcompany.com', 'tin@hcompany.com',
'mike@hcompany.com', 'mike@hcompany.com',
'susan@hcompany.com', 'susan@hcompany.com',
'test@hcompany.com' 'test@hcompany.com',
]; ];
User.destroyAll(function() { User.destroyAll(function() {
emails.forEach(function(email) { emails.forEach(function(email) {
@ -1027,7 +1027,7 @@ function testOrm(dataSource) {
var newData = { var 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)',
}; };
Post.updateOrCreate(newData, function(err, updatedPost) { Post.updateOrCreate(newData, function(err, updatedPost) {
if (err) throw err; if (err) throw err;

View File

@ -19,7 +19,7 @@ describe('crud-with-options', function () {
birthday: { type: Date, index: true }, birthday: { type: Date, index: true },
role: { type: String, index: true }, role: { type: String, index: true },
order: { type: Number, index: true, sort: true }, order: { type: Number, index: true, sort: true },
vip: {type: Boolean} vip: { type: Boolean },
}); });
options = {}; options = {};
filter = { fields: ['name', 'id'] }; filter = { fields: ['name', 'id'] };
@ -198,7 +198,7 @@ describe('crud-with-options', function () {
{ id: 3, name: 'c' }, { id: 3, name: 'c' },
{ id: 4, name: 'd', vip: true }, { id: 4, name: 'd', vip: true },
{ id: 5, name: 'e' }, { id: 5, name: 'e' },
{ id: 6, name: 'f' } { id: 6, name: 'f' },
]; ];
// Use automigrate so that serial keys are 1-6 // Use automigrate so that serial keys are 1-6
db.automigrate(['User'], function(err) { db.automigrate(['User'], function(err) {
@ -547,7 +547,7 @@ function seed(done) {
role: 'lead', role: 'lead',
birthday: new Date('1980-12-08'), birthday: new Date('1980-12-08'),
order: 2, order: 2,
vip: true vip: true,
}, },
{ {
seq: 1, seq: 1,
@ -556,18 +556,18 @@ function seed(done) {
role: 'lead', role: 'lead',
birthday: new Date('1942-06-18'), birthday: new Date('1942-06-18'),
order: 1, order: 1,
vip: true vip: true,
}, },
{ seq: 2, name: 'George Harrison', order: 5, vip: false }, { seq: 2, name: 'George Harrison', order: 5, vip: false },
{ seq: 3, name: 'Ringo Starr', order: 6, vip: false }, { seq: 3, name: 'Ringo Starr', order: 6, vip: false },
{ seq: 4, name: 'Pete Best', order: 4 }, { seq: 4, name: 'Pete Best', order: 4 },
{seq: 5, name: 'Stuart Sutcliffe', order: 3, vip: true} { seq: 5, name: 'Stuart Sutcliffe', order: 3, vip: true },
]; ];
async.series([ async.series([
User.destroyAll.bind(User), User.destroyAll.bind(User),
function(cb) { function(cb) {
async.each(beatles, User.create.bind(User), cb); async.each(beatles, User.create.bind(User), cb);
} },
], done); ], done);
} }

View File

@ -19,7 +19,7 @@ describe('DataSource', function() {
// this is what LoopBack does // this is what LoopBack does
return new DataSource({ return new DataSource({
name: 'dsname', name: 'dsname',
connector: throwingConnector connector: throwingConnector,
}); });
}).should.throw(/loopback-connector-throwing/); }).should.throw(/loopback-connector-throwing/);
}); });

View File

@ -21,7 +21,7 @@ describe('datatypes', function () {
bool: Boolean, bool: Boolean,
list: { type: [String] }, list: { type: [String] },
arr: Array, arr: Array,
nested: Nested nested: Nested,
}); });
db.automigrate(['Model'], done); db.automigrate(['Model'], done);
}); });
@ -29,7 +29,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', { var myModel = db.define('myModel', {
list: { type: ['object'] } list: { type: ['object'] },
}); });
(function() { (function() {
@ -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', { var myModel = db.define('myModel', {
list: { type: ['object'] } list: { type: ['object'] },
}); });
(function() { (function() {
@ -56,7 +56,7 @@ describe('datatypes', function () {
var d = new Date, id; var d = new Date, 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'],
}, function(err, m) { }, function(err, m) {
should.not.exists(err); should.not.exists(err);
should.exist(m && m.id); should.exist(m && m.id);
@ -127,7 +127,7 @@ describe('datatypes', function () {
// update using updateAttributes // update using updateAttributes
m.updateAttributes({ m.updateAttributes({
id: m.id, num: '10' id: m.id, num: '10',
}, function(err, m) { }, function(err, m) {
should.not.exist(err); should.not.exist(err);
m.num.should.be.type('number'); m.num.should.be.type('number');
@ -162,7 +162,7 @@ describe('datatypes', function () {
function(done) { function(done) {
db = getSchema(); db = getSchema();
Model = db.define('RequiredNumber', { Model = db.define('RequiredNumber', {
num: { type: Number, required: true } num: { type: Number, required: true },
}); });
db.automigrate(['Model'], function() { db.automigrate(['Model'], function() {
Model.create({ num: [1, 2, 3] }, function(err, inst) { Model.create({ num: [1, 2, 3] }, function(err, inst) {
@ -180,10 +180,10 @@ describe('datatypes', function () {
'TestModel', 'TestModel',
{ {
desc: { type: String, required: false }, desc: { type: String, required: false },
stars: { type: Number, required: false } stars: { type: Number, required: false },
}, },
{ {
persistUndefinedAsNull: true persistUndefinedAsNull: true,
}); });
isStrict = TestModel.definition.settings.strict; isStrict = TestModel.definition.settings.strict;
@ -294,7 +294,7 @@ describe('datatypes', function () {
inst.__data.dx = undefined; inst.__data.dx = undefined;
inst.toObject(false).should.have.properties({ inst.toObject(false).should.have.properties({
desc: null, stars: null, extra: null, dx: null desc: null, stars: null, extra: null, dx: null,
}); });
}); });
}); });

View File

@ -46,7 +46,7 @@ var setupProducts = function(ids, done) {
ids.widgetB = inst.id; ids.widgetB = inst.id;
next(); next();
}); });
} },
], done); ], done);
}; };
@ -56,17 +56,17 @@ describe('default scope', function () {
db = getSchema(); db = getSchema();
Category = db.define('Category', { Category = db.define('Category', {
name: String name: String,
}); });
Product = db.define('Product', { Product = db.define('Product', {
name: String, name: String,
kind: String, kind: String,
description: String, description: String,
active: { type: Boolean, default: true } active: { type: Boolean, default: true },
}, { }, {
scope: { order: 'name' }, scope: { order: 'name' },
scopes: { active: { where: { active: true } } } scopes: { active: { where: { active: true }}},
}); });
Product.lookupModel = function(data) { Product.lookupModel = function(data) {
@ -80,7 +80,7 @@ describe('default scope', function () {
scope: { where: { kind: 'Tool' }, order: 'name' }, scope: { where: { kind: 'Tool' }, order: 'name' },
scopes: { active: { where: { active: true }}}, scopes: { active: { where: { active: true }}},
mongodb: { collection: 'Product' }, mongodb: { collection: 'Product' },
memory: { collection: 'Product' } memory: { collection: 'Product' },
}); });
Widget = db.define('Widget', Product.definition.properties, { Widget = db.define('Widget', Product.definition.properties, {
@ -89,11 +89,11 @@ describe('default scope', function () {
scope: { where: { kind: 'Widget' }, order: 'name' }, scope: { where: { kind: 'Widget' }, order: 'name' },
scopes: { active: { where: { active: true }}}, scopes: { active: { where: { active: true }}},
mongodb: { collection: 'Product' }, mongodb: { collection: 'Product' },
memory: { collection: 'Product' } memory: { collection: 'Product' },
}); });
Person = db.define('Person', { name: String }, { Person = db.define('Person', { name: String }, {
scope: { include: 'things' } scope: { include: 'things' },
}); });
// inst is only valid for instance methods // inst is only valid for instance methods
@ -112,7 +112,7 @@ describe('default scope', function () {
attributes: propertiesFn, attributes: propertiesFn,
scope: scopeFn, scope: scopeFn,
mongodb: { collection: 'Product' }, mongodb: { collection: 'Product' },
memory: { collection: 'Product' } memory: { collection: 'Product' },
}); });
Category.hasMany(Product); Category.hasMany(Product);
@ -685,7 +685,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; }) var kinds = products.map(function(p) { return p.kind; });
kinds.sort(); kinds.sort();
kinds.should.eql(['Thing', 'Widget']); kinds.should.eql(['Thing', 'Widget']);
done(); done();
@ -717,7 +717,7 @@ describe('default scope', function () {
}, },
function(next) { function(next) {
cat.things.create({ name: 'Thing A' }, next); cat.things.create({ name: 'Thing A' }, next);
} },
], done); ], done);
}); });
}); });

View File

@ -15,7 +15,7 @@ describe('defaults', function () {
Server = db.define('Server', { Server = db.define('Server', {
host: String, host: String,
port: { type: Number, default: 80 }, port: { type: Number, default: 80 },
createdAt: {type: Date, default: '$now'} createdAt: { type: Date, default: '$now' },
}); });
}); });
@ -34,7 +34,7 @@ describe('defaults', function () {
it('should apply defaults on read', function(done) { it('should apply defaults on read', function(done) {
db.defineProperty('Server', 'host', { db.defineProperty('Server', 'host', {
type: String, type: String,
default: 'localhost' default: 'localhost',
}); });
Server.all(function(err, servers) { Server.all(function(err, servers) {
(new String('localhost')).should.equal(servers[0].host); (new String('localhost')).should.equal(servers[0].host);

View File

@ -31,7 +31,7 @@ describe('Memory connector with mocked discovery', function() {
dataLength: 20, dataLength: 20,
dataPrecision: null, dataPrecision: null,
dataScale: null, dataScale: null,
nullable: 0 nullable: 0,
}, },
{ {
owner: 'STRONGLOOP', owner: 'STRONGLOOP',
@ -41,7 +41,7 @@ describe('Memory connector with mocked discovery', function() {
dataLength: 20, dataLength: 20,
dataPrecision: null, dataPrecision: null,
dataScale: null, dataScale: null,
nullable: 0 nullable: 0,
}, },
{ {
owner: 'STRONGLOOP', owner: 'STRONGLOOP',
@ -51,7 +51,7 @@ describe('Memory connector with mocked discovery', function() {
dataLength: null, dataLength: null,
dataPrecision: 10, dataPrecision: 10,
dataScale: 0, dataScale: 0,
nullable: 1 nullable: 1,
}, },
{ {
owner: 'STRONGLOOP', owner: 'STRONGLOOP',
@ -61,7 +61,7 @@ describe('Memory connector with mocked discovery', function() {
dataLength: null, dataLength: null,
dataPrecision: 10, dataPrecision: 10,
dataScale: 0, dataScale: 0,
nullable: 1 nullable: 1,
}]; }];
ds.discoverModelProperties = function(modelName, options, cb) { ds.discoverModelProperties = function(modelName, options, cb) {
@ -88,7 +88,7 @@ describe('Memory connector with mocked discovery', function() {
nameMapper: function(type, name) { nameMapper: function(type, name) {
// Convert all names to lower case // Convert all names to lower case
return name.toLowerCase(); return name.toLowerCase();
} },
}, 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');
@ -118,8 +118,8 @@ describe('Memory connector with mocked discovery', function() {
var models = { var models = {
inventory: { inventory: {
product: { type: 'string' }, product: { type: 'string' },
location: {type: 'string'} location: { type: 'string' },
} },
}; };
ds.connector.discoverSchemas = function(modelName, options, cb) { ds.connector.discoverSchemas = function(modelName, options, cb) {
process.nextTick(function() { process.nextTick(function() {
@ -138,8 +138,8 @@ describe('Memory connector with mocked discovery', function() {
var models = { var models = {
inventory: { inventory: {
product: { type: 'string' }, product: { type: 'string' },
location: {type: 'string'} location: { type: 'string' },
} },
}; };
ds.connector.discoverSchemas = function(modelName, options, cb) { ds.connector.discoverSchemas = function(modelName, options, cb) {
process.nextTick(function() { process.nextTick(function() {
@ -184,7 +184,7 @@ describe('Memory connector with mocked discovery', function() {
name: 'Inventory', name: 'Inventory',
options: { options: {
idInjection: false, idInjection: false,
memory: { schema: 'STRONGLOOP', table: 'INVENTORY' } memory: { schema: 'STRONGLOOP', table: 'INVENTORY' },
}, },
properties: { properties: {
available: { available: {
@ -195,12 +195,12 @@ describe('Memory connector with mocked discovery', function() {
dataPrecision: 10, dataPrecision: 10,
dataScale: 0, dataScale: 0,
dataType: 'int', dataType: 'int',
nullable: 1 nullable: 1,
}, },
precision: 10, precision: 10,
required: false, required: false,
scale: 0, scale: 0,
type: undefined type: undefined,
}, },
locationId: { locationId: {
length: 20, length: 20,
@ -210,12 +210,12 @@ describe('Memory connector with mocked discovery', function() {
dataPrecision: null, dataPrecision: null,
dataScale: null, dataScale: null,
dataType: 'varchar', dataType: 'varchar',
nullable: 0 nullable: 0,
}, },
precision: null, precision: null,
required: true, required: true,
scale: null, scale: null,
type: undefined type: undefined,
}, },
productId: { productId: {
length: 20, length: 20,
@ -225,12 +225,12 @@ describe('Memory connector with mocked discovery', function() {
dataPrecision: null, dataPrecision: null,
dataScale: null, dataScale: null,
dataType: 'varchar', dataType: 'varchar',
nullable: 0 nullable: 0,
}, },
precision: null, precision: null,
required: true, required: true,
scale: null, scale: null,
type: undefined type: undefined,
}, },
total: { total: {
length: null, length: null,
@ -240,14 +240,14 @@ describe('Memory connector with mocked discovery', function() {
dataPrecision: 10, dataPrecision: 10,
dataScale: 0, dataScale: 0,
dataType: 'int', dataType: 'int',
nullable: 1 nullable: 1,
}, },
precision: 10, precision: 10,
required: false, required: false,
scale: 0, scale: 0,
type: undefined type: undefined,
} },
} },
}; };
}); });
@ -307,7 +307,7 @@ describe('discoverModelDefinitions', function(){
}); });
tableNames.should.be.eql( tableNames.should.be.eql(
["CUSTOMER", "INVENTORY", "LOCATION"] ['CUSTOMER', 'INVENTORY', 'LOCATION']
); );
done(); done();
}); });
@ -322,7 +322,7 @@ describe('discoverModelDefinitions', function(){
}); });
tableNames.should.be.eql( tableNames.should.be.eql(
["CUSTOMER", "INVENTORY", "LOCATION"] ['CUSTOMER', 'INVENTORY', 'LOCATION']
); );
done(); done();
}; };
@ -338,7 +338,7 @@ describe('discoverModelDefinitions', function(){
}); });
tableNames.should.be.eql( tableNames.should.be.eql(
["CUSTOMER", "INVENTORY", "LOCATION"] ['CUSTOMER', 'INVENTORY', 'LOCATION']
); );
done(); done();
}) })
@ -362,7 +362,7 @@ describe('discoverModelProperties', function(){
dataLength: 20, dataLength: 20,
dataPrecision: null, dataPrecision: null,
dataScale: null, dataScale: null,
nullable: 0 nullable: 0,
}, },
{ {
owner: 'STRONGLOOP', owner: 'STRONGLOOP',
@ -372,7 +372,7 @@ describe('discoverModelProperties', function(){
dataLength: 20, dataLength: 20,
dataPrecision: null, dataPrecision: null,
dataScale: null, dataScale: null,
nullable: 0 nullable: 0,
}, },
{ {
owner: 'STRONGLOOP', owner: 'STRONGLOOP',
@ -382,7 +382,7 @@ describe('discoverModelProperties', function(){
dataLength: null, dataLength: null,
dataPrecision: 10, dataPrecision: 10,
dataScale: 0, dataScale: 0,
nullable: 1 nullable: 1,
}, },
{ {
owner: 'STRONGLOOP', owner: 'STRONGLOOP',
@ -392,7 +392,7 @@ describe('discoverModelProperties', function(){
dataLength: null, dataLength: null,
dataPrecision: 10, dataPrecision: 10,
dataScale: 0, dataScale: 0,
nullable: 1 nullable: 1,
}]; }];
ds.connector.discoverModelProperties = function(modelName, options, cb) { ds.connector.discoverModelProperties = function(modelName, options, cb) {
@ -446,14 +446,14 @@ describe('discoverPrimaryKeys', function(){
tableName: 'INVENTORY', tableName: 'INVENTORY',
columnName: 'PRODUCT_ID', columnName: 'PRODUCT_ID',
keySeq: 1, keySeq: 1,
pkName: 'ID_PK' pkName: 'ID_PK',
}, },
{ {
owner: 'STRONGLOOP', owner: 'STRONGLOOP',
tableName: 'INVENTORY', tableName: 'INVENTORY',
columnName: 'LOCATION_ID', columnName: 'LOCATION_ID',
keySeq: 2, keySeq: 2,
pkName: 'ID_PK' pkName: 'ID_PK',
}]; }];
ds.connector.discoverPrimaryKeys = function(modelName, options, cb) { ds.connector.discoverPrimaryKeys = function(modelName, options, cb) {
@ -509,7 +509,7 @@ describe('discoverForeignKeys', function(){
pkOwner: 'STRONGLOOP', pkOwner: 'STRONGLOOP',
pkName: 'PRODUCT_PK', pkName: 'PRODUCT_PK',
pkTableName: 'PRODUCT', pkTableName: 'PRODUCT',
pkColumnName: 'ID' pkColumnName: 'ID',
}]; }];
ds.connector.discoverForeignKeys = function(modelName, options, cb) { ds.connector.discoverForeignKeys = function(modelName, options, cb) {
@ -566,7 +566,7 @@ describe('discoverExportedForeignKeys', function(){
pkName: 'PRODUCT_PK', pkName: 'PRODUCT_PK',
pkOwner: 'STRONGLOOP', pkOwner: 'STRONGLOOP',
pkTableName: 'PRODUCT', pkTableName: 'PRODUCT',
pkColumnName: 'ID' pkColumnName: 'ID',
}]; }];
ds.connector.discoverExportedForeignKeys = function(modelName, options, cb) { ds.connector.discoverExportedForeignKeys = function(modelName, options, cb) {

View File

@ -23,7 +23,7 @@ describe('events', function() {
listener.apply(this, arguments); listener.apply(this, arguments);
done(); done();
}); });
} };
}); });
describe('changed', function() { describe('changed', function() {

View File

@ -63,7 +63,7 @@ describe('GeoPoint', function () {
fn = function() { fn = function() {
new GeoPoint({ new GeoPoint({
lat: 150, lat: 150,
lng: null lng: null,
}); });
}; };
fn.should.throw(); fn.should.throw();

View File

@ -22,7 +22,7 @@ describe('hooks', function () {
email: { type: String, index: true }, email: { type: String, index: true },
name: String, name: String,
password: String, password: String,
state: String state: String,
}); });
db.automigrate('User', done); db.automigrate('User', done);
@ -83,7 +83,7 @@ describe('hooks', function () {
var old = User.dataSource.connector.create; var 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'));
} };
User.afterCreate = function() { User.afterCreate = function() {
throw new Error('shouldn\'t be called'); throw new Error('shouldn\'t be called');
@ -103,7 +103,7 @@ describe('hooks', function () {
var old = User.dataSource.connector.create; var 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');
} };
User.afterCreate = function() { User.afterCreate = function() {
throw new Error('shouldn\'t be called'); throw new Error('shouldn\'t be called');
@ -147,7 +147,7 @@ describe('hooks', function () {
User.create(function(err, user) { User.create(function(err, user) {
User.beforeSave = function(next, data) { User.beforeSave = function(next, data) {
data.should.have.keys('id', 'name', 'email', data.should.have.keys('id', 'name', 'email',
'password', 'state') 'password', 'state');
done(); done();
}; };
user.save(); user.save();
@ -162,10 +162,10 @@ describe('hooks', function () {
User.destroyAll(function() { User.destroyAll(function() {
User.create({ User.create({
email: 'james.bond@example.com', email: 'james.bond@example.com',
password: '53cr3t' password: '53cr3t',
}, function() { }, function() {
User.findOne({ User.findOne({
where: {email: 'james.bond@example.com'} where: { email: 'james.bond@example.com' },
}, function(err, jb) { }, function(err, jb) {
jb.password.should.equal('hash'); jb.password.should.equal('hash');
done(); done();
@ -181,14 +181,14 @@ describe('hooks', function () {
}; };
User.destroyAll(function() { User.destroyAll(function() {
User.create({ User.create({
email: 'james.bond@example.com' email: 'james.bond@example.com',
}, function(err, u) { }, function(err, u) {
u.updateAttribute('password', 'new password', function(e, u) { u.updateAttribute('password', 'new password', function(e, u) {
should.not.exist(e); should.not.exist(e);
should.exist(u); should.exist(u);
u.password.should.equal('hash'); u.password.should.equal('hash');
User.findOne({ User.findOne({
where: {email: 'james.bond@example.com'} where: { email: 'james.bond@example.com' },
}, function(err, jb) { }, function(err, jb) {
jb.password.should.equal('hash'); jb.password.should.equal('hash');
done(); done();
@ -265,7 +265,7 @@ describe('hooks', function () {
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'));
} };
user.save(function(err) { user.save(function(err) {
done(); done();
@ -297,9 +297,9 @@ describe('hooks', function () {
var destroy = User.dataSource.connector.destroy; var 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'));
} };
User.afterDestroy = function() { User.afterDestroy = function() {
should.fail('afterDestroy shouldn\'t be called') should.fail('afterDestroy shouldn\'t be called');
}; };
User.create(function(err, user) { User.create(function(err, user) {
user.destroy(function(err) { user.destroy(function(err) {
@ -376,7 +376,7 @@ describe('hooks', function () {
'beforeCreate', 'beforeCreate',
'beforeSave', 'beforeSave',
'afterSave', 'afterSave',
'afterCreate' 'afterCreate',
]); ]);
done(); done();
}); });
@ -392,7 +392,7 @@ describe('hooks', function () {
'beforeCreate', 'beforeCreate',
'beforeSave', 'beforeSave',
'afterSave', 'afterSave',
'afterCreate' 'afterCreate',
]); ]);
done(); done();
}); });
@ -420,7 +420,7 @@ describe('hooks', function () {
valid.should.be.true; valid.should.be.true;
life.should.eql([ life.should.eql([
'beforeValidate', 'beforeValidate',
'afterValidate' 'afterValidate',
]); ]);
done(); done();
}); });
@ -430,7 +430,7 @@ describe('hooks', function () {
user.destroy(function() { user.destroy(function() {
life.should.eql([ life.should.eql([
'beforeDestroy', 'beforeDestroy',
'afterDestroy' 'afterDestroy',
]); ]);
done(); done();
}); });

View File

@ -126,7 +126,7 @@ describe('include', function () {
it('should fetch Passports - User - Posts - User', function(done) { it('should fetch Passports - User - Posts - User', function(done) {
Passport.find({ Passport.find({
include: {owner: {posts: 'author'}} include: { owner: { posts: 'author' }},
}, function(err, passports) { }, function(err, passports) {
should.not.exist(err); should.not.exist(err);
should.exist(passports); should.exist(passports);
@ -158,8 +158,8 @@ describe('include', function () {
Passport.find({ Passport.find({
include: { owner: { relation: 'posts', scope:{ include: { owner: { relation: 'posts', scope:{
fields: ['title'], include: ['author'], fields: ['title'], include: ['author'],
order: 'title DESC' order: 'title DESC',
}}} }}},
}, function(err, passports) { }, function(err, passports) {
should.not.exist(err); should.not.exist(err);
should.exist(passports); should.exist(passports);
@ -196,11 +196,11 @@ describe('include', function () {
relation: 'posts', scope: { relation: 'posts', scope: {
fields: ['title'], include: ['author'], fields: ['title'], include: ['author'],
order: 'title DESC', order: 'title DESC',
limit: 2 limit: 2,
}
}
}, },
limit: 1 },
},
limit: 1,
}, function(err, passports) { }, function(err, passports) {
if (err) return done(err); if (err) return done(err);
passports.length.should.equal(1); passports.length.should.equal(1);
@ -211,7 +211,7 @@ describe('include', function () {
it('should fetch Users with include scope on Posts - belongsTo', function(done) { it('should fetch Users with include scope on Posts - belongsTo', function(done) {
Post.find({ Post.find({
include: { relation: 'author', scope:{ fields: ['name'] }} include: { relation: 'author', scope:{ fields: ['name'] }},
}, function(err, posts) { }, function(err, posts) {
should.not.exist(err); should.not.exist(err);
should.exist(posts); should.exist(posts);
@ -229,8 +229,8 @@ describe('include', function () {
it('should fetch Users with include scope on Posts - hasMany', function(done) { it('should fetch Users with include scope on Posts - hasMany', function(done) {
User.find({ User.find({
include: { relation: 'posts', scope:{ include: { relation: 'posts', scope:{
order: 'title DESC' order: 'title DESC',
}} }},
}, function(err, users) { }, function(err, users) {
should.not.exist(err); should.not.exist(err);
should.exist(users); should.exist(users);
@ -259,8 +259,8 @@ describe('include', function () {
it('should fetch Users with include scope on Passports - hasMany', function(done) { it('should fetch Users with include scope on Passports - hasMany', function(done) {
User.find({ User.find({
include: { relation: 'passports', scope:{ include: { relation: 'passports', scope:{
where: { number: '2' } where: { number: '2' },
}} }},
}, function(err, users) { }, function(err, users) {
should.not.exist(err); should.not.exist(err);
should.exist(users); should.exist(users);
@ -313,9 +313,9 @@ describe('include', function () {
function(done) { function(done) {
User.find({ include: [ User.find({ include: [
{ relation: 'posts', scope: { { relation: 'posts', scope: {
where: {title: 'Post A'} where: { title: 'Post A' },
}}, }},
'passports' 'passports',
] }, function(err, users) { ] }, function(err, users) {
should.not.exist(err); should.not.exist(err);
should.exist(users); should.exist(users);
@ -423,7 +423,7 @@ describe('include', function () {
// fixed by DB optimization // fixed by DB optimization
it('should support include scope on hasAndBelongsToMany', function(done) { it('should support include scope on hasAndBelongsToMany', function(done) {
Assembly.find({ include: { relation: 'parts', scope: { Assembly.find({ include: { relation: 'parts', scope: {
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(); var parts = assemblies[0].parts();
@ -435,7 +435,7 @@ describe('include', function () {
it('should save related items separately', function(done) { it('should save related items separately', function(done) {
User.find({ User.find({
include: 'posts' include: 'posts',
}) })
.then(function(users) { .then(function(users) {
var posts = users[0].posts(); var posts = users[0].posts();
@ -444,7 +444,7 @@ describe('include', function () {
}) })
.then(function(updatedUser) { .then(function(updatedUser) {
return User.findById(updatedUser.id, { return User.findById(updatedUser.id, {
include: 'posts' include: 'posts',
}); });
}) })
.then(function(user) { .then(function(user) {
@ -518,10 +518,10 @@ describe('include', function () {
Assembly.find({ Assembly.find({
where: { where: {
name: { name: {
inq: ['sedan', 'hatchback', 'SUV'] inq: ['sedan', 'hatchback', 'SUV'],
}
}, },
include: 'parts' },
include: 'parts',
}, function(err, result) { }, function(err, result) {
should.not.exist(err); should.not.exist(err);
should.exists(result); should.exists(result);
@ -584,7 +584,7 @@ describe('include', function () {
function(done) { function(done) {
var self = this; var 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) {
should.not.exist(err); should.not.exist(err);
should.exist(users); should.exist(users);
@ -627,19 +627,19 @@ function setup(done) {
Building = db.define('Building'); Building = db.define('Building');
User = db.define('User', { User = db.define('User', {
name: String, name: String,
age: Number age: Number,
}); });
Profile = db.define('Profile', { Profile = db.define('Profile', {
profileName: String profileName: String,
}); });
AccessToken = db.define('AccessToken', { AccessToken = db.define('AccessToken', {
token: String token: String,
}); });
Passport = db.define('Passport', { Passport = db.define('Passport', {
number: String number: String,
}); });
Post = db.define('Post', { Post = db.define('Post', {
title: String title: String,
}); });
Passport.belongsTo('owner', { model: User }); Passport.belongsTo('owner', { model: User });
@ -647,18 +647,18 @@ function setup(done) {
User.hasMany('posts', { foreignKey: 'userId' }); User.hasMany('posts', { foreignKey: 'userId' });
User.hasMany('accesstokens', { User.hasMany('accesstokens', {
foreignKey: 'userId', foreignKey: 'userId',
options: {disableInclude: true} options: { disableInclude: true },
}); });
Profile.belongsTo('user', { model: User }); Profile.belongsTo('user', { model: User });
User.hasOne('profile', { foreignKey: 'userId' }); User.hasOne('profile', { foreignKey: 'userId' });
Post.belongsTo('author', { model: User, foreignKey: 'userId' }); Post.belongsTo('author', { model: User, foreignKey: 'userId' });
Assembly = db.define('Assembly', { Assembly = db.define('Assembly', {
name: String name: String,
}); });
Part = db.define('Part', { Part = db.define('Part', {
partNumber: String partNumber: String,
}); });
Assembly.hasAndBelongsToMany(Part); Assembly.hasAndBelongsToMany(Part);
@ -678,7 +678,7 @@ function setup(done) {
{ name: 'User B', age: 22 }, { name: 'User B', age: 22 },
{ name: 'User C', age: 23 }, { name: 'User C', age: 23 },
{ name: 'User D', age: 24 }, { name: 'User D', age: 24 },
{name: 'User E', age: 25} { name: 'User E', age: 25 },
], ],
function(items) { function(items) {
createdUsers = items; createdUsers = items;
@ -693,7 +693,7 @@ function setup(done) {
AccessToken, AccessToken,
[ [
{ token: '1', userId: createdUsers[0].id }, { token: '1', userId: createdUsers[0].id },
{token: '2', userId: createdUsers[1].id} { token: '2', userId: createdUsers[1].id },
], ],
function(items) {} function(items) {}
); );
@ -721,10 +721,10 @@ function setup(done) {
[ [
{ profileName: 'Profile A', userId: createdUsers[0].id }, { profileName: 'Profile A', userId: createdUsers[0].id },
{ profileName: 'Profile B', userId: createdUsers[1].id }, { profileName: 'Profile B', userId: createdUsers[1].id },
{profileName: 'Profile Z'} { profileName: 'Profile Z' },
], ],
function(items) { function(items) {
createdProfiles = items createdProfiles = items;
done(); done();
} }
); );
@ -738,7 +738,7 @@ function setup(done) {
{ title: 'Post B', userId: createdUsers[0].id }, { title: 'Post B', userId: createdUsers[0].id },
{ title: 'Post C', userId: createdUsers[0].id }, { title: 'Post C', userId: createdUsers[0].id },
{ title: 'Post D', userId: createdUsers[1].id }, { title: 'Post D', userId: createdUsers[1].id },
{title: 'Post E'} { title: 'Post E' },
], ],
function(items) { function(items) {
createdPosts = items; createdPosts = items;
@ -778,35 +778,35 @@ describe('Model instance with included relation .toJSON()', function() {
db = new DataSource({ connector: 'memory' }); db = new DataSource({ connector: 'memory' });
ChallengerModel = db.createModel('Challenger', ChallengerModel = db.createModel('Challenger',
{ {
name: String name: String,
}, },
{ {
relations: { relations: {
gameParticipations: { gameParticipations: {
type: 'hasMany', type: 'hasMany',
model: 'GameParticipation', model: 'GameParticipation',
foreignKey: '' foreignKey: '',
} },
} },
} }
); );
GameParticipationModel = db.createModel('GameParticipation', GameParticipationModel = db.createModel('GameParticipation',
{ {
date: Date date: Date,
}, },
{ {
relations: { relations: {
challenger: { challenger: {
type: 'belongsTo', type: 'belongsTo',
model: 'Challenger', model: 'Challenger',
foreignKey: '' foreignKey: '',
}, },
results: { results: {
type: 'hasMany', type: 'hasMany',
model: 'Result', model: 'Result',
foreignKey: '' foreignKey: '',
} },
} },
} }
); );
ResultModel = db.createModel('Result', { ResultModel = db.createModel('Result', {
@ -816,9 +816,9 @@ describe('Model instance with included relation .toJSON()', function() {
gameParticipation: { gameParticipation: {
type: 'belongsTo', type: 'belongsTo',
model: 'GameParticipation', model: 'GameParticipation',
foreignKey: '' foreignKey: '',
} },
} },
}); });
async.waterfall([ async.waterfall([
@ -838,14 +838,14 @@ describe('Model instance with included relation .toJSON()', function() {
function createGameParticipations(challengers, callback) { function createGameParticipations(challengers, callback) {
GameParticipationModel.create([ GameParticipationModel.create([
{ challengerId: challengers[0].id, date: Date.now() }, { challengerId: challengers[0].id, date: Date.now() },
{challengerId: challengers[0].id, date: Date.now()} { challengerId: challengers[0].id, date: Date.now() },
], callback); ], callback);
} }
function createResults(gameParticipations, callback) { function createResults(gameParticipations, callback) {
ResultModel.create([ ResultModel.create([
{ gameParticipationId: gameParticipations[0].id, points: 10 }, { gameParticipationId: gameParticipations[0].id, points: 10 },
{gameParticipationId: gameParticipations[0].id, points: 20} { gameParticipationId: gameParticipations[0].id, points: 20 },
], callback); ], callback);
} }

View File

@ -3,44 +3,44 @@
// This file is licensed under the MIT License. // This file is licensed under the MIT License.
// License text available at https://opensource.org/licenses/MIT // License text available at https://opensource.org/licenses/MIT
var assert = require("assert"); var assert = require('assert');
var should = require("should"); var should = require('should');
var includeUtils = require("../lib/include_utils"); var 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 = [ var objs = [
{id: 11, letter: "A"}, { id: 11, letter: 'A' },
{id: 22, letter: "B"} { id: 22, letter: 'B' },
]; ];
var result = includeUtils.buildOneToOneIdentityMapWithOrigKeys(objs, "id"); var 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 overwrite keys in case of collision', function() { it('should overwrite keys in case of collision', function() {
var objs = [ var 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"); var 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);
result.get(11)["letter"].should.equal("HA!"); result.get(11)['letter'].should.equal('HA!');
result.get(33)["letter"].should.equal("C"); result.get(33)['letter'].should.equal('C');
}); });
}); });
describe('#buildOneToOneIdentityMapWithOrigKeys', function() { describe('#buildOneToOneIdentityMapWithOrigKeys', function() {
it('should return an object with keys', function() { it('should return an object with keys', function() {
var objs = [ var objs = [
{id: 11, letter: "A"}, { id: 11, letter: 'A' },
{id: 22, letter: "B"} { id: 22, letter: 'B' },
]; ];
var result = includeUtils.buildOneToOneIdentityMapWithOrigKeys(objs, 'id'); var result = includeUtils.buildOneToOneIdentityMapWithOrigKeys(objs, 'id');
result.get(11).should.be.ok; result.get(11).should.be.ok;
@ -51,26 +51,26 @@ describe('include_util', function(){
describe('#buildOneToManyIdentityMap', function() { describe('#buildOneToManyIdentityMap', function() {
it('should return an object with keys', function() { it('should return an object with keys', function() {
var objs = [ var objs = [
{id: 11, letter: "A"}, { id: 11, letter: 'A' },
{id: 22, letter: "B"} { id: 22, letter: 'B' },
]; ];
var result = includeUtils.buildOneToManyIdentityMapWithOrigKeys(objs, "id"); var 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 collect keys in case of collision', function() { it('should collect keys in case of collision', function() {
var objs = [ var 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"); var 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');
}); });
}); });
}); });

View File

@ -19,14 +19,14 @@ var json = {
city: 'San Jose', city: 'San Jose',
state: 'CA', state: 'CA',
zipcode: '95131', zipcode: '95131',
country: 'US' country: 'US',
}, },
friends: ['John', 'Mary'], friends: ['John', 'Mary'],
emails: [ emails: [
{ label: 'work', id: 'x@sample.com' }, { label: 'work', id: 'x@sample.com' },
{label: 'home', id: 'x@home.com'} { label: 'home', id: 'x@home.com' },
], ],
tags: [] tags: [],
}; };
describe('Introspection of model definitions from JSON', function() { describe('Introspection of model definitions from JSON', function() {

View File

@ -22,7 +22,7 @@ describe('JSON property', function () {
it('should accept JSON in constructor and return object', function() { it('should accept JSON in constructor and return object', function() {
var m = new Model({ var m = new Model({
propertyName: '{"foo": "bar"}' 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');
@ -30,7 +30,7 @@ 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; var 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');
}); });

View File

@ -22,7 +22,7 @@ describe('ModelBuilder define model', function () {
bio: ModelBuilder.Text, bio: ModelBuilder.Text,
approved: Boolean, approved: Boolean,
joinedAt: Date, joinedAt: Date,
age: Number age: Number,
}); });
// define any custom method // define any custom method
@ -169,15 +169,15 @@ describe('ModelBuilder define model', function () {
city: String, city: String,
state: String, state: String,
zipCode: String, zipCode: String,
country: String country: String,
}, },
emails: [ emails: [
{ {
label: String, label: String,
email: String email: String,
} },
], ],
friends: [String] friends: [String],
}); });
// define any custom method // define any custom method
@ -192,9 +192,9 @@ describe('ModelBuilder define model', function () {
name: 'Joe', age: 20, name: 'Joe', age: 20,
address: { street: '123 Main St', 'city': 'San Jose', state: 'CA' }, address: { street: '123 Main St', 'city': 'San Jose', state: 'CA' },
emails: [ emails: [
{label: 'work', email: 'xyz@sample.com'} { label: 'work', email: 'xyz@sample.com' },
], ],
friends: ['Mary', 'John'] friends: ['Mary', 'John'],
}); });
User.modelName.should.equal('User'); User.modelName.should.equal('User');
@ -234,7 +234,7 @@ describe('ModelBuilder define model', function () {
city: String, city: String,
state: String, state: String,
zipCode: String, zipCode: String,
country: String country: String,
}); });
user = new User({ name: 'Joe', address: { street: '123 Main St', 'city': 'San Jose', state: 'CA' }}); user = new User({ name: 'Joe', address: { street: '123 Main St', 'city': 'San Jose', state: 'CA' }});
@ -253,7 +253,7 @@ describe('ModelBuilder define model', function () {
var Follow = modelBuilder.define('Follow', { var Follow = modelBuilder.define('Follow', {
followerId: { type: String, id: 1 }, followerId: { type: String, id: 1 },
followeeId: { type: String, id: 2 }, followeeId: { type: String, id: 2 },
followAt: Date followAt: Date,
}); });
var follow = new Follow({ followerId: 1, followeeId: 2 }); var follow = new Follow({ followerId: 1, followeeId: 2 });
@ -272,7 +272,7 @@ describe('DataSource ping', function() {
}; };
ds.connector.ping = function(cb) { ds.connector.ping = function(cb) {
cb(new Error('bad connection 2')); cb(new Error('bad connection 2'));
} };
it('should report connection errors during ping', function(done) { it('should report connection errors during ping', function(done) {
ds.ping(function(err) { ds.ping(function(err) {
@ -285,7 +285,7 @@ describe('DataSource ping', function() {
it('should cancel invocation after timeout', function(done) { it('should cancel invocation after timeout', function(done) {
ds.connected = false; // Force connect ds.connected = false; // Force connect
var Post = ds.define('Post', { var Post = ds.define('Post', {
title: { type: String, length: 255 } title: { type: String, length: 255 },
}); });
Post.create(function(err) { Post.create(function(err) {
(!!err).should.be.true; (!!err).should.be.true;
@ -307,7 +307,7 @@ describe('DataSource define model', function () {
return new Date(); return new Date();
} }, } },
timestamp: { type: Number, default: Date.now }, timestamp: { type: Number, default: Date.now },
published: { type: Boolean, default: false, index: true } published: { type: Boolean, default: false, index: true },
}); });
// simpler way to describe model // simpler way to describe model
@ -316,7 +316,7 @@ describe('DataSource define model', function () {
bio: ModelBuilder.Text, bio: ModelBuilder.Text,
approved: Boolean, approved: Boolean,
joinedAt: { type: Date, default: Date }, joinedAt: { type: Date, default: Date },
age: Number age: Number,
}); });
var Group = ds.define('Group', { group: String }); var Group = ds.define('Group', { group: String });
@ -382,7 +382,7 @@ describe('DataSource define model', function () {
var modelBuilder = new ModelBuilder(); var modelBuilder = new ModelBuilder();
var Color = modelBuilder.define('Color', { var Color = modelBuilder.define('Color', {
name: String name: String,
}); });
Color.should.not.have.property('create'); Color.should.not.have.property('create');
@ -406,7 +406,7 @@ describe('DataSource define model', function () {
var modelBuilder = new ModelBuilder(); var modelBuilder = new ModelBuilder();
var User = modelBuilder.define('User', { var User = modelBuilder.define('User', {
name: String name: String,
}); });
var seq = 0; var seq = 0;
@ -583,7 +583,7 @@ describe('DataSource define model', function () {
var ds = new DataSource('memory');// define models var ds = new DataSource('memory');// define models
Post = ds.define('Post', { Post = ds.define('Post', {
title: { type: String, length: 255, index: true }, title: { type: String, length: 255, index: true },
content: { type: String } content: { type: String },
}); });
Post.create({ title: 'a', content: 'AAA' }, function(err, post) { Post.create({ title: 'a', content: 'AAA' }, function(err, post) {
@ -643,7 +643,7 @@ describe('DataSource define model', function () {
var ds = new DataSource('memory'); var ds = new DataSource('memory');
var User = ds.define('User', { name: String, bio: String }, { var User = ds.define('User', { name: String, bio: String }, {
http: { path: 'accounts' } http: { path: 'accounts' },
}); });
User.http.path.should.equal('/accounts'); User.http.path.should.equal('/accounts');
}); });
@ -652,7 +652,7 @@ describe('DataSource define model', function () {
var ds = new DataSource('memory'); var ds = new DataSource('memory');
var User = ds.define('User', { name: String, bio: String }, { var User = ds.define('User', { name: String, bio: String }, {
http: { path: '/accounts' } http: { path: '/accounts' },
}); });
User.http.path.should.equal('/accounts'); User.http.path.should.equal('/accounts');
}); });
@ -766,7 +766,7 @@ describe('Models attached to a dataSource', function() {
Post = ds.define('Post', { Post = ds.define('Post', {
title: { type: String, length: 255, index: true }, title: { type: String, length: 255, index: true },
content: { type: String }, content: { type: String },
comments: [String] comments: [String],
}); });
}); });
@ -956,7 +956,7 @@ describe('DataSource constructor', function () {
return null; return null;
} }
return { return {
name: name name: name,
}; };
}; };
@ -1053,10 +1053,10 @@ describe('Load models with relations', function () {
var ds = new DataSource('memory'); var ds = new DataSource('memory');
var Author = ds.define('Author', { name: String }, { relations: { var Author = ds.define('Author', { name: String }, { relations: {
pictures: {type: 'hasMany', model: 'Picture', polymorphic: 'imageable'} pictures: { type: 'hasMany', model: 'Picture', polymorphic: 'imageable' },
}}); }});
var Picture = ds.define('Picture', { name: String }, { relations: { var Picture = ds.define('Picture', { name: String }, { relations: {
imageable: {type: 'belongsTo', polymorphic: true} imageable: { type: 'belongsTo', polymorphic: true },
}}); }});
assert(Author.relations['pictures']); assert(Author.relations['pictures']);
@ -1071,8 +1071,8 @@ describe('Load models with relations', function () {
polymorphic: { polymorphic: {
as: 'imageable', as: 'imageable',
foreignKey: 'imageableId', foreignKey: 'imageableId',
discriminator: 'imageableType' discriminator: 'imageableType',
} },
}); });
assert(Picture.relations['imageable']); assert(Picture.relations['imageable']);
@ -1087,8 +1087,8 @@ describe('Load models with relations', function () {
polymorphic: { polymorphic: {
as: 'imageable', as: 'imageable',
foreignKey: 'imageableId', foreignKey: 'imageableId',
discriminator: 'imageableType' discriminator: 'imageableType',
} },
}); });
done(); done();
}); });
@ -1126,7 +1126,7 @@ describe('Load models with relations', function () {
keyFrom: 'userId', keyFrom: 'userId',
modelTo: 'User', modelTo: 'User',
keyTo: 'id', keyTo: 'id',
multiple: false multiple: false,
}); });
assert(User.relations['posts']); assert(User.relations['posts']);
assert.deepEqual(User.relations['posts'].toJSON(), { assert.deepEqual(User.relations['posts'].toJSON(), {
@ -1136,7 +1136,7 @@ describe('Load models with relations', function () {
keyFrom: 'id', keyFrom: 'id',
modelTo: 'Post', modelTo: 'Post',
keyTo: 'userId', keyTo: 'userId',
multiple: true multiple: true,
}); });
assert(User.relations['accounts']); assert(User.relations['accounts']);
assert.deepEqual(User.relations['accounts'].toJSON(), { assert.deepEqual(User.relations['accounts'].toJSON(), {
@ -1146,7 +1146,7 @@ describe('Load models with relations', function () {
keyFrom: 'id', keyFrom: 'id',
modelTo: 'Account', modelTo: 'Account',
keyTo: 'userId', keyTo: 'userId',
multiple: true multiple: true,
}); });
done(); done();
@ -1181,11 +1181,11 @@ describe('Load models with relations', function () {
it('should handle hasMany through', function(done) { it('should handle hasMany through', function(done) {
var ds = new DataSource('memory'); var ds = new DataSource('memory');
var Physician = ds.createModel('Physician', { var Physician = ds.createModel('Physician', {
name: String name: String,
}, { relations: { patients: { model: 'Patient', type: 'hasMany', through: 'Appointment' }}}); }, { relations: { patients: { model: 'Patient', type: 'hasMany', through: 'Appointment' }}});
var Patient = ds.createModel('Patient', { var Patient = ds.createModel('Patient', {
name: String name: String,
}, { relations: { physicians: { model: 'Physician', type: 'hasMany', through: 'Appointment' }}}); }, { relations: { physicians: { model: 'Physician', type: 'hasMany', through: 'Appointment' }}});
assert(!Physician.relations['patients']); // Appointment hasn't been resolved yet assert(!Physician.relations['patients']); // Appointment hasn't been resolved yet
@ -1194,7 +1194,7 @@ describe('Load models with relations', function () {
var Appointment = ds.createModel('Appointment', { var Appointment = ds.createModel('Appointment', {
physicianId: Number, physicianId: Number,
patientId: Number, patientId: Number,
appointmentDate: Date appointmentDate: Date,
}, { relations: { patient: { type: 'belongsTo', model: 'Patient' }, physician: { type: 'belongsTo', model: 'Physician' }}}); }, { relations: { patient: { type: 'belongsTo', model: 'Patient' }, physician: { type: 'belongsTo', model: 'Physician' }}});
assert(Physician.relations['patients']); assert(Physician.relations['patients']);
@ -1205,17 +1205,17 @@ describe('Load models with relations', function () {
it('should handle hasMany through options', function(done) { it('should handle hasMany through options', function(done) {
var ds = new DataSource('memory'); var ds = new DataSource('memory');
var Physician = ds.createModel('Physician', { var Physician = ds.createModel('Physician', {
name: String name: String,
}, { relations: { patients: { model: 'Patient', type: 'hasMany', foreignKey: 'leftId', through: 'Appointment' }}}); }, { relations: { patients: { model: 'Patient', type: 'hasMany', foreignKey: 'leftId', through: 'Appointment' }}});
var Patient = ds.createModel('Patient', { var Patient = ds.createModel('Patient', {
name: String name: String,
}, { relations: { physicians: { model: 'Physician', type: 'hasMany', foreignKey: 'rightId', through: 'Appointment' }}}); }, { relations: { physicians: { model: 'Physician', type: 'hasMany', foreignKey: 'rightId', through: 'Appointment' }}});
var Appointment = ds.createModel('Appointment', { var Appointment = ds.createModel('Appointment', {
physicianId: Number, physicianId: Number,
patientId: Number, patientId: Number,
appointmentDate: Date appointmentDate: Date,
}, { relations: { patient: { type: 'belongsTo', model: 'Patient' }, physician: { type: 'belongsTo', model: 'Physician' }}}); }, { relations: { patient: { type: 'belongsTo', model: 'Patient' }, physician: { type: 'belongsTo', model: 'Physician' }}});
assert(Physician.relations['patients'].keyTo === 'leftId'); assert(Physician.relations['patients'].keyTo === 'leftId');
@ -1277,7 +1277,7 @@ describe('DataAccessObject', function () {
vip: Boolean, vip: Boolean,
date: Date, date: Date,
location: 'GeoPoint', location: 'GeoPoint',
scores: [Number] scores: [Number],
}); });
}); });
@ -1383,7 +1383,7 @@ describe('DataAccessObject', function () {
try { try {
// The where clause cannot be an array // The where clause cannot be an array
model._coerce([ model._coerce([
{vip: true} { vip: true },
]); ]);
} catch (err) { } catch (err) {
error = err; error = err;
@ -1505,7 +1505,7 @@ describe('DataAccessObject', function () {
assert.deepEqual(filter, { filter: { x: null }}, 'Should nullify undefined'); assert.deepEqual(filter, { filter: { x: null }}, 'Should nullify undefined');
ds.settings.normalizeUndefinedInQuery = 'throw'; ds.settings.normalizeUndefinedInQuery = 'throw';
(function(){ model._normalize({filter: { x: undefined }}) }).should.throw(/`undefined` in query/); (function() { model._normalize({ filter: { x: undefined }}); }).should.throw(/`undefined` in query/);
}); });
it('should skip GeoPoint', function() { it('should skip GeoPoint', function() {
@ -1614,7 +1614,7 @@ describe('Load models from json', function () {
bio: ModelBuilder.Text, bio: ModelBuilder.Text,
approved: Boolean, approved: Boolean,
joinedAt: Date, joinedAt: Date,
age: Number age: Number,
}); });
modelBuilder.defaultModelBaseClass = User; modelBuilder.defaultModelBaseClass = User;
@ -1631,7 +1631,7 @@ describe('Load models from json', function () {
bio: ModelBuilder.Text, bio: ModelBuilder.Text,
approved: Boolean, approved: Boolean,
joinedAt: Date, joinedAt: Date,
age: Number age: Number,
}); });
var Customer = modelBuilder.define('Customer', var Customer = modelBuilder.define('Customer',
@ -1647,7 +1647,7 @@ describe('Load models from json', function () {
bio: ModelBuilder.Text, bio: ModelBuilder.Text,
approved: Boolean, approved: Boolean,
joinedAt: Date, joinedAt: Date,
age: Number age: Number,
}); });
var Customer = User.extend('Customer', { customerId: { type: String, id: true }}); var Customer = User.extend('Customer', { customerId: { type: String, id: true }});
@ -1687,22 +1687,22 @@ describe('Load models from json', function () {
var modelBuilder = new ModelBuilder(); var modelBuilder = new ModelBuilder();
var User = modelBuilder.define('User', { var User = modelBuilder.define('User', {
name: String name: String,
}, { }, {
defaultPermission: 'ALLOW', defaultPermission: 'ALLOW',
acls: [ acls: [
{ {
principalType: 'ROLE', principalType: 'ROLE',
principalId: '$everyone', principalId: '$everyone',
permission: 'ALLOW' permission: 'ALLOW',
} },
], ],
relations: { relations: {
posts: { posts: {
type: 'hasMany', type: 'hasMany',
model: 'Post' model: 'Post',
} },
} },
}); });
var Customer = User.extend('Customer', var Customer = User.extend('Customer',
@ -1713,15 +1713,15 @@ describe('Load models from json', function () {
{ {
principalType: 'ROLE', principalType: 'ROLE',
principalId: '$unauthenticated', principalId: '$unauthenticated',
permission: 'DENY' permission: 'DENY',
} },
], ],
relations: { relations: {
orders: { orders: {
type: 'hasMany', type: 'hasMany',
model: 'Order' model: 'Order',
} },
} },
} }
); );
@ -1731,16 +1731,16 @@ describe('Load models from json', function () {
{ {
principalType: 'ROLE', principalType: 'ROLE',
principalId: '$everyone', principalId: '$everyone',
permission: 'ALLOW' permission: 'ALLOW',
} },
], ],
relations: { relations: {
posts: { posts: {
type: 'hasMany', type: 'hasMany',
model: 'Post' model: 'Post',
}
}, },
strict: false },
strict: false,
}); });
assert.deepEqual(Customer.settings, { assert.deepEqual(Customer.settings, {
@ -1749,26 +1749,26 @@ describe('Load models from json', function () {
{ {
principalType: 'ROLE', principalType: 'ROLE',
principalId: '$everyone', principalId: '$everyone',
permission: 'ALLOW' permission: 'ALLOW',
}, },
{ {
principalType: 'ROLE', principalType: 'ROLE',
principalId: '$unauthenticated', principalId: '$unauthenticated',
permission: 'DENY' permission: 'DENY',
} },
], ],
relations: { relations: {
posts: { posts: {
type: 'hasMany', type: 'hasMany',
model: 'Post' model: 'Post',
}, },
orders: { orders: {
type: 'hasMany', type: 'hasMany',
model: 'Order' model: 'Order',
} },
}, },
strict: false, strict: false,
base: User base: User,
}); });
done(); done();
@ -1802,7 +1802,7 @@ describe('ModelBuilder options.models', function () {
var builder = new ModelBuilder(); var builder = new ModelBuilder();
var M1 = builder.define('M1'); var M1 = builder.define('M1');
var M2 = builder.define('M2', {}, { models: { var M2 = builder.define('M2', {}, { models: {
'M1': M1 'M1': M1,
}}); }});
assert.equal(M2.M1, M1, 'M1 should be injected to M2'); assert.equal(M2.M1, M1, 'M1 should be injected to M2');
@ -1812,7 +1812,7 @@ describe('ModelBuilder options.models', function () {
var builder = new ModelBuilder(); var builder = new ModelBuilder();
var M1 = builder.define('M1'); var M1 = builder.define('M1');
var M2 = builder.define('M2', {}, { models: { var M2 = builder.define('M2', {}, { models: {
'M1': 'M1' 'M1': 'M1',
}}); }});
assert.equal(M2.M1, M1, 'M1 should be injected to M2'); assert.equal(M2.M1, M1, 'M1 should be injected to M2');
@ -1822,7 +1822,7 @@ describe('ModelBuilder options.models', function () {
function() { function() {
var builder = new ModelBuilder(); var builder = new ModelBuilder();
var M2 = builder.define('M2', {}, { models: { var M2 = builder.define('M2', {}, { models: {
'M1': 'M1' 'M1': 'M1',
}}); }});
assert(M2.M1, 'M1 should be injected to M2'); assert(M2.M1, 'M1 should be injected to M2');
assert(M2.M1.settings.unresolved, 'M1 is still a proxy'); assert(M2.M1.settings.unresolved, 'M1 is still a proxy');

View File

@ -23,7 +23,7 @@ describe('manipulation', function () {
married: Boolean, married: Boolean,
age: { type: Number, index: true }, age: { type: Number, index: true },
dob: Date, dob: Date,
createdAt: {type: Date, default: Date} createdAt: { type: Date, default: Date },
}, { forceId: true, strict: true }); }, { forceId: true, strict: true });
db.automigrate(['Person'], done); db.automigrate(['Person'], done);
@ -233,7 +233,7 @@ describe('manipulation', function () {
var batch = [ var batch = [
{ name: 'Shaltay' }, { name: 'Shaltay' },
{ name: 'Boltay' }, { name: 'Boltay' },
{} {},
]; ];
Person.create(batch, function(e, ps) { Person.create(batch, function(e, ps) {
should.not.exist(e); should.not.exist(e);
@ -269,7 +269,7 @@ describe('manipulation', function () {
var batch = [ var batch = [
{ name: 'A' }, { name: 'A' },
{ name: 'B' }, { name: 'B' },
undefined undefined,
]; ];
Person.create(batch, function(e, ps) { Person.create(batch, function(e, ps) {
should.not.exist(e); should.not.exist(e);
@ -289,7 +289,7 @@ describe('manipulation', function () {
created.toObject().should.have.properties({ created.toObject().should.have.properties({
id: created.id, id: created.id,
name: 'a-name', name: 'a-name',
gender: undefined gender: undefined,
}); });
Person.findById(created.id, function(err, found) { Person.findById(created.id, function(err, found) {
@ -297,7 +297,7 @@ describe('manipulation', function () {
var result = found.toObject(); var result = found.toObject();
result.should.have.properties({ result.should.have.properties({
id: created.id, id: created.id,
name: 'a-name' name: 'a-name',
}); });
// The gender can be null from a RDB // The gender can be null from a RDB
should.equal(result.gender, null); should.equal(result.gender, null);
@ -430,7 +430,7 @@ describe('manipulation', function () {
}; };
(function() { (function() {
p.save({ p.save({
'throws': true 'throws': true,
}); });
}).should.throw(ValidationError); }).should.throw(ValidationError);
}); });
@ -648,7 +648,7 @@ describe('manipulation', function () {
var fakeConnector = { var 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'));
} },
}; };
person.getConnector = function() { return fakeConnector; }; person.getConnector = function() { return fakeConnector; };
person.updateAttributes({ name: 'John' }, function(err, p) { person.updateAttributes({ name: 'John' }, function(err, p) {
@ -699,7 +699,7 @@ describe('manipulation', function () {
instance.toObject().should.have.properties({ instance.toObject().should.have.properties({
id: instance.id, id: instance.id,
name: 'a-name', name: 'a-name',
gender: undefined gender: undefined,
}); });
Person.updateOrCreate( Person.updateOrCreate(
@ -709,7 +709,7 @@ describe('manipulation', function () {
var result = updated.toObject(); var result = updated.toObject();
result.should.have.properties({ result.should.have.properties({
id: instance.id, id: instance.id,
name: 'updated name' name: 'updated name',
}); });
should.equal(result.gender, null); should.equal(result.gender, null);
done(); done();
@ -737,7 +737,7 @@ describe('manipulation', function () {
Post = ds.define('Post', { Post = ds.define('Post', {
title: { type: String, length: 255, index: true }, title: { type: String, length: 255, index: true },
content: { type: String }, content: { type: String },
comments: [String] comments: [String],
}); });
ds.automigrate('Post', done); ds.automigrate('Post', done);
}); });
@ -954,7 +954,7 @@ describe('manipulation', function () {
Post = ds.define('Post', { Post = ds.define('Post', {
title: { type: String, length: 255, index: true }, title: { type: String, length: 255, index: true },
content: { type: String }, content: { type: String },
comments: [String] comments: [String],
}); });
ds.automigrate('Post', done); ds.automigrate('Post', done);
}); });
@ -1189,9 +1189,9 @@ describe('manipulation', function () {
beforeEach(function createTestData(done) { beforeEach(function createTestData(done) {
Person.create([{ Person.create([{
name: 'John' name: 'John',
}, { }, {
name: 'Jane' name: 'Jane',
}], done); }], done);
}); });
@ -1347,7 +1347,7 @@ describe('manipulation', function () {
before(function(done) { before(function(done) {
CustomModel = db.define('CustomModel1', { CustomModel = db.define('CustomModel1', {
createdAt: { type: Date, default: '$now' } createdAt: { type: Date, default: '$now' },
}); });
db.automigrate('CustomModel1', done); db.automigrate('CustomModel1', done);
}); });
@ -1371,7 +1371,7 @@ describe('manipulation', function () {
before(function(done) { before(function(done) {
CustomModel = db.define('CustomModel2', { CustomModel = db.define('CustomModel2', {
now: { type: String, default: '$now' } now: { type: String, default: '$now' },
}); });
db.automigrate('CustomModel2', done); db.automigrate('CustomModel2', done);
}); });
@ -1393,7 +1393,7 @@ describe('manipulation', function () {
before(function(done) { before(function(done) {
CustomModel = db.define('CustomModel3', { CustomModel = db.define('CustomModel3', {
now: { type: Date, defaultFn: 'now' } now: { type: Date, defaultFn: 'now' },
}); });
db.automigrate('CustomModel3', done); db.automigrate('CustomModel3', done);
}); });
@ -1415,7 +1415,7 @@ describe('manipulation', function () {
before(function(done) { before(function(done) {
CustomModel = db.define('CustomModel4', { CustomModel = db.define('CustomModel4', {
guid: { type: String, defaultFn: 'guid' } guid: { type: String, defaultFn: 'guid' },
}); });
db.automigrate('CustomModel4', done); db.automigrate('CustomModel4', done);
}); });
@ -1434,7 +1434,7 @@ describe('manipulation', function () {
before(function(done) { before(function(done) {
CustomModel = db.define('CustomModel5', { CustomModel = db.define('CustomModel5', {
guid: { type: String, defaultFn: 'uuid' } guid: { type: String, defaultFn: 'uuid' },
}); });
db.automigrate('CustomModel5', done); db.automigrate('CustomModel5', done);
}); });
@ -1454,7 +1454,7 @@ describe('manipulation', function () {
before(function(done) { before(function(done) {
CustomModel = db.define('CustomModel5', { CustomModel = db.define('CustomModel5', {
guid: { type: String, defaultFn: 'uuidv4' } guid: { type: String, defaultFn: 'uuidv4' },
}); });
db.automigrate('CustomModel5', done); db.automigrate('CustomModel5', done);
}); });
@ -1554,19 +1554,19 @@ describe('manipulation', function () {
beforeEach(function createTestData(done) { beforeEach(function createTestData(done) {
Person.create([{ Person.create([{
name: 'Brett Boe', name: 'Brett Boe',
age: 19 age: 19,
}, { }, {
name: 'Carla Coe', name: 'Carla Coe',
age: 20 age: 20,
}, { }, {
name: 'Donna Doe', name: 'Donna Doe',
age: 21 age: 21,
}, { }, {
name: 'Frank Foe', name: 'Frank Foe',
age: 22 age: 22,
}, { }, {
name: 'Grace Goe', name: 'Grace Goe',
age: 23 age: 23,
}], done); }], done);
}); });
@ -1654,13 +1654,13 @@ function givenSomePeople(done) {
{ name: 'George Harrison', gender: 'male' }, { name: 'George Harrison', gender: 'male' },
{ name: 'Ringo Starr', gender: 'male' }, { name: 'Ringo Starr', gender: 'male' },
{ name: 'Pete Best', gender: 'male' }, { name: 'Pete Best', gender: 'male' },
{ name: 'Stuart Sutcliffe', gender: 'male' } { name: 'Stuart Sutcliffe', gender: 'male' },
]; ];
async.series([ async.series([
Person.destroyAll.bind(Person), Person.destroyAll.bind(Person),
function(cb) { function(cb) {
async.each(beatles, Person.create.bind(Person), cb); async.each(beatles, Person.create.bind(Person), cb);
} },
], done); ], done);
} }

View File

@ -36,20 +36,20 @@ describe('Memory connector', function() {
function createUserModel() { function createUserModel() {
var ds = new DataSource({ var ds = new DataSource({
connector: 'memory', connector: 'memory',
file: file file: file,
}); });
var User = ds.createModel('User', { var User = ds.createModel('User', {
id: { id: {
type: Number, type: Number,
id: true, id: true,
generated: true generated: true,
}, },
name: String, name: String,
bio: String, bio: String,
approved: Boolean, approved: Boolean,
joinedAt: Date, joinedAt: Date,
age: Number age: Number,
}); });
return User; return User;
} }
@ -141,7 +141,7 @@ describe('Memory connector', function() {
describe('Query for memory connector', function() { describe('Query for memory connector', function() {
var ds = new DataSource({ var ds = new DataSource({
connector: 'memory' connector: 'memory',
}); });
var User = ds.define('User', { var User = ds.define('User', {
@ -156,13 +156,13 @@ describe('Memory connector', function() {
street: String, street: String,
city: String, city: String,
state: String, state: String,
zipCode: String zipCode: String,
}, },
friends: [ friends: [
{ {
name: String name: String,
} },
] ],
}); });
before(seed); before(seed);
@ -318,9 +318,9 @@ describe('Memory connector', function() {
User.find({ User.find({
where: { where: {
children: { children: {
regexp: /an/ regexp: /an/,
} },
} },
}, function(err, users) { }, function(err, users) {
should.not.exist(err); should.not.exist(err);
users.length.should.be.equal(2); users.length.should.be.equal(2);
@ -333,8 +333,8 @@ describe('Memory connector', function() {
it('should successfully extract 1 users matching over array values', function(done) { it('should successfully extract 1 users matching over array values', function(done) {
User.find({ User.find({
where: { where: {
children: 'Dhani' children: 'Dhani',
} },
}, function(err, users) { }, function(err, users) {
should.not.exist(err); should.not.exist(err);
users.length.should.be.equal(1); users.length.should.be.equal(1);
@ -346,8 +346,8 @@ describe('Memory connector', function() {
it('should successfully extract 5 users matching a neq filter over array values', function(done) { it('should successfully extract 5 users matching a neq filter over array values', function(done) {
User.find({ User.find({
where: { where: {
'children': {neq: 'Dhani'} 'children': { neq: 'Dhani' },
} },
}, function(err, users) { }, function(err, users) {
should.not.exist(err); should.not.exist(err);
users.length.should.be.equal(5); users.length.should.be.equal(5);
@ -531,14 +531,14 @@ describe('Memory connector', function() {
street: '123 A St', street: '123 A St',
city: 'San Jose', city: 'San Jose',
state: 'CA', state: 'CA',
zipCode: '95131' zipCode: '95131',
}, },
friends: [ friends: [
{ name: 'Paul McCartney' }, { name: 'Paul McCartney' },
{ name: 'George Harrison' }, { name: 'George Harrison' },
{ name: 'Ringo Starr' }, { name: 'Ringo Starr' },
], ],
children: ['Sean', 'Julian'] children: ['Sean', 'Julian'],
}, },
{ {
seq: 1, seq: 1,
@ -552,26 +552,26 @@ describe('Memory connector', function() {
street: '456 B St', street: '456 B St',
city: 'San Mateo', city: 'San Mateo',
state: 'CA', state: 'CA',
zipCode: '94065' zipCode: '94065',
}, },
friends: [ friends: [
{ name: 'John Lennon' }, { name: 'John Lennon' },
{ name: 'George Harrison' }, { name: 'George Harrison' },
{ name: 'Ringo Starr' }, { name: 'Ringo Starr' },
], ],
children: ['Stella', 'Mary', 'Heather', 'Beatrice', 'James'] children: ['Stella', 'Mary', 'Heather', 'Beatrice', 'James'],
}, },
{ seq: 2, name: 'George Harrison', order: 5, vip: false, children: ['Dhani'] }, { seq: 2, name: 'George Harrison', order: 5, vip: false, children: ['Dhani'] },
{ seq: 3, name: 'Ringo Starr', order: 6, vip: false }, { seq: 3, name: 'Ringo Starr', order: 6, vip: false },
{ seq: 4, name: 'Pete Best', order: 4, children: [] }, { seq: 4, name: 'Pete Best', order: 4, children: [] },
{seq: 5, name: 'Stuart Sutcliffe', order: 3, vip: true} { seq: 5, name: 'Stuart Sutcliffe', order: 3, vip: true },
]; ];
async.series([ async.series([
User.destroyAll.bind(User), User.destroyAll.bind(User),
function(cb) { function(cb) {
async.each(beatles, User.create.bind(User), cb); async.each(beatles, User.create.bind(User), cb);
} },
], done); ], done);
} }
@ -579,19 +579,19 @@ describe('Memory connector', function() {
it('should use collection setting', function(done) { it('should use collection setting', function(done) {
var ds = new DataSource({ var ds = new DataSource({
connector: 'memory' connector: 'memory',
}); });
var Product = ds.createModel('Product', { var Product = ds.createModel('Product', {
name: String name: String,
}); });
var Tool = ds.createModel('Tool', { var Tool = ds.createModel('Tool', {
name: String name: String,
}, { memory: { collection: 'Product' }}); }, { memory: { collection: 'Product' }});
var Widget = ds.createModel('Widget', { var Widget = ds.createModel('Widget', {
name: String name: String,
}, { memory: { collection: 'Product' }}); }, { memory: { collection: 'Product' }});
ds.connector.getCollection('Tool').should.equal('Product'); ds.connector.getCollection('Tool').should.equal('Product');
@ -606,7 +606,7 @@ describe('Memory connector', function() {
}, },
function(next) { function(next) {
Widget.create({ name: 'Widget A' }, next); Widget.create({ name: 'Widget A' }, next);
} },
], function(err) { ], function(err) {
Product.find(function(err, products) { Product.find(function(err, products) {
should.not.exist(err); should.not.exist(err);
@ -623,11 +623,11 @@ describe('Memory connector', function() {
var ds; var ds;
beforeEach(function() { beforeEach(function() {
ds = new DataSource({ ds = new DataSource({
connector: 'memory' connector: 'memory',
}); });
ds.createModel('m1', { ds.createModel('m1', {
name: String name: String,
}); });
}); });
@ -704,7 +704,7 @@ describe('Memory connector', function() {
before(function() { before(function() {
ds = new DataSource({ connector: 'memory' }); ds = new DataSource({ connector: 'memory' });
Cars = ds.define('Cars', { Cars = ds.define('Cars', {
color: String color: String,
}); });
}); });
@ -735,14 +735,14 @@ describe('Memory connector', function() {
var ds; var ds;
beforeEach(function() { beforeEach(function() {
ds = new DataSource({ ds = new DataSource({
connector: 'memory' connector: 'memory',
}); });
}); });
it('automigrate does NOT report error when NO models are attached', function(done) { it('automigrate does NOT report error when NO models are attached', function(done) {
ds.automigrate(function(err) { ds.automigrate(function(err) {
done(); done();
}) });
}); });
it('automigrate does NOT report error when NO models are attached - promise variant', function(done) { it('automigrate does NOT report error when NO models are attached - promise variant', function(done) {
@ -758,7 +758,7 @@ describe('Memory connector', function() {
var ds, model; var ds, model;
beforeEach(function() { beforeEach(function() {
ds = new DataSource({ ds = new DataSource({
connector: 'memory' connector: 'memory',
}); });
ds.connector.autoupdate = function(models, cb) { ds.connector.autoupdate = function(models, cb) {
@ -766,14 +766,14 @@ describe('Memory connector', function() {
}; };
model = ds.createModel('m1', { model = ds.createModel('m1', {
name: String name: String,
}); });
ds.automigrate(); ds.automigrate();
ds.createModel('m1', { ds.createModel('m1', {
name: String, name: String,
address: String address: String,
}); });
}); });
@ -898,7 +898,7 @@ describe('Memory connector with options', function() {
Post = ds.define('Post', { Post = ds.define('Post', {
title: String, title: String,
content: String content: String,
}); });
}); });
@ -947,7 +947,7 @@ describe('Memory connector with options', function() {
describe('Memory connector with observers', function() { describe('Memory connector with observers', function() {
var ds = new DataSource({ var ds = new DataSource({
connector: 'memory' connector: 'memory',
}); });
it('should have observer mixed into the connector', function() { it('should have observer mixed into the connector', function() {

View File

@ -65,12 +65,12 @@ describe('Model class', function () {
it('should apply a mixin class', function() { it('should apply a mixin class', function() {
var Address = modelBuilder.define('Address', { var 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); var memory = new DataSource('mem', { connector: Memory }, modelBuilder);
var Item = memory.createModel('Item', { name: 'string' }, { var Item = memory.createModel('Item', { name: 'string' }, {
mixins: { Address: true } mixins: { Address: true },
}); });
var properties = Item.definition.properties; var properties = Item.definition.properties;
@ -86,9 +86,9 @@ describe('Model class', function () {
TimeStamp: true, Demo: { value: true }, TimeStamp: true, Demo: { value: true },
Multi: [ Multi: [
{ key: 'foo', value: 'bar' }, { key: 'foo', value: 'bar' },
{ key: 'fox', value: 'baz' } { key: 'fox', value: 'baz' },
] ],
} },
}); });
Item.mixin('Example', { foo: 'bar' }); Item.mixin('Example', { foo: 'bar' });
@ -117,7 +117,7 @@ describe('Model class', function () {
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); var memory = new DataSource('mem', { connector: Memory }, modelBuilder);
Person = memory.createModel('Person', { name: 'string' }); Person = memory.createModel('Person', { name: 'string' });

View File

@ -24,11 +24,11 @@ describe('ModelDefinition class', function () {
var modelBuilder = new ModelBuilder(); var modelBuilder = new ModelBuilder();
var User = new ModelDefinition(modelBuilder, 'User', { var User = new ModelDefinition(modelBuilder, 'User', {
name: "string", name: 'string',
bio: ModelBuilder.Text, bio: ModelBuilder.Text,
approved: Boolean, approved: Boolean,
joinedAt: Date, joinedAt: Date,
age: "number" age: 'number',
}); });
User.build(); User.build();
@ -39,12 +39,12 @@ describe('ModelDefinition class', function () {
assert.equal(User.properties.age.type, Number); assert.equal(User.properties.age.type, Number);
var json = User.toJSON(); var 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');
assert.equal(json.properties.approved.type, "Boolean"); assert.equal(json.properties.approved.type, 'Boolean');
assert.equal(json.properties.joinedAt.type, "Date"); assert.equal(json.properties.joinedAt.type, 'Date');
assert.equal(json.properties.age.type, "Number"); assert.equal(json.properties.age.type, 'Number');
assert.deepEqual(User.toJSON(), json); assert.deepEqual(User.toJSON(), json);
@ -56,18 +56,18 @@ describe('ModelDefinition class', function () {
var modelBuilder = new ModelBuilder(); var modelBuilder = new ModelBuilder();
var User = new ModelDefinition(modelBuilder, 'User', { var User = new ModelDefinition(modelBuilder, 'User', {
name: "string", name: 'string',
bio: ModelBuilder.Text, bio: ModelBuilder.Text,
approved: Boolean, approved: Boolean,
joinedAt: Date, joinedAt: Date,
age: "number" age: 'number',
}); });
User.build(); User.build();
var json = User.toJSON(); var 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);
assert.equal(User.properties.bio.type, ModelBuilder.Text); assert.equal(User.properties.bio.type, ModelBuilder.Text);
assert.equal(User.properties.approved.type, Boolean); assert.equal(User.properties.approved.type, Boolean);
@ -96,8 +96,8 @@ describe('ModelDefinition class', function () {
street: String, street: String,
city: String, city: String,
zipCode: String, zipCode: String,
state: String state: String,
} },
}); });
User.build(); User.build();
@ -109,12 +109,12 @@ describe('ModelDefinition class', function () {
assert.equal(typeof User.properties.address.type, 'function'); assert.equal(typeof User.properties.address.type, 'function');
var json = User.toJSON(); var 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');
assert.equal(json.properties.approved.type, "Boolean"); assert.equal(json.properties.approved.type, 'Boolean');
assert.equal(json.properties.joinedAt.type, "Date"); assert.equal(json.properties.joinedAt.type, 'Date');
assert.equal(json.properties.age.type, "Number"); assert.equal(json.properties.age.type, 'Number');
assert.deepEqual(json.properties.address.type, { street: { type: 'String' }, assert.deepEqual(json.properties.address.type, { street: { type: 'String' },
city: { type: 'String' }, city: { type: 'String' },
@ -132,7 +132,7 @@ describe('ModelDefinition class', function () {
street: String, street: String,
city: String, city: String,
zipCode: String, zipCode: String,
state: String state: String,
}); });
var User = new ModelDefinition(modelBuilder, 'User', { var User = new ModelDefinition(modelBuilder, 'User', {
name: String, name: String,
@ -140,7 +140,7 @@ describe('ModelDefinition class', function () {
approved: Boolean, approved: Boolean,
joinedAt: Date, joinedAt: Date,
age: Number, age: Number,
address: Address address: Address,
}); });
@ -153,12 +153,12 @@ describe('ModelDefinition class', function () {
assert.equal(User.properties.address.type, Address); assert.equal(User.properties.address.type, Address);
var json = User.toJSON(); var 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');
assert.equal(json.properties.approved.type, "Boolean"); assert.equal(json.properties.approved.type, 'Boolean');
assert.equal(json.properties.joinedAt.type, "Date"); assert.equal(json.properties.joinedAt.type, 'Date');
assert.equal(json.properties.age.type, "Number"); assert.equal(json.properties.age.type, 'Number');
assert.equal(json.properties.address.type, 'Address'); assert.equal(json.properties.address.type, 'Address');
@ -173,7 +173,7 @@ describe('ModelDefinition class', function () {
street: String, street: String,
city: String, city: String,
zipCode: String, zipCode: String,
state: String state: String,
}); });
var User = new ModelDefinition(modelBuilder, 'User', { var User = new ModelDefinition(modelBuilder, 'User', {
name: String, name: String,
@ -181,7 +181,7 @@ describe('ModelDefinition class', function () {
approved: Boolean, approved: Boolean,
joinedAt: Date, joinedAt: Date,
age: Number, age: Number,
address: 'Address' address: 'Address',
}); });
@ -194,12 +194,12 @@ describe('ModelDefinition class', function () {
assert.equal(User.properties.address.type, Address); assert.equal(User.properties.address.type, Address);
var json = User.toJSON(); var 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');
assert.equal(json.properties.approved.type, "Boolean"); assert.equal(json.properties.approved.type, 'Boolean');
assert.equal(json.properties.joinedAt.type, "Date"); assert.equal(json.properties.joinedAt.type, 'Date');
assert.equal(json.properties.age.type, "Number"); assert.equal(json.properties.age.type, 'Number');
assert.equal(json.properties.address.type, 'Address'); assert.equal(json.properties.address.type, 'Address');
@ -212,11 +212,11 @@ describe('ModelDefinition class', function () {
var User = new ModelDefinition(modelBuilder, 'User', { var 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,
approved: Boolean, approved: Boolean,
joinedAt: Date, joinedAt: Date,
age: "number" age: 'number',
}); });
assert.equal(User.idName(), 'userId'); assert.equal(User.idName(), 'userId');
@ -230,11 +230,11 @@ describe('ModelDefinition class', function () {
var User = new ModelDefinition(modelBuilder, 'User', { var 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',
bio: ModelBuilder.Text, bio: ModelBuilder.Text,
approved: Boolean, approved: Boolean,
joinedAt: Date, joinedAt: Date,
age: "number" age: 'number',
}); });
var ids = User.ids(); var ids = User.ids();
@ -251,7 +251,7 @@ describe('ModelDefinition class', function () {
var User = new ModelDefinition(modelBuilder, 'User', { var 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' }});
assert.equal(User.tableName('oracle'), 'USER'); assert.equal(User.tableName('oracle'), 'USER');
@ -267,9 +267,9 @@ describe('ModelDefinition class', function () {
relations: { relations: {
children: { children: {
type: 'hasMany', type: 'hasMany',
model: 'anotherChild' model: 'anotherChild',
} },
} },
}); });
var baseChild = modelBuilder.define('baseChild'); var baseChild = modelBuilder.define('baseChild');
baseChild.attachTo(memory); baseChild.attachTo(memory);
@ -301,14 +301,14 @@ describe('ModelDefinition class', function () {
it('should serialize protected properties into JSON', function() { it('should serialize protected properties into JSON', function() {
var modelBuilder = memory.modelBuilder; var modelBuilder = memory.modelBuilder;
var ProtectedModel = memory.createModel('protected', {}, { var ProtectedModel = memory.createModel('protected', {}, {
protected: ['protectedProperty'] protected: ['protectedProperty'],
}); });
var pm = new ProtectedModel({ var pm = new ProtectedModel({
id: 1, foo: 'bar', protectedProperty: 'protected' id: 1, foo: 'bar', protectedProperty: 'protected',
}); });
var serialized = pm.toJSON(); var serialized = pm.toJSON();
assert.deepEqual(serialized, { assert.deepEqual(serialized, {
id: 1, foo: 'bar', protectedProperty: 'protected' id: 1, foo: 'bar', protectedProperty: 'protected',
}); });
}); });
@ -318,11 +318,11 @@ describe('ModelDefinition class', function () {
var Child = memory.createModel('child', {}, { protected: ['protectedProperty'] }); var Child = memory.createModel('child', {}, { protected: ['protectedProperty'] });
Parent.hasMany(Child); Parent.hasMany(Child);
Parent.create({ Parent.create({
name: 'parent' name: 'parent',
}, function(err, parent) { }, function(err, parent) {
parent.children.create({ parent.children.create({
name: 'child', name: 'child',
protectedProperty: 'protectedValue' protectedProperty: 'protectedValue',
}, function(err, child) { }, function(err, child) {
Parent.find({ include: 'children' }, function(err, parents) { Parent.find({ include: 'children' }, function(err, parents) {
var serialized = parents[0].toJSON(); var serialized = parents[0].toJSON();
@ -338,17 +338,17 @@ describe('ModelDefinition class', function () {
it('should not serialize hidden properties into JSON', function() { it('should not serialize hidden properties into JSON', function() {
var modelBuilder = memory.modelBuilder; var modelBuilder = memory.modelBuilder;
var HiddenModel = memory.createModel('hidden', {}, { var HiddenModel = memory.createModel('hidden', {}, {
hidden: ['secret'] hidden: ['secret'],
}); });
var hm = new HiddenModel({ var hm = new HiddenModel({
id: 1, id: 1,
foo: 'bar', foo: 'bar',
secret: 'secret' secret: 'secret',
}); });
var serialized = hm.toJSON(); var serialized = hm.toJSON();
assert.deepEqual(serialized, { assert.deepEqual(serialized, {
id: 1, id: 1,
foo: 'bar' foo: 'bar',
}); });
}); });
@ -358,11 +358,11 @@ describe('ModelDefinition class', function () {
var Child = memory.createModel('child', {}, { hidden: ['secret'] }); var Child = memory.createModel('child', {}, { hidden: ['secret'] });
Parent.hasMany(Child); Parent.hasMany(Child);
Parent.create({ Parent.create({
name: 'parent' name: 'parent',
}, function(err, parent) { }, function(err, parent) {
parent.children.create({ parent.children.create({
name: 'child', name: 'child',
secret: 'secret' secret: 'secret',
}, function(err, child) { }, function(err, child) {
Parent.find({ include: 'children' }, function(err, parents) { Parent.find({ include: 'children' }, function(err, parents) {
var serialized = parents[0].toJSON(); var serialized = parents[0].toJSON();
@ -399,7 +399,7 @@ describe('ModelDefinition class', function () {
it('should support "array" type shortcut', function() { it('should support "array" type shortcut', function() {
var Model = memory.createModel('TwoArrays', { var Model = memory.createModel('TwoArrays', {
regular: Array, regular: Array,
sugar: 'array' sugar: 'array',
}); });
var props = Model.definition.properties; var props = Model.definition.properties;
@ -411,11 +411,11 @@ describe('ModelDefinition class', function () {
var Todo; var Todo;
before(function prepModel() { before(function prepModel() {
Todo = new ModelDefinition(new ModelBuilder(), 'Todo', { Todo = new ModelDefinition(new ModelBuilder(), 'Todo', {
content: 'string' content: 'string',
}); });
Todo.defineProperty('id', { Todo.defineProperty('id', {
type: 'number', type: 'number',
id: true id: true,
}); });
Todo.build(); Todo.build();
}); });
@ -429,7 +429,7 @@ describe('ModelDefinition class', function () {
var Todo; var Todo;
before(function prepModel() { before(function prepModel() {
Todo = new ModelDefinition(new ModelBuilder(), 'Todo', { Todo = new ModelDefinition(new ModelBuilder(), 'Todo', {
content: 'string' content: 'string',
}); });
Todo.build(); Todo.build();
}); });

View File

@ -30,7 +30,7 @@ describe('optional-validation', function () {
birthday: { type: Date, index: true }, birthday: { type: Date, index: true },
role: { type: String, index: true }, role: { type: String, index: true },
order: { type: Number, index: true, sort: true }, order: { type: Number, index: true, sort: true },
vip: {type: Boolean} vip: { type: Boolean },
}, { forceId: true, strict: true }); }, { forceId: true, strict: true });
db.automigrate(['ModelWithForceId', 'User'], done); db.automigrate(['ModelWithForceId', 'User'], done);
}); });
@ -136,7 +136,6 @@ describe('optional-validation', function () {
}); });
}); });
describe('no model setting', function() { describe('no model setting', function() {
describe('method create', function() { describe('method create', function() {

View File

@ -36,7 +36,7 @@ module.exports = function(dataSource, should, connectorCapabilities) {
// Set id.generated to false to honor client side values // Set id.generated to false to honor client side values
id: { type: String, id: true, generated: false, default: uid.next }, id: { type: String, id: true, generated: false, default: uid.next },
name: { type: String, required: true }, name: { type: String, required: true },
extra: { type: String, required: false } extra: { type: String, required: false },
}); });
uid.reset(); uid.reset();
@ -79,7 +79,7 @@ module.exports = function(dataSource, should, connectorCapabilities) {
hookMonitor.names.should.eql([ hookMonitor.names.should.eql([
'access', 'access',
'loaded' 'loaded',
]); ]);
done(); done();
}); });
@ -165,7 +165,7 @@ module.exports = function(dataSource, should, connectorCapabilities) {
})); }));
done(); done();
}); });
}) });
it('emits error when `loaded` hook fails', function(done) { it('emits error when `loaded` hook fails', function(done) {
TestModel.observe('loaded', nextWithError(expectedError)); TestModel.observe('loaded', nextWithError(expectedError));
@ -191,7 +191,7 @@ module.exports = function(dataSource, should, connectorCapabilities) {
'before save', 'before save',
'persist', 'persist',
'loaded', 'loaded',
'after save' 'after save',
]); ]);
done(); done();
}); });
@ -206,9 +206,9 @@ module.exports = function(dataSource, should, connectorCapabilities) {
instance: { instance: {
id: instance.id, id: instance.id,
name: 'created', name: 'created',
extra: undefined extra: undefined,
}, },
isNewInstance: true isNewInstance: true,
})); }));
done(); done();
}); });
@ -251,11 +251,11 @@ module.exports = function(dataSource, should, connectorCapabilities) {
ctxRecorder.records.should.eql([ ctxRecorder.records.should.eql([
aCtxForModel(TestModel, { aCtxForModel(TestModel, {
instance: { id: list[0].id, name: '1', extra: undefined }, instance: { id: list[0].id, name: '1', extra: undefined },
isNewInstance: true isNewInstance: true,
}), }),
aCtxForModel(TestModel, { aCtxForModel(TestModel, {
instance: { id: list[1].id, name: '2', extra: undefined }, instance: { id: list[1].id, name: '2', extra: undefined },
isNewInstance: true isNewInstance: true,
}), }),
]); ]);
done(); done();
@ -283,7 +283,7 @@ module.exports = function(dataSource, should, connectorCapabilities) {
ctxRecorder.records.should.eql(aCtxForModel(TestModel, { ctxRecorder.records.should.eql(aCtxForModel(TestModel, {
data: { id: 'new-id', name: 'a name' }, data: { id: 'new-id', name: 'a name' },
isNewInstance: true, isNewInstance: true,
currentInstance: { extra: null, id: 'new-id', name: 'a name' } currentInstance: { extra: null, id: 'new-id', name: 'a name' },
})); }));
done(); done();
@ -315,7 +315,7 @@ module.exports = function(dataSource, should, connectorCapabilities) {
dbInstance.toObject(true).should.eql({ dbInstance.toObject(true).should.eql({
id: 'new-id', id: 'new-id',
name: 'a name', name: 'a name',
extra: 'hook data' extra: 'hook data',
}); });
done(); done();
}); });
@ -338,7 +338,7 @@ module.exports = function(dataSource, should, connectorCapabilities) {
ctxRecorder.records.should.eql(aCtxForModel(TestModel, { ctxRecorder.records.should.eql(aCtxForModel(TestModel, {
data: { id: 'new-id', name: 'a name' }, data: { id: 'new-id', name: 'a name' },
isNewInstance: true isNewInstance: true,
})); }));
done(); done();
@ -384,9 +384,9 @@ module.exports = function(dataSource, should, connectorCapabilities) {
instance: { instance: {
id: instance.id, id: instance.id,
name: 'created', name: 'created',
extra: undefined extra: undefined,
}, },
isNewInstance: true isNewInstance: true,
})); }));
done(); done();
}); });
@ -429,11 +429,11 @@ module.exports = function(dataSource, should, connectorCapabilities) {
ctxRecorder.records.should.eql([ ctxRecorder.records.should.eql([
aCtxForModel(TestModel, { aCtxForModel(TestModel, {
instance: { id: list[0].id, name: '1', extra: undefined }, instance: { id: list[0].id, name: '1', extra: undefined },
isNewInstance: true isNewInstance: true,
}), }),
aCtxForModel(TestModel, { aCtxForModel(TestModel, {
instance: { id: list[1].id, name: '2', extra: undefined }, instance: { id: list[1].id, name: '2', extra: undefined },
isNewInstance: true isNewInstance: true,
}), }),
]); ]);
done(); done();
@ -463,7 +463,7 @@ module.exports = function(dataSource, should, connectorCapabilities) {
ctxRecorder.records.should.eql(aCtxForModel(TestModel, { ctxRecorder.records.should.eql(aCtxForModel(TestModel, {
instance: { id: list[0].id, name: 'ok', extra: undefined }, instance: { id: list[0].id, name: 'ok', extra: undefined },
isNewInstance: true isNewInstance: true,
})); }));
done(); done();
}); });
@ -483,7 +483,7 @@ module.exports = function(dataSource, should, connectorCapabilities) {
where: { name: 'new-record' }, where: { name: 'new-record' },
limit: 1, limit: 1,
offset: 0, offset: 0,
skip: 0 skip: 0,
}})); }}));
done(); done();
}); });
@ -503,9 +503,9 @@ module.exports = function(dataSource, should, connectorCapabilities) {
instance: { instance: {
id: getLastGeneratedUid(), id: getLastGeneratedUid(),
name: existingInstance.name, name: existingInstance.name,
extra: undefined extra: undefined,
}, },
isNewInstance: true isNewInstance: true,
})); }));
done(); done();
}); });
@ -524,9 +524,9 @@ module.exports = function(dataSource, should, connectorCapabilities) {
instance: { instance: {
id: record.id, id: record.id,
name: 'new-record', name: 'new-record',
extra: undefined extra: undefined,
}, },
isNewInstance: true isNewInstance: true,
})); }));
done(); done();
}); });
@ -558,7 +558,7 @@ module.exports = function(dataSource, should, connectorCapabilities) {
'before save', 'before save',
'persist', 'persist',
'loaded', 'loaded',
'after save' 'after save',
]); ]);
done(); done();
}); });
@ -578,12 +578,12 @@ module.exports = function(dataSource, should, connectorCapabilities) {
'access', 'access',
'before save', 'before save',
'persist', 'persist',
'loaded' 'loaded',
]); ]);
} else { } else {
hookMonitor.names.should.eql([ hookMonitor.names.should.eql([
'access', 'access',
'loaded' 'loaded',
]); ]);
} }
done(); done();
@ -635,15 +635,15 @@ module.exports = function(dataSource, should, connectorCapabilities) {
ctxRecorder.records.should.eql(aCtxForModel(TestModel, { ctxRecorder.records.should.eql(aCtxForModel(TestModel, {
data: { data: {
id: getLastGeneratedUid(), id: getLastGeneratedUid(),
name: existingInstance.name name: existingInstance.name,
}, },
isNewInstance: true, isNewInstance: true,
currentInstance: { currentInstance: {
id: getLastGeneratedUid(), id: getLastGeneratedUid(),
name: record.name, name: record.name,
extra: null extra: null,
}, },
where: { name: existingInstance.name } where: { name: existingInstance.name },
})); }));
done(); done();
@ -666,24 +666,24 @@ module.exports = function(dataSource, should, connectorCapabilities) {
ctxRecorder.records.should.eql(aCtxForModel(TestModel, { ctxRecorder.records.should.eql(aCtxForModel(TestModel, {
data: { data: {
id: record.id, id: record.id,
name: 'new-record' name: 'new-record',
}, },
isNewInstance: true, isNewInstance: true,
currentInstance: { currentInstance: {
id: record.id, id: record.id,
name: record.name, name: record.name,
extra: null extra: null,
}, },
where: { name: 'new-record' } where: { name: 'new-record' },
})); }));
} else { } else {
ctxRecorder.records.should.eql(aCtxForModel(TestModel, { ctxRecorder.records.should.eql(aCtxForModel(TestModel, {
data: { data: {
id: record.id, id: record.id,
name: 'new-record' name: 'new-record',
}, },
isNewInstance: true, isNewInstance: true,
currentInstance: { id: record.id, name: record.name, extra: null } currentInstance: { id: record.id, name: record.name, extra: null },
})); }));
} }
done(); done();
@ -715,7 +715,7 @@ module.exports = function(dataSource, should, connectorCapabilities) {
dbInstance.toObject(true).should.eql({ dbInstance.toObject(true).should.eql({
id: existingInstance.id, id: existingInstance.id,
name: existingInstance.name, name: existingInstance.name,
extra: undefined extra: undefined,
}); });
}); });
@ -753,7 +753,7 @@ module.exports = function(dataSource, should, connectorCapabilities) {
dbInstance.toObject(true).should.eql({ dbInstance.toObject(true).should.eql({
id: instance.id, id: instance.id,
name: instance.name, name: instance.name,
extra: 'hook data' extra: 'hook data',
}); });
}); });
} }
@ -779,9 +779,9 @@ module.exports = function(dataSource, should, connectorCapabilities) {
ctxRecorder.records.should.eql(aCtxForModel(TestModel, { ctxRecorder.records.should.eql(aCtxForModel(TestModel, {
data: { data: {
id: existingInstance.id, id: existingInstance.id,
name: existingInstance.name name: existingInstance.name,
}, },
isNewInstance: false isNewInstance: false,
})); }));
done(); done();
@ -801,9 +801,9 @@ module.exports = function(dataSource, should, connectorCapabilities) {
ctxRecorder.records.should.eql(aCtxForModel(TestModel, { ctxRecorder.records.should.eql(aCtxForModel(TestModel, {
data: { data: {
id: record.id, id: record.id,
name: 'new-record' name: 'new-record',
}, },
isNewInstance: true isNewInstance: true,
})); }));
done(); done();
@ -876,9 +876,9 @@ module.exports = function(dataSource, should, connectorCapabilities) {
instance: { instance: {
id: instance.id, id: instance.id,
name: 'new name', name: 'new name',
extra: undefined extra: undefined,
}, },
isNewInstance: true isNewInstance: true,
})); }));
done(); done();
}); });
@ -936,7 +936,7 @@ module.exports = function(dataSource, should, connectorCapabilities) {
'before save', 'before save',
'persist', 'persist',
'loaded', 'loaded',
'after save' 'after save',
]); ]);
done(); done();
}); });
@ -1003,14 +1003,14 @@ module.exports = function(dataSource, should, connectorCapabilities) {
ctxRecorder.records.should.eql(aCtxForModel(TestModel, { ctxRecorder.records.should.eql(aCtxForModel(TestModel, {
data: { data: {
id: existingInstance.id, id: existingInstance.id,
name: 'changed' name: 'changed',
}, },
currentInstance: { currentInstance: {
id: existingInstance.id, id: existingInstance.id,
name: 'changed' name: 'changed',
}, },
where: { id: existingInstance.id }, where: { id: existingInstance.id },
options: { throws: false, validate: true } options: { throws: false, validate: true },
})); }));
done(); done();
@ -1043,7 +1043,7 @@ module.exports = function(dataSource, should, connectorCapabilities) {
extra: 'changed', extra: 'changed',
}, },
isNewInstance: false, isNewInstance: false,
options: { throws: false, validate: true } options: { throws: false, validate: true },
})); }));
done(); done();
@ -1081,10 +1081,10 @@ module.exports = function(dataSource, should, connectorCapabilities) {
instance: { instance: {
id: existingInstance.id, id: existingInstance.id,
name: 'changed', name: 'changed',
extra: undefined extra: undefined,
}, },
isNewInstance: false, isNewInstance: false,
options: { throws: false, validate: true } options: { throws: false, validate: true },
})); }));
done(); done();
}); });
@ -1103,10 +1103,10 @@ module.exports = function(dataSource, should, connectorCapabilities) {
instance: { instance: {
id: instance.id, id: instance.id,
name: 'created', name: 'created',
extra: undefined extra: undefined,
}, },
isNewInstance: true, isNewInstance: true,
options: { throws: false, validate: true } options: { throws: false, validate: true },
})); }));
done(); done();
}); });
@ -1148,7 +1148,7 @@ module.exports = function(dataSource, should, connectorCapabilities) {
'before save', 'before save',
'persist', 'persist',
'loaded', 'loaded',
'after save' 'after save',
]); ]);
done(); done();
}); });
@ -1165,7 +1165,7 @@ module.exports = function(dataSource, should, connectorCapabilities) {
ctxRecorder.records.should.eql(aCtxForModel(TestModel, { ctxRecorder.records.should.eql(aCtxForModel(TestModel, {
where: { id: existingInstance.id }, where: { id: existingInstance.id },
data: { name: 'changed' }, data: { name: 'changed' },
currentInstance: currentInstance currentInstance: currentInstance,
})); }));
done(); done();
}); });
@ -1197,7 +1197,7 @@ module.exports = function(dataSource, should, connectorCapabilities) {
instance.toObject(true).should.eql({ instance.toObject(true).should.eql({
id: existingInstance.id, id: existingInstance.id,
name: 'hooked name', name: 'hooked name',
extra: 'extra data' extra: 'extra data',
}); });
done(); done();
}); });
@ -1225,9 +1225,9 @@ module.exports = function(dataSource, should, connectorCapabilities) {
currentInstance: { currentInstance: {
id: existingInstance.id, id: existingInstance.id,
name: 'changed', name: 'changed',
extra: null extra: null,
}, },
isNewInstance: false isNewInstance: false,
})); }));
done(); done();
@ -1255,14 +1255,14 @@ module.exports = function(dataSource, should, connectorCapabilities) {
var Address = dataSource.createModel('NestedAddress', { var 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', { var 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 },
extra: {type: String} extra: { type: String },
}); });
dataSource.automigrate(['UserWithAddress', 'NestedAddress'], function(err) { dataSource.automigrate(['UserWithAddress', 'NestedAddress'], function(err) {
@ -1298,7 +1298,7 @@ module.exports = function(dataSource, should, connectorCapabilities) {
id: existingUser.id, id: existingUser.id,
name: existingUser.name, name: existingUser.name,
address: { id: '1', city: 'Springfield', country: 'USA' }, address: { id: '1', city: 'Springfield', country: 'USA' },
extra: 'hook data' extra: 'hook data',
}); });
done(); done();
}); });
@ -1357,9 +1357,9 @@ module.exports = function(dataSource, should, connectorCapabilities) {
instance: { instance: {
id: existingInstance.id, id: existingInstance.id,
name: 'changed', name: 'changed',
extra: undefined extra: undefined,
}, },
isNewInstance: false isNewInstance: false,
})); }));
done(); done();
}); });
@ -1404,7 +1404,7 @@ module.exports = function(dataSource, should, connectorCapabilities) {
'before save', 'before save',
'persist', 'persist',
'loaded', 'loaded',
'after save' 'after save',
]); ]);
done(); done();
}); });
@ -1421,7 +1421,7 @@ module.exports = function(dataSource, should, connectorCapabilities) {
name: 'changed', name: 'changed',
extra: undefined, extra: undefined,
}, },
isNewInstance: false isNewInstance: false,
})); }));
done(); done();
}); });
@ -1451,7 +1451,7 @@ module.exports = function(dataSource, should, connectorCapabilities) {
instance.toObject(true).should.eql({ instance.toObject(true).should.eql({
id: existingInstance.id, id: existingInstance.id,
name: 'hooked name', name: 'hooked name',
extra: 'extra data' extra: 'extra data',
}); });
done(); done();
}); });
@ -1477,14 +1477,14 @@ module.exports = function(dataSource, should, connectorCapabilities) {
where: { id: existingInstance.id }, where: { id: existingInstance.id },
data: { data: {
name: 'replacedName', name: 'replacedName',
id: existingInstance.id id: existingInstance.id,
}, },
currentInstance: { currentInstance: {
id: existingInstance.id, id: existingInstance.id,
name: 'replacedName', name: 'replacedName',
extra: null extra: null,
}, },
isNewInstance: false isNewInstance: false,
})); }));
done(); done();
@ -1507,14 +1507,14 @@ module.exports = function(dataSource, should, connectorCapabilities) {
var Address = dataSource.createModel('NestedAddress', { var 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', { var 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 },
extra: {type: String} extra: { type: String },
}); });
dataSource.automigrate(['UserWithAddress', 'NestedAddress'], function(err) { dataSource.automigrate(['UserWithAddress', 'NestedAddress'], function(err) {
@ -1545,7 +1545,7 @@ module.exports = function(dataSource, should, connectorCapabilities) {
id: existingUser.id, id: existingUser.id,
name: 'John', name: 'John',
address: { id: '1', city: 'Springfield', country: 'USA' }, address: { id: '1', city: 'Springfield', country: 'USA' },
extra: 'hook data' extra: 'hook data',
}); });
done(); done();
}); });
@ -1562,9 +1562,9 @@ module.exports = function(dataSource, should, connectorCapabilities) {
ctxRecorder.records.should.eql(aCtxForModel(TestModel, { ctxRecorder.records.should.eql(aCtxForModel(TestModel, {
data: { data: {
name: 'changed', name: 'changed',
id: data.id id: data.id,
}, },
isNewInstance : false isNewInstance : false,
})); }));
done(); done();
}); });
@ -1602,9 +1602,9 @@ module.exports = function(dataSource, should, connectorCapabilities) {
instance: { instance: {
id: existingInstance.id, id: existingInstance.id,
name: 'replaced', name: 'replaced',
extra: undefined extra: undefined,
}, },
isNewInstance: false isNewInstance: false,
})); }));
done(); done();
}); });
@ -1648,7 +1648,7 @@ module.exports = function(dataSource, should, connectorCapabilities) {
'before save', 'before save',
'persist', 'persist',
'loaded', 'loaded',
'after save' 'after save',
]); ]);
done(); done();
}); });
@ -1667,7 +1667,7 @@ module.exports = function(dataSource, should, connectorCapabilities) {
'before save', 'before save',
'persist', 'persist',
'loaded', 'loaded',
'after save' 'after save',
]); ]);
} else { } else {
hookMonitor.names.should.eql([ hookMonitor.names.should.eql([
@ -1676,7 +1676,7 @@ module.exports = function(dataSource, should, connectorCapabilities) {
'before save', 'before save',
'persist', 'persist',
'loaded', 'loaded',
'after save' 'after save',
]); ]);
} }
done(); done();
@ -1737,7 +1737,7 @@ module.exports = function(dataSource, should, connectorCapabilities) {
if (err) return done(err); if (err) return done(err);
(list || []).map(toObject).should.eql([ (list || []).map(toObject).should.eql([
{ id: existingInstance.id, name: existingInstance.name, extra: undefined }, { id: existingInstance.id, name: existingInstance.name, extra: undefined },
{ id: instance.id, name: 'new name', extra: undefined } { id: instance.id, name: 'new name', extra: undefined },
]); ]);
done(); done();
}); });
@ -1759,7 +1759,7 @@ module.exports = function(dataSource, should, connectorCapabilities) {
(list || []).map(toObject).should.eql([ (list || []).map(toObject).should.eql([
{ id: existingInstance.id, name: existingInstance.name, extra: undefined }, { id: existingInstance.id, name: existingInstance.name, extra: undefined },
{ id: list[1].id, name: 'second', extra: undefined }, { id: list[1].id, name: 'second', extra: undefined },
{ id: instance.id, name: 'new name', extra: undefined } { id: instance.id, name: 'new name', extra: undefined },
]); ]);
done(); done();
}); });
@ -1796,7 +1796,7 @@ module.exports = function(dataSource, should, connectorCapabilities) {
// UPDATE or CREATE will be triggered // UPDATE or CREATE will be triggered
ctxRecorder.records.should.eql(aCtxForModel(TestModel, { ctxRecorder.records.should.eql(aCtxForModel(TestModel, {
where: { id: existingInstance.id }, where: { id: existingInstance.id },
data: { id: existingInstance.id, name: 'updated name' } data: { id: existingInstance.id, name: 'updated name' },
})); }));
} else { } else {
// currentInstance is set, because a non-atomic `updateOrCreate` // currentInstance is set, because a non-atomic `updateOrCreate`
@ -1805,7 +1805,7 @@ module.exports = function(dataSource, should, connectorCapabilities) {
ctxRecorder.records.should.eql(aCtxForModel(TestModel, { ctxRecorder.records.should.eql(aCtxForModel(TestModel, {
where: { id: existingInstance.id }, where: { id: existingInstance.id },
data: { id: existingInstance.id, name: 'updated name' }, data: { id: existingInstance.id, name: 'updated name' },
currentInstance: existingInstance currentInstance: existingInstance,
})); }));
} }
done(); done();
@ -1826,14 +1826,14 @@ module.exports = function(dataSource, should, connectorCapabilities) {
// UPDATE or CREATE will be triggered // UPDATE or CREATE will be triggered
ctxRecorder.records.should.eql(aCtxForModel(TestModel, { ctxRecorder.records.should.eql(aCtxForModel(TestModel, {
where: { id: 'new-id' }, where: { id: 'new-id' },
data: { id: 'new-id', name: 'a name' } data: { id: 'new-id', name: 'a name' },
})); }));
} else { } else {
// The default unoptimized implementation runs // The default unoptimized implementation runs
// `instance.save` and thus a full instance is availalbe // `instance.save` and thus a full instance is availalbe
ctxRecorder.records.should.eql(aCtxForModel(TestModel, { ctxRecorder.records.should.eql(aCtxForModel(TestModel, {
instance: { id: 'new-id', name: 'a name', extra: undefined }, instance: { id: 'new-id', name: 'a name', extra: undefined },
isNewInstance: true isNewInstance: true,
})); }));
} }
@ -1918,21 +1918,21 @@ module.exports = function(dataSource, should, connectorCapabilities) {
currentInstance: { currentInstance: {
id: 'new-id', id: 'new-id',
name: 'a name', name: 'a name',
extra: undefined extra: undefined,
} },
})); }));
} else { } else {
ctxRecorder.records.should.eql(aCtxForModel(TestModel, { ctxRecorder.records.should.eql(aCtxForModel(TestModel, {
data: { data: {
id: 'new-id', id: 'new-id',
name: 'a name' name: 'a name',
}, },
isNewInstance: true, isNewInstance: true,
currentInstance: { currentInstance: {
id: 'new-id', id: 'new-id',
name: 'a name', name: 'a name',
extra: undefined extra: undefined,
} },
})); }));
} }
done(); done();
@ -1951,13 +1951,13 @@ module.exports = function(dataSource, should, connectorCapabilities) {
where: { id: existingInstance.id }, where: { id: existingInstance.id },
data: { data: {
id: existingInstance.id, id: existingInstance.id,
name: 'updated name' name: 'updated name',
}, },
currentInstance: { currentInstance: {
id: existingInstance.id, id: existingInstance.id,
name: 'updated name', name: 'updated name',
extra: undefined extra: undefined,
} },
}); });
if (!dataSource.connector.updateOrCreate) { if (!dataSource.connector.updateOrCreate) {
@ -1987,9 +1987,9 @@ module.exports = function(dataSource, should, connectorCapabilities) {
ctxRecorder.records.should.eql(aCtxForModel(TestModel, { ctxRecorder.records.should.eql(aCtxForModel(TestModel, {
data: { data: {
id: 'new-id', id: 'new-id',
name: 'a name' name: 'a name',
}, },
isNewInstance: true isNewInstance: true,
})); }));
} }
done(); done();
@ -2008,8 +2008,8 @@ module.exports = function(dataSource, should, connectorCapabilities) {
ctxRecorder.records.should.eql(aCtxForModel(TestModel, { ctxRecorder.records.should.eql(aCtxForModel(TestModel, {
data: { data: {
id: existingInstance.id, id: existingInstance.id,
name: 'updated name' name: 'updated name',
} },
})); }));
} else { } else {
// For Unoptimized connector, the callback function `contextRecorder.recordAndNext` // For Unoptimized connector, the callback function `contextRecorder.recordAndNext`
@ -2020,17 +2020,17 @@ module.exports = function(dataSource, should, connectorCapabilities) {
instance: { instance: {
id: existingInstance.id, id: existingInstance.id,
name: 'first', name: 'first',
extra: null extra: null,
}, },
isNewInstance: false, isNewInstance: false,
options: { notify: false } options: { notify: false },
}), }),
aCtxForModel(TestModel, { aCtxForModel(TestModel, {
data: { data: {
id: existingInstance.id, id: existingInstance.id,
name: 'updated name' name: 'updated name',
} },
}) }),
]); ]);
} }
done(); done();
@ -2058,9 +2058,9 @@ module.exports = function(dataSource, should, connectorCapabilities) {
instance: { instance: {
id: existingInstance.id, id: existingInstance.id,
name: 'updated name', name: 'updated name',
extra: undefined extra: undefined,
}, },
isNewInstance: false isNewInstance: false,
})); }));
done(); done();
}); });
@ -2077,9 +2077,9 @@ module.exports = function(dataSource, should, connectorCapabilities) {
instance: { instance: {
id: instance.id, id: instance.id,
name: 'a name', name: 'a name',
extra: undefined extra: undefined,
}, },
isNewInstance: true isNewInstance: true,
})); }));
done(); done();
}); });
@ -2102,7 +2102,7 @@ module.exports = function(dataSource, should, connectorCapabilities) {
'before save', 'before save',
'persist', 'persist',
'loaded', 'loaded',
'after save' 'after save',
]); ]);
done(); done();
}); });
@ -2121,7 +2121,7 @@ module.exports = function(dataSource, should, connectorCapabilities) {
'before save', 'before save',
'persist', 'persist',
'loaded', 'loaded',
'after save' 'after save',
]); ]);
} else { } else {
// TODO: Please see loopback-datasource-juggler/issues#836 // TODO: Please see loopback-datasource-juggler/issues#836
@ -2139,7 +2139,7 @@ module.exports = function(dataSource, should, connectorCapabilities) {
'before save', 'before save',
'persist', 'persist',
'loaded', 'loaded',
'after save' 'after save',
]); ]);
}; };
done(); done();
@ -2200,7 +2200,7 @@ module.exports = function(dataSource, should, connectorCapabilities) {
if (err) return done(err); if (err) return done(err);
(list || []).map(toObject).should.eql([ (list || []).map(toObject).should.eql([
{ id: existingInstance.id, name: existingInstance.name, extra: undefined }, { id: existingInstance.id, name: existingInstance.name, extra: undefined },
{ id: instance.id, name: 'new name', extra: undefined } { id: instance.id, name: 'new name', extra: undefined },
]); ]);
done(); done();
}); });
@ -2222,7 +2222,7 @@ module.exports = function(dataSource, should, connectorCapabilities) {
(list || []).map(toObject).should.eql([ (list || []).map(toObject).should.eql([
{ id: existingInstance.id, name: existingInstance.name, extra: undefined }, { id: existingInstance.id, name: existingInstance.name, extra: undefined },
{ id: list[1].id, name: 'second', extra: undefined }, { id: list[1].id, name: 'second', extra: undefined },
{ id: instance.id, name: 'new name', extra: undefined } { id: instance.id, name: 'new name', extra: undefined },
]); ]);
done(); done();
}); });
@ -2275,8 +2275,8 @@ module.exports = function(dataSource, should, connectorCapabilities) {
instance: { instance: {
id: existingInstance.id, id: existingInstance.id,
name: 'replaced name', name: 'replaced name',
extra: undefined extra: undefined,
} },
}); });
if (!dataSource.connector.replaceOrCreate) { if (!dataSource.connector.replaceOrCreate) {
@ -2300,8 +2300,8 @@ module.exports = function(dataSource, should, connectorCapabilities) {
instance: { instance: {
id: 'new-id', id: 'new-id',
name: 'a name', name: 'a name',
extra: undefined extra: undefined,
} },
}); });
if (!dataSource.connector.replaceOrCreate) { if (!dataSource.connector.replaceOrCreate) {
@ -2385,13 +2385,13 @@ module.exports = function(dataSource, should, connectorCapabilities) {
where: { id: existingInstance.id }, where: { id: existingInstance.id },
data: { data: {
id: existingInstance.id, id: existingInstance.id,
name: 'replaced name' name: 'replaced name',
}, },
currentInstance: { currentInstance: {
id: existingInstance.id, id: existingInstance.id,
name: 'replaced name', name: 'replaced name',
extra: undefined extra: undefined,
} },
}; };
var expectedContext = aCtxForModel(TestModel, expected); var expectedContext = aCtxForModel(TestModel, expected);
@ -2417,8 +2417,8 @@ module.exports = function(dataSource, should, connectorCapabilities) {
var expected = { var expected = {
data: { data: {
id: 'new-id', id: 'new-id',
name: 'a name' name: 'a name',
} },
}; };
expected.isNewInstance = expected.isNewInstance =
@ -2441,8 +2441,8 @@ module.exports = function(dataSource, should, connectorCapabilities) {
var expected = { var expected = {
data: { data: {
id: existingInstance.id, id: existingInstance.id,
name: 'replaced name' name: 'replaced name',
} },
}; };
expected.isNewInstance = expected.isNewInstance =
@ -2465,18 +2465,18 @@ module.exports = function(dataSource, should, connectorCapabilities) {
aCtxForModel(TestModel, { aCtxForModel(TestModel, {
data: { data: {
id: existingInstance.id, id: existingInstance.id,
name: 'first' name: 'first',
}, },
isNewInstance: false, isNewInstance: false,
options: { notify: false } options: { notify: false },
}), }),
aCtxForModel(TestModel, { aCtxForModel(TestModel, {
data: { data: {
id: existingInstance.id, id: existingInstance.id,
name: 'replaced name' name: 'replaced name',
}, },
isNewInstance: false isNewInstance: false,
}) }),
]); ]);
} }
done(); done();
@ -2505,8 +2505,8 @@ module.exports = function(dataSource, should, connectorCapabilities) {
instance: { instance: {
id: existingInstance.id, id: existingInstance.id,
name: 'replaced name', name: 'replaced name',
extra: undefined extra: undefined,
} },
}; };
expected.isNewInstance = expected.isNewInstance =
@ -2530,8 +2530,8 @@ module.exports = function(dataSource, should, connectorCapabilities) {
instance: { instance: {
id: instance.id, id: instance.id,
name: 'a name', name: 'a name',
extra: undefined extra: undefined,
} },
}; };
expected.isNewInstance = expected.isNewInstance =
connectorCapabilities.replaceOrCreateReportsNewInstance ? connectorCapabilities.replaceOrCreateReportsNewInstance ?
@ -2746,7 +2746,7 @@ module.exports = function(dataSource, should, connectorCapabilities) {
if (err) return done(err); if (err) return done(err);
ctxRecorder.records.should.eql(aCtxForModel(TestModel, { ctxRecorder.records.should.eql(aCtxForModel(TestModel, {
where: { id: existingInstance.id }, where: { id: existingInstance.id },
instance: existingInstance instance: existingInstance,
})); }));
done(); done();
}); });
@ -2788,13 +2788,13 @@ module.exports = function(dataSource, should, connectorCapabilities) {
aCtxForModel(TestModel, { aCtxForModel(TestModel, {
hookState: { foo: 'bar' }, hookState: { foo: 'bar' },
where: { id: '1' }, where: { id: '1' },
instance: existingInstance instance: existingInstance,
}), }),
aCtxForModel(TestModel, { aCtxForModel(TestModel, {
hookState: { foo: 'BAR' }, hookState: { foo: 'BAR' },
where: { id: '1' }, where: { id: '1' },
instance: existingInstance instance: existingInstance,
}) }),
]); ]);
done(); done();
}); });
@ -2846,7 +2846,7 @@ module.exports = function(dataSource, should, connectorCapabilities) {
if (err) return done(err); if (err) return done(err);
(list || []).map(toObject).should.eql([ (list || []).map(toObject).should.eql([
{ id: existingInstance.id, name: existingInstance.name, extra: undefined }, { id: existingInstance.id, name: existingInstance.name, extra: undefined },
{ id: '2', name: 'new name', extra: undefined } { id: '2', name: 'new name', extra: undefined },
]); ]);
done(); done();
}); });
@ -2900,7 +2900,7 @@ module.exports = function(dataSource, should, connectorCapabilities) {
ctxRecorder.records.should.eql(aCtxForModel(TestModel, { ctxRecorder.records.should.eql(aCtxForModel(TestModel, {
data: { name: 'changed' }, data: { name: 'changed' },
where: { name: existingInstance.name } where: { name: existingInstance.name },
})); }));
done(); done();
@ -2947,7 +2947,7 @@ module.exports = function(dataSource, should, connectorCapabilities) {
if (err) return done(err); if (err) return done(err);
ctxRecorder.records.should.eql(aCtxForModel(TestModel, { ctxRecorder.records.should.eql(aCtxForModel(TestModel, {
where: { id: existingInstance.id }, where: { id: existingInstance.id },
data: { name: 'updated name' } data: { name: 'updated name' },
})); }));
done(); done();
}); });

View File

@ -104,7 +104,7 @@ describe('relations', function () {
var chapters = [ var chapters = [
{ name: 'a' }, { name: 'a' },
{ name: 'z' }, { name: 'z' },
{name: 'c'} { name: 'c' },
]; ];
Book.create(function(err, book) { Book.create(function(err, book) {
book.chapters.create(chapters, function(err, chs) { book.chapters.create(chapters, function(err, chs) {
@ -123,7 +123,7 @@ describe('relations', function () {
var chapters = [ var chapters = [
{ name: 'a' }, { name: 'a' },
{ name: 'z' }, { name: 'z' },
{name: 'c'} { name: 'c' },
]; ];
Book.create(function(err, book) { Book.create(function(err, book) {
book.chapters.create(chapters) book.chapters.create(chapters)
@ -174,10 +174,10 @@ describe('relations', function () {
.then(function(book) { .then(function(book) {
return book.chapters.create({ name: 'a' }) return book.chapters.create({ name: 'a' })
.then(function() { .then(function() {
return book.chapters.create({name: 'z'}) return book.chapters.create({ name: 'z' });
}) })
.then(function() { .then(function() {
return book.chapters.create({name: 'c'}) return book.chapters.create({ name: 'c' });
}) })
.then(function() { .then(function() {
return verify(book); return verify(book);
@ -297,14 +297,14 @@ describe('relations', function () {
return book.chapters.create({ name: 'a' }) return book.chapters.create({ name: 'a' })
.then(function(ch) { .then(function(ch) {
id = ch.id; id = ch.id;
return book.chapters.create({name: 'z'}) return book.chapters.create({ name: 'z' });
}) })
.then(function() { .then(function() {
return book.chapters.create({name: 'c'}) return book.chapters.create({ name: 'c' });
}) })
.then(function() { .then(function() {
return verify(book); return verify(book);
}) });
}).catch(done); }).catch(done);
function verify(book) { function verify(book) {
@ -346,10 +346,10 @@ describe('relations', function () {
.then(function(book) { .then(function(book) {
book.chapters.create({ name: 'a' }) book.chapters.create({ name: 'a' })
.then(function() { .then(function() {
return book.chapters.create({name: 'b'}) return book.chapters.create({ name: 'b' });
}) })
.then(function() { .then(function() {
return book.chapters.create({name: 'c'}) return book.chapters.create({ name: 'c' });
}) })
.then(function() { .then(function() {
return verify(book); return verify(book);
@ -360,7 +360,7 @@ describe('relations', function () {
return book.chapters.count() return book.chapters.count()
.then(function(count) { .then(function(count) {
count.should.equal(3); count.should.equal(3);
return book.chapters.count({ name: 'b' }) return book.chapters.count({ name: 'b' });
}) })
.then(function(count) { .then(function(count) {
count.should.equal(1); count.should.equal(1);
@ -402,7 +402,7 @@ describe('relations', function () {
return book.chapters.create({ name: 'a' }) return book.chapters.create({ name: 'a' })
.then(function(ch) { .then(function(ch) {
id = ch.id; id = ch.id;
return book.chapters.updateById(id, {name: 'aa'}) return book.chapters.updateById(id, { name: 'aa' });
}) })
.then(function(ch) { .then(function(ch) {
return verify(book); return verify(book);
@ -447,7 +447,7 @@ describe('relations', function () {
return book.chapters.create({ name: 'a' }) return book.chapters.create({ name: 'a' })
.then(function(ch) { .then(function(ch) {
id = ch.id; id = ch.id;
return book.chapters.destroy(id) return book.chapters.destroy(id);
}) })
.then(function(ch) { .then(function(ch) {
return verify(book); return verify(book);
@ -493,10 +493,10 @@ describe('relations', function () {
return book.chapters.create({ name: 'a' }) return book.chapters.create({ name: 'a' })
.then(function(ch) { .then(function(ch) {
id = ch.id; id = ch.id;
return book.chapters.create({name: 'z'}) return book.chapters.create({ name: 'z' });
}) })
.then(function() { .then(function() {
return book.chapters.create({name: 'c'}) return book.chapters.create({ name: 'c' });
}) })
.then(function() { .then(function() {
return verify(book); return verify(book);
@ -625,7 +625,7 @@ describe('relations', function () {
function verifyPatient(patient, next) { function verifyPatient(patient, next) {
Appointment.find({ where: { Appointment.find({ where: {
physicianId: physician.id, physicianId: physician.id,
patientId: patient.id patientId: patient.id,
}}, }},
function(err, apps) { function(err, apps) {
should.not.exist(err); should.not.exist(err);
@ -649,7 +649,7 @@ describe('relations', function () {
function verifyPatient(patient, next) { function verifyPatient(patient, next) {
Appointment.find({ where: { Appointment.find({ where: {
physicianId: physician.id, physicianId: physician.id,
patientId: patient.id patientId: patient.id,
}}) }})
.then(function(apps) { .then(function(apps) {
apps.should.have.lengthOf(1); apps.should.have.lengthOf(1);
@ -690,14 +690,14 @@ describe('relations', function () {
.then(function(physician) { .then(function(physician) {
return physician.patients.create({ name: 'a' }) return physician.patients.create({ name: 'a' })
.then(function() { .then(function() {
return physician.patients.create({name: 'z'}) return physician.patients.create({ name: 'z' });
}) })
.then(function() { .then(function() {
return physician.patients.create({name: 'c'}) return physician.patients.create({ name: 'c' });
}) })
.then(function() { .then(function() {
return verify(physician); return verify(physician);
}) });
}).catch(done); }).catch(done);
function verify(physician) { function verify(physician) {
return physician.patients.getAsync() return physician.patients.getAsync()
@ -737,7 +737,7 @@ describe('relations', function () {
ch1.should.have.lengthOf(1); ch1.should.have.lengthOf(1);
ch1[0].name.should.eql('z'); ch1[0].name.should.eql('z');
//order //order
physician.patients({ order: "patientId DESC" },function (err2, ch2) { physician.patients({ order: 'patientId DESC' }, function(err2, ch2) {
should.not.exist(err2); should.not.exist(err2);
should.exist(ch2); should.exist(ch2);
ch2.should.have.lengthOf(3); ch2.should.have.lengthOf(3);
@ -779,10 +779,10 @@ describe('relations', function () {
return physician.patients.create({ name: 'a' }) return physician.patients.create({ name: 'a' })
.then(function(ch) { .then(function(ch) {
id = ch.id; id = ch.id;
return physician.patients.create({name: 'z'}) return physician.patients.create({ name: 'z' });
}) })
.then(function() { .then(function() {
return physician.patients.create({name: 'c'}) return physician.patients.create({ name: 'c' });
}) })
.then(function() { .then(function() {
return verify(physician); return verify(physician);
@ -984,10 +984,10 @@ describe('relations', function () {
return physician.patients.create({ name: 'a' }) return physician.patients.create({ name: 'a' })
.then(function(ch) { .then(function(ch) {
id = ch.id; id = ch.id;
return physician.patients.create({name: 'z'}) return physician.patients.create({ name: 'z' });
}) })
.then(function() { .then(function() {
return physician.patients.create({name: 'c'}) return physician.patients.create({ name: 'c' });
}) })
.then(function() { .then(function() {
return verify(physician); return verify(physician);
@ -1380,7 +1380,7 @@ describe('relations', function () {
scope: function(inst, filter) { scope: function(inst, filter) {
var m = this.properties(inst); // re-use properties var m = this.properties(inst); // re-use properties
if (m) return { where: m }; if (m) return { where: m };
} },
}); });
db.automigrate(['Category', 'Job'], done); db.automigrate(['Category', 'Job'], done);
}); });
@ -1433,7 +1433,7 @@ describe('relations', function () {
it('should find records on scope with promises', function(done) { it('should find records on scope with promises', function(done) {
Category.findOne() Category.findOne()
.then(function(c) { .then(function(c) {
return c.jobs.getAsync() return c.jobs.getAsync();
}) })
.then(function(jobs) { .then(function(jobs) {
jobs.should.have.length(2); jobs.should.have.length(2);
@ -1457,7 +1457,7 @@ describe('relations', function () {
it('should find record on scope with promises - filtered', function(done) { it('should find record on scope with promises - filtered', function(done) {
Category.findOne() Category.findOne()
.then(function(c) { .then(function(c) {
return c.jobs.getAsync({ where: { type: 'book' } }) return c.jobs.getAsync({ where: { type: 'book' }});
}) })
.then(function(jobs) { .then(function(jobs) {
jobs.should.have.length(1); jobs.should.have.length(1);
@ -1713,11 +1713,11 @@ describe('relations', function () {
Picture = db.define('Picture', { name: String }); Picture = db.define('Picture', { name: String });
Author = db.define('Author', { Author = db.define('Author', {
username: { type: String, id: true, generated: true }, username: { type: String, id: true, generated: true },
name: String name: String,
}); });
Reader = db.define('Reader', { Reader = db.define('Reader', {
username: { type: String, id: true, generated: true }, username: { type: String, id: true, generated: true },
name: String name: String,
}); });
db.automigrate(['Picture', 'Author', 'Reader'], done); db.automigrate(['Picture', 'Author', 'Reader'], done);
@ -1728,23 +1728,23 @@ describe('relations', function () {
as: 'avatar', as: 'avatar',
polymorphic: { polymorphic: {
foreignKey: 'oid', foreignKey: 'oid',
discriminator: 'type' discriminator: 'type',
} },
}); });
Reader.hasOne(Picture, { Reader.hasOne(Picture, {
as: 'mugshot', as: 'mugshot',
polymorphic: { polymorphic: {
foreignKey: 'oid', foreignKey: 'oid',
discriminator: 'type' discriminator: 'type',
} },
}); });
Picture.belongsTo('owner', { Picture.belongsTo('owner', {
idName: 'username', idName: 'username',
polymorphic: { polymorphic: {
idType: Author.definition.properties.username.type, idType: Author.definition.properties.username.type,
foreignKey: 'oid', foreignKey: 'oid',
discriminator: 'type' discriminator: 'type',
} },
}); });
db.automigrate(['Picture', 'Author', 'Reader'], done); db.automigrate(['Picture', 'Author', 'Reader'], done);
}); });
@ -1880,7 +1880,7 @@ describe('relations', function () {
Author.hasMany(Picture, { polymorphic: 'imageable' }); Author.hasMany(Picture, { polymorphic: 'imageable' });
Reader.hasMany(Picture, { polymorphic: { // alt syntax Reader.hasMany(Picture, { polymorphic: { // alt syntax
as: 'imageable', foreignKey: 'imageableId', as: 'imageable', foreignKey: 'imageableId',
discriminator: 'imageableType' discriminator: 'imageableType',
}}); }});
Picture.belongsTo('imageable', { polymorphic: true }); Picture.belongsTo('imageable', { polymorphic: true });
@ -1895,8 +1895,8 @@ describe('relations', function () {
polymorphic: { polymorphic: {
as: 'imageable', as: 'imageable',
foreignKey: 'imageableId', foreignKey: 'imageableId',
discriminator: 'imageableType' discriminator: 'imageableType',
} },
}); });
Picture.relations['imageable'].toJSON().should.eql({ Picture.relations['imageable'].toJSON().should.eql({
@ -1910,8 +1910,8 @@ describe('relations', function () {
polymorphic: { polymorphic: {
as: 'imageable', as: 'imageable',
foreignKey: 'imageableId', foreignKey: 'imageableId',
discriminator: 'imageableType' discriminator: 'imageableType',
} },
}); });
db.automigrate(['Picture', 'Author', 'Reader'], done); db.automigrate(['Picture', 'Author', 'Reader'], done);
@ -2320,7 +2320,7 @@ describe('relations', function () {
it('should create polymorphic through model - new author', function(done) { it('should create polymorphic through model - new author', function(done) {
PictureLink.findOne({ where: { PictureLink.findOne({ where: {
pictureId: anotherPicture.id, imageableId: author.id, imageableType: 'Author' pictureId: anotherPicture.id, imageableId: author.id, imageableType: 'Author',
}}, function(err, link) { }}, function(err, link) {
should.not.exist(err); should.not.exist(err);
link.pictureId.should.eql(anotherPicture.id); link.pictureId.should.eql(anotherPicture.id);
@ -2361,7 +2361,7 @@ describe('relations', function () {
// syntax 2 (new) // syntax 2 (new)
Fear.belongsTo('mind', { Fear.belongsTo('mind', {
methods: { check: function() { return true; } } methods: { check: function() { return true; } },
}); });
Object.keys((new Fear).toObject()).should.containEql('mindId'); Object.keys((new Fear).toObject()).should.containEql('mindId');
@ -2373,7 +2373,7 @@ describe('relations', function () {
var rel = Fear.relations['mind']; var rel = Fear.relations['mind'];
rel.defineMethod('other', function() { rel.defineMethod('other', function() {
return true; return true;
}) });
}); });
it('should have setup a custom method on accessor', function() { it('should have setup a custom method on accessor', function() {
@ -2435,7 +2435,7 @@ describe('relations', function () {
.then(function(list) { .then(function(list) {
listId = list.id; listId = list.id;
should.exist(list); should.exist(list);
return list.todos.create({name: 'Item 1'}) return list.todos.create({ name: 'Item 1' });
}) })
.then(function(todo) { .then(function(todo) {
itemId = todo.id; itemId = todo.id;
@ -2561,7 +2561,7 @@ describe('relations', function () {
Passport = db.define('Passport', { name: String, notes: String }); Passport = db.define('Passport', { name: String, notes: String });
Passport.belongsTo(Person, { Passport.belongsTo(Person, {
properties: { notes: 'passportNotes' }, properties: { notes: 'passportNotes' },
scope: { fields: { id: true, name: true } } scope: { fields: { id: true, name: true }},
}); });
db.automigrate(['Person', 'Passport'], done); db.automigrate(['Person', 'Passport'], done);
}); });
@ -2600,7 +2600,7 @@ describe('relations', function () {
p.personId.should.equal(person.id); p.personId.should.equal(person.id);
person.name.should.equal('Fred'); person.name.should.equal('Fred');
person.passportNotes.should.equal('Some notes...'); person.passportNotes.should.equal('Some notes...');
return p.save() return p.save();
}) })
.then(function(passport) { .then(function(passport) {
done(); done();
@ -2612,7 +2612,7 @@ describe('relations', function () {
Passport.findOne() Passport.findOne()
.then(function(p) { .then(function(p) {
p.personId.should.eql(personCreated.id); p.personId.should.eql(personCreated.id);
return p.person.getAsync() return p.person.getAsync();
}) })
.then(function(person) { .then(function(person) {
person.name.should.equal('Fred'); person.name.should.equal('Fred');
@ -2636,7 +2636,7 @@ describe('relations', function () {
Passport = db.define('Passport', { name: String, notes: String }); Passport = db.define('Passport', { name: String, notes: String });
Passport.belongsTo(Person, { Passport.belongsTo(Person, {
properties: ['name'], properties: ['name'],
options: { embedsProperties: true, invertProperties: true } options: { embedsProperties: true, invertProperties: true },
}); });
db.automigrate(['Person', 'Passport'], done); db.automigrate(['Person', 'Passport'], done);
}); });
@ -2690,7 +2690,7 @@ describe('relations', function () {
it('can be declared using hasOne method', function() { it('can be declared using hasOne method', function() {
Supplier.hasOne(Account, { Supplier.hasOne(Account, {
properties: { name: 'supplierName' }, properties: { name: 'supplierName' },
methods: { check: function() { return true; } } methods: { check: function() { return true; } },
}); });
Object.keys((new Account()).toObject()).should.containEql('supplierId'); Object.keys((new Account()).toObject()).should.containEql('supplierId');
(new Supplier()).account.should.be.an.instanceOf(Function); (new Supplier()).account.should.be.an.instanceOf(Function);
@ -2700,7 +2700,7 @@ describe('relations', function () {
var rel = Supplier.relations['account']; var rel = Supplier.relations['account'];
rel.defineMethod('other', function() { rel.defineMethod('other', function() {
return true; return true;
}) });
}); });
it('should have setup a custom method on accessor', function() { it('should have setup a custom method on accessor', function() {
@ -2761,7 +2761,7 @@ describe('relations', function () {
should.exist(supplier); should.exist(supplier);
return supplier.account.create({ accountNo: 'a01' }) return supplier.account.create({ accountNo: 'a01' })
.then(function(account) { .then(function(account) {
return supplier.account.getAsync() return supplier.account.getAsync();
}) })
.then(function(act) { .then(function(act) {
accountId = act.id; accountId = act.id;
@ -2770,7 +2770,7 @@ describe('relations', function () {
supplier.account().id.should.equal(act.id); supplier.account().id.should.equal(act.id);
act.supplierName.should.equal(supplier.name); act.supplierName.should.equal(supplier.name);
done(); done();
}) });
}) })
.catch(done); .catch(done);
}); });
@ -2796,7 +2796,7 @@ describe('relations', function () {
Supplier.findById(supplierId) Supplier.findById(supplierId)
.then(function(supplier) { .then(function(supplier) {
should.exist(supplier); should.exist(supplier);
return supplier.account.update({supplierName: 'Supplier B'}) return supplier.account.update({ supplierName: 'Supplier B' });
}) })
.then(function(act) { .then(function(act) {
act.supplierName.should.equal('Supplier B'); act.supplierName.should.equal('Supplier B');
@ -2840,7 +2840,7 @@ describe('relations', function () {
Supplier.findById(supplierId) Supplier.findById(supplierId)
.then(function(supplier) { .then(function(supplier) {
should.exist(supplier); should.exist(supplier);
return supplier.account.getAsync() return supplier.account.getAsync();
}) })
.then(function(act) { .then(function(act) {
should.exist(act); should.exist(act);
@ -2867,7 +2867,7 @@ describe('relations', function () {
should.exist(supplier); should.exist(supplier);
return supplier.account.create({ accountNo: 'a01' }) return supplier.account.create({ accountNo: 'a01' })
.then(function(account) { .then(function(account) {
return supplier.account.destroy() return supplier.account.destroy();
}) })
.then(function(err) { .then(function(err) {
done(); done();
@ -2892,7 +2892,7 @@ describe('relations', function () {
Supplier.findById(supplierId) Supplier.findById(supplierId)
.then(function(supplier) { .then(function(supplier) {
should.exist(supplier); should.exist(supplier);
return supplier.account.getAsync() return supplier.account.getAsync();
}) })
.then(function(act) { .then(function(act) {
should.not.exist(act); should.not.exist(act);
@ -2987,7 +2987,7 @@ describe('relations', function () {
should.exist(supplier); should.exist(supplier);
return supplier.account.create({ accountNo: 'a01', block: false }) return supplier.account.create({ accountNo: 'a01', block: false })
.then(function(account) { .then(function(account) {
return supplier.account.getAsync() return supplier.account.getAsync();
}) })
.then(function(act) { .then(function(act) {
accountId = act.id; accountId = act.id;
@ -3007,10 +3007,10 @@ describe('relations', function () {
it('should find record that match scope with promises', function(done) { it('should find record that match scope with promises', function(done) {
Account.updateAll({ block: true }) Account.updateAll({ block: true })
.then(function() { .then(function() {
return Supplier.findById(supplierId) return Supplier.findById(supplierId);
}) })
.then(function(supplier) { .then(function(supplier) {
return supplier.account.getAsync() return supplier.account.getAsync();
}) })
.then(function(account) { .then(function(account) {
should.not.exist(account); should.not.exist(account);
@ -3031,24 +3031,24 @@ describe('relations', function () {
sid: { sid: {
type: String, type: String,
id: true, id: true,
generated: true generated: true,
}, },
name: String name: String,
}); });
Account = db.define('Account', { Account = db.define('Account', {
accid: { accid: {
type: String, type: String,
id: true, id: true,
generated: false generated: false,
}, },
supplierName: String supplierName: String,
}); });
}); });
it('can be declared with non standard foreignKey', function() { it('can be declared with non standard foreignKey', function() {
Supplier.hasOne(Account, { Supplier.hasOne(Account, {
properties: { name: 'supplierName' }, properties: { name: 'supplierName' },
foreignKey: 'sid' foreignKey: 'sid',
}); });
Object.keys((new Account()).toObject()).should.containEql('sid'); Object.keys((new Account()).toObject()).should.containEql('sid');
(new Supplier()).account.should.be.an.instanceOf(Function); (new Supplier()).account.should.be.an.instanceOf(Function);
@ -3116,12 +3116,12 @@ describe('relations', function () {
db = getSchema(); db = getSchema();
CompanyBoard = db.define('CompanyBoard', { CompanyBoard = db.define('CompanyBoard', {
membersNumber: Number, membersNumber: Number,
companyId: String companyId: String,
}); });
Boss = db.define('Boss', { Boss = db.define('Boss', {
id: { type: String, id: true, generated: false }, id: { type: String, id: true, generated: false },
boardMembersNumber: Number, boardMembersNumber: Number,
companyId: String companyId: String,
}); });
}); });
@ -3129,7 +3129,7 @@ describe('relations', function () {
CompanyBoard.hasOne(Boss, { CompanyBoard.hasOne(Boss, {
properties: { membersNumber: 'boardMembersNumber' }, properties: { membersNumber: 'boardMembersNumber' },
primaryKey: 'companyId', primaryKey: 'companyId',
foreignKey: 'companyId' foreignKey: 'companyId',
}); });
Object.keys((new Boss()).toObject()).should.containEql('companyId'); Object.keys((new Boss()).toObject()).should.containEql('companyId');
(new CompanyBoard()).boss.should.be.an.instanceOf(Function); (new CompanyBoard()).boss.should.be.an.instanceOf(Function);
@ -3184,7 +3184,7 @@ describe('relations', function () {
describe('hasMany with primaryKey different from model PK', function() { describe('hasMany with primaryKey different from model PK', function() {
var Employee, Boss; var Employee, Boss;
var COMPANY_ID = "Company1"; var COMPANY_ID = 'Company1';
before(function() { before(function() {
db = getSchema(); db = getSchema();
@ -3195,7 +3195,7 @@ describe('relations', function () {
it('relation can be declared with primaryKey', function() { it('relation can be declared with primaryKey', function() {
Boss.hasMany(Employee, { Boss.hasMany(Employee, {
primaryKey: 'companyId', primaryKey: 'companyId',
foreignKey: 'companyId' foreignKey: 'companyId',
}); });
(new Boss()).employees.should.be.an.instanceOf(Function); (new Boss()).employees.should.be.an.instanceOf(Function);
}); });
@ -3217,7 +3217,7 @@ describe('relations', function () {
employee.should.be.an.instanceOf(Employee); employee.should.be.an.instanceOf(Employee);
employee.companyId.should.be.eql(boss.companyId); employee.companyId.should.be.eql(boss.companyId);
return employees; return employees;
}) });
}); });
}); });
}); });
@ -3233,7 +3233,7 @@ describe('relations', function () {
}).then(function(employees) { }).then(function(employees) {
should.exists(employees); should.exists(employees);
employees.length.should.equal(1); employees.length.should.equal(1);
}) });
}); });
}); });
}); });
@ -3242,7 +3242,7 @@ describe('relations', function () {
describe('belongsTo with primaryKey different from model PK', function() { describe('belongsTo with primaryKey different from model PK', function() {
var Employee, Boss; var Employee, Boss;
var COMPANY_ID = "Company1"; var COMPANY_ID = 'Company1';
var bossId; var bossId;
before(function() { before(function() {
@ -3254,7 +3254,7 @@ describe('relations', function () {
it('relation can be declared with primaryKey', function() { it('relation can be declared with primaryKey', function() {
Employee.belongsTo(Boss, { Employee.belongsTo(Boss, {
primaryKey: 'companyId', primaryKey: 'companyId',
foreignKey: 'companyId' foreignKey: 'companyId',
}); });
(new Employee()).boss.should.be.an.instanceOf(Function); (new Employee()).boss.should.be.an.instanceOf(Function);
}); });
@ -3264,7 +3264,7 @@ describe('relations', function () {
return Boss.create({ address: 'testAddress', companyId: COMPANY_ID }) return Boss.create({ address: 'testAddress', companyId: COMPANY_ID })
.then(function(boss) { .then(function(boss) {
bossId = boss.id; bossId = boss.id;
return Employee.create({name: 'a', companyId: COMPANY_ID}) return Employee.create({ name: 'a', companyId: COMPANY_ID });
}) })
.then(function(employee) { .then(function(employee) {
should.exists(employee); should.exists(employee);
@ -3390,7 +3390,7 @@ describe('relations', function () {
at.articleId.should.eql(article.id); at.articleId.should.eql(article.id);
done(); done();
}); });
}) });
}) })
.catch(done); .catch(done);
}); });
@ -3404,7 +3404,7 @@ describe('relations', function () {
tags.should.not.be.empty; tags.should.not.be.empty;
return article.tagNames.remove(tags[0]) return article.tagNames.remove(tags[0])
.then(function() { .then(function() {
return article.tagNames.getAsync() return article.tagNames.getAsync();
}) })
.then(function(tags) { .then(function(tags) {
tags.should.have.lengthOf(len - 1); tags.should.have.lengthOf(len - 1);
@ -3494,7 +3494,7 @@ describe('relations', function () {
it('can be declared using embedsOne method', function(done) { it('can be declared using embedsOne method', function(done) {
Person.embedsOne(Passport, { Person.embedsOne(Passport, {
default: { name: 'Anonymous' }, // a bit contrived default: { name: 'Anonymous' }, // a bit contrived
methods: { check: function() { return true; } } methods: { check: function() { return true; } },
}); });
Person.embedsOne(Address); // all by default Person.embedsOne(Address); // all by default
db.automigrate(['Person'], done); db.automigrate(['Person'], done);
@ -3513,7 +3513,7 @@ describe('relations', function () {
var rel = Person.relations['passportItem']; var rel = Person.relations['passportItem'];
rel.defineMethod('other', function() { rel.defineMethod('other', function() {
return true; return true;
}) });
}); });
it('should have setup a custom method on accessor', function() { it('should have setup a custom method on accessor', function() {
@ -3781,7 +3781,7 @@ describe('relations', function () {
it('can be declared using embedsOne method', function(done) { it('can be declared using embedsOne method', function(done) {
Person.embedsOne(Passport, { Person.embedsOne(Passport, {
options: {persistent: true} options: { persistent: true },
}); });
db.automigrate(['Person', 'Passport'], done); db.automigrate(['Person', 'Passport'], done);
}); });
@ -4098,7 +4098,7 @@ describe('relations', function () {
Person = db.define('Person', { name: String }); Person = db.define('Person', { name: String });
Address = tmp.define('Address', { Address = tmp.define('Address', {
id: { type: Number, id:true }, id: { type: Number, id:true },
street: String street: String,
}); });
db.automigrate(['Person'], done); db.automigrate(['Person'], done);
@ -4215,7 +4215,7 @@ describe('relations', function () {
Person.create({ name: 'Wilma', addresses: addresses }, function(err, p) { Person.create({ name: 'Wilma', addresses: addresses }, function(err, p) {
err.name.should.equal('ValidationError'); err.name.should.equal('ValidationError');
err.details.messages.addresses.should.eql([ err.details.messages.addresses.should.eql([
'contains invalid item: `work` (`street` can\'t be blank)' 'contains invalid item: `work` (`street` can\'t be blank)',
]); ]);
done(); done();
}); });
@ -4261,7 +4261,7 @@ describe('relations', function () {
it('should create embedded from attributes - property name', function(done) { it('should create embedded from attributes - property name', function(done) {
var addresses = [ var addresses = [
{ id: 'home', street: 'Home Street' }, { id: 'home', street: 'Home Street' },
{id: 'work', street: 'Work Street'} { id: 'work', street: 'Work Street' },
]; ];
Person.create({ name: 'Wilma', addresses: addresses }, function(err, p) { Person.create({ name: 'Wilma', addresses: addresses }, function(err, p) {
should.not.exist(err); should.not.exist(err);
@ -4274,7 +4274,7 @@ describe('relations', function () {
it('should not create embedded from attributes - relation name', function(done) { it('should not create embedded from attributes - relation name', function(done) {
var addresses = [ var addresses = [
{ id: 'home', street: 'Home Street' }, { id: 'home', street: 'Home Street' },
{id: 'work', street: 'Work Street'} { id: 'work', street: 'Work Street' },
]; ];
Person.create({ name: 'Wilma', addressList: addresses }, function(err, p) { Person.create({ name: 'Wilma', addressList: addresses }, function(err, p) {
should.not.exist(err); should.not.exist(err);
@ -4319,7 +4319,7 @@ describe('relations', function () {
// persistent: true // persistent: true
Person.embedsMany(Address, { Person.embedsMany(Address, {
scope: { order: 'street' }, scope: { order: 'street' },
options: {persistent: true} options: { persistent: true },
}); });
db.automigrate(['Person', 'Address'], done); db.automigrate(['Person', 'Address'], done);
}); });
@ -4437,12 +4437,12 @@ describe('relations', function () {
Category.embedsMany(Link, { Category.embedsMany(Link, {
as: 'items', // rename as: 'items', // rename
scope: { include: 'job' }, // always include scope: { include: 'job' }, // always include
options: { belongsTo: 'job' } // optional, for add()/remove() options: { belongsTo: 'job' }, // optional, for add()/remove()
}); });
Link.belongsTo(Job, { Link.belongsTo(Job, {
foreignKey: 'id', // re-use the actual job id foreignKey: 'id', // re-use the actual job id
properties: { id: 'id', name: 'name' }, // denormalize, transfer id properties: { id: 'id', name: 'name' }, // denormalize, transfer id
options: { invertProperties: true } options: { invertProperties: true },
}); });
db.automigrate(['Category', 'Job', 'Link'], function() { db.automigrate(['Category', 'Job', 'Link'], function() {
Job.create({ name: 'Job 0' }, done); // offset ids for tests Job.create({ name: 'Job 0' }, done); // offset ids for tests
@ -4601,7 +4601,7 @@ describe('relations', function () {
Category.findById(category.id, function(err, cat) { Category.findById(category.id, function(err, cat) {
cat.name.should.equal('Category B'); cat.name.should.equal('Category B');
cat.links.toObject().should.eql([ cat.links.toObject().should.eql([
{id: jobId, name: 'Job 1', notes: 'Some notes...'} { id: jobId, name: 'Job 1', notes: 'Some notes...' },
]); ]);
cat.items.at(0).should.equal(cat.links[0]); cat.items.at(0).should.equal(cat.links[0]);
cat.items(function(err, items) { // alternative access cat.items(function(err, items) { // alternative access
@ -4629,7 +4629,7 @@ describe('relations', function () {
Category.findById(category.id, function(err, cat) { Category.findById(category.id, function(err, cat) {
cat.name.should.equal('Category B'); cat.name.should.equal('Category B');
cat.links.toObject().should.eql([ cat.links.toObject().should.eql([
{id: jobId, name: 'Job 1', notes: 'Updated notes...'} { id: jobId, name: 'Job 1', notes: 'Updated notes...' },
]); ]);
done(); done();
}); });
@ -4668,7 +4668,7 @@ describe('relations', function () {
Link = tmp.define('Link', { Link = tmp.define('Link', {
id: { type: Number, id: true }, id: { type: Number, id: true },
name: String, notes: String name: String, notes: String,
}); // generic model }); // generic model
Link.validatesPresenceOf('linkedId'); Link.validatesPresenceOf('linkedId');
Link.validatesPresenceOf('linkedType'); Link.validatesPresenceOf('linkedType');
@ -4681,12 +4681,12 @@ describe('relations', function () {
Book.embedsMany(Link, { as: 'people', Book.embedsMany(Link, { as: 'people',
polymorphic: 'linked', polymorphic: 'linked',
scope: { include: 'linked' } scope: { include: 'linked' },
}); });
Link.belongsTo('linked', { Link.belongsTo('linked', {
polymorphic: { idType: idType }, // native type polymorphic: { idType: idType }, // native type
properties: { name: 'name' }, // denormalized properties: { name: 'name' }, // denormalized
options: { invertProperties: true } options: { invertProperties: true },
}); });
db.automigrate(['Book', 'Author', 'Reader'], done); db.automigrate(['Book', 'Author', 'Reader'], done);
}); });
@ -4819,7 +4819,7 @@ describe('relations', function () {
reverse.http = { verb: 'put', path: '/jobs/reverse' }; reverse.http = { verb: 'put', path: '/jobs/reverse' };
Category.referencesMany(Job, { scopeMethods: { Category.referencesMany(Job, { scopeMethods: {
reverse: reverse reverse: reverse,
}}); }});
Category.prototype['__reverse__jobs'].should.be.a.function; Category.prototype['__reverse__jobs'].should.be.a.function;
@ -5007,10 +5007,10 @@ describe('relations', function () {
categories[0].jobs({ order: 'name DESC' }, function(err, jobs) { categories[0].jobs({ order: 'name DESC' }, function(err, jobs) {
should.not.exist(err); should.not.exist(err);
jobs.should.have.length(2); jobs.should.have.length(2);
jobs[0].id.should.eql(job3.id) jobs[0].id.should.eql(job3.id);
jobs[1].id.should.eql(job2.id) jobs[1].id.should.eql(job2.id);
done(); done();
}) });
}); });
}); });
@ -5022,7 +5022,7 @@ describe('relations', function () {
cat.jobIds.should.eql(expected); cat.jobIds.should.eql(expected);
done(); done();
}); });
}) });
}); });
it('should include related items from scope', function(done) { it('should include related items from scope', function(done) {
@ -5071,7 +5071,7 @@ describe('relations', function () {
return Job.create({ name: 'Job 1' }) return Job.create({ name: 'Job 1' })
.then(function(p) { .then(function(p) {
job1 = p; job1 = p;
return Job.create({ name: 'Job 3' }) return Job.create({ name: 'Job 3' });
}) })
.then(function(p) { .then(function(p) {
job3 = p; job3 = p;
@ -5102,7 +5102,7 @@ describe('relations', function () {
Category.findOne() Category.findOne()
.then(function(cat) { .then(function(cat) {
cat.jobIds = [job2.id, job2.id]; cat.jobIds = [job2.id, job2.id];
cat.save() cat.save();
}) })
.then(function(p) { .then(function(p) {
should.not.exist(p); should.not.exist(p);
@ -5120,7 +5120,7 @@ describe('relations', function () {
Category.findOne() Category.findOne()
.then(function(cat) { .then(function(cat) {
cat.jobIds.should.eql([job2.id]); cat.jobIds.should.eql([job2.id]);
return cat.jobs.getAsync() return cat.jobs.getAsync();
}) })
.then(function(jobs) { .then(function(jobs) {
var p = jobs[0]; var p = jobs[0];
@ -5135,7 +5135,7 @@ describe('relations', function () {
Category.findOne() Category.findOne()
.then(function(cat) { .then(function(cat) {
cat.jobIds.should.eql([job2.id]); cat.jobIds.should.eql([job2.id]);
return cat.jobs.findById(job2.id) return cat.jobs.findById(job2.id);
}) })
.then(function(p) { .then(function(p) {
p.should.be.instanceof(Job); p.should.be.instanceof(Job);
@ -5165,7 +5165,7 @@ describe('relations', function () {
.then(function(p) { .then(function(p) {
p.name.should.equal(attrs.name); p.name.should.equal(attrs.name);
done(); done();
}) });
}) })
.catch(done); .catch(done);
}); });
@ -5173,7 +5173,7 @@ describe('relations', function () {
it('should get a record by index with promises - at', function(done) { it('should get a record by index with promises - at', function(done) {
Category.findOne() Category.findOne()
.then(function(cat) { .then(function(cat) {
return cat.jobs.at(0) return cat.jobs.at(0);
}) })
.then(function(p) { .then(function(p) {
p.should.be.instanceof(Job); p.should.be.instanceof(Job);
@ -5216,7 +5216,7 @@ describe('relations', function () {
it('should find items on scope with promises - findById', function(done) { it('should find items on scope with promises - findById', function(done) {
Category.findOne() Category.findOne()
.then(function(cat) { .then(function(cat) {
return cat.jobs.findById(job3.id) return cat.jobs.findById(job3.id);
}) })
.then(function(p) { .then(function(p) {
p.id.should.eql(job3.id); p.id.should.eql(job3.id);
@ -5230,7 +5230,7 @@ describe('relations', function () {
Category.findOne() Category.findOne()
.then(function(cat) { .then(function(cat) {
var filter = { where: { name: 'Job 1' }}; var filter = { where: { name: 'Job 1' }};
return cat.jobs.getAsync(filter) return cat.jobs.getAsync(filter);
}) })
.then(function(jobs) { .then(function(jobs) {
jobs.should.have.length(1); jobs.should.have.length(1);
@ -5261,7 +5261,7 @@ describe('relations', function () {
.then(function(cat) { .then(function(cat) {
var expected = [job2.id, job3.id]; var expected = [job2.id, job3.id];
cat.jobIds.should.eql(expected); cat.jobIds.should.eql(expected);
return cat.jobs.getAsync() return cat.jobs.getAsync();
}) })
.then(function(jobs) { .then(function(jobs) {
jobs.should.have.length(2); jobs.should.have.length(2);
@ -5276,7 +5276,7 @@ describe('relations', function () {
Category.find() Category.find()
.then(function(categories) { .then(function(categories) {
categories.should.have.length(1); categories.should.have.length(1);
return categories[0].jobs.getAsync({order: 'name DESC'}) return categories[0].jobs.getAsync({ order: 'name DESC' });
}) })
.then(function(jobs) { .then(function(jobs) {
jobs.should.have.length(2); jobs.should.have.length(2);
@ -5321,7 +5321,7 @@ describe('relations', function () {
.then(function() { .then(function() {
var expected = [job3.id]; var expected = [job3.id];
cat.jobIds.should.eql(expected); cat.jobIds.should.eql(expected);
return Job.exists(job2.id) return Job.exists(job2.id);
}) })
.then(function(exists) { .then(function(exists) {
should.exist(exists); should.exist(exists);
@ -5337,7 +5337,7 @@ describe('relations', function () {
.then(function(cat) { .then(function(cat) {
var expected = [job3.id]; var expected = [job3.id];
cat.jobIds.should.eql(expected); cat.jobIds.should.eql(expected);
return cat.jobs.getAsync() return cat.jobs.getAsync();
}) })
.then(function(jobs) { .then(function(jobs) {
jobs.should.have.length(1); jobs.should.have.length(1);
@ -5398,14 +5398,14 @@ describe('relations', function () {
cat.jobs.create({ name: 'Job 2' }, function(err, p) { cat.jobs.create({ name: 'Job 2' }, function(err, p) {
done(); done();
}); });
}) });
}); });
}); });
it('should allow custom scope methods - summarize', function(done) { it('should allow custom scope methods - summarize', function(done) {
var expected = [ var expected = [
{ name: 'Job 1', categoryId: categoryId, categoryName: 'Category A' }, { name: 'Job 1', categoryId: categoryId, categoryName: 'Category A' },
{ name: 'Job 2', categoryId: categoryId, categoryName: 'Category A' } { name: 'Job 2', categoryId: categoryId, categoryName: 'Category A' },
]; ];
Category.findOne(function(err, cat) { Category.findOne(function(err, cat) {
@ -5418,18 +5418,18 @@ describe('relations', function () {
result.should.eql(expected); result.should.eql(expected);
done(); done();
}); });
}) });
}); });
it('should allow custom scope methods with promises - summarize', function(done) { it('should allow custom scope methods with promises - summarize', function(done) {
var expected = [ var expected = [
{ name: 'Job 1', categoryId: categoryId, categoryName: 'Category A' }, { name: 'Job 1', categoryId: categoryId, categoryName: 'Category A' },
{ name: 'Job 2', categoryId: categoryId, categoryName: 'Category A' } { name: 'Job 2', categoryId: categoryId, categoryName: 'Category A' },
]; ];
Category.findOne() Category.findOne()
.then(function(cat) { .then(function(cat) {
return cat.jobs.summarize() return cat.jobs.summarize();
}) })
.then(function(summary) { .then(function(summary) {
var result = summary.map(function(item) { var result = summary.map(function(item) {

View File

@ -13,22 +13,22 @@ describe('scope', function () {
before(function() { before(function() {
db = getSchema(); db = getSchema();
Railway = db.define('Railway', { Railway = db.define('Railway', {
URID: {type: String, index: true} URID: { type: String, index: true },
}, { }, {
scopes: { scopes: {
highSpeed: { highSpeed: {
where: { where: {
highSpeed: true highSpeed: true,
} },
} },
} },
}); });
Station = db.define('Station', { Station = db.define('Station', {
USID: { type: String, index: true }, USID: { type: String, index: true },
capacity: { type: Number, index: true }, capacity: { type: Number, index: true },
thoughput: { type: Number, index: true }, thoughput: { type: Number, index: true },
isActive: { type: Boolean, index: true }, isActive: { type: Boolean, index: true },
isUndeground: {type: Boolean, index: true} isUndeground: { type: Boolean, index: true },
}); });
}); });
@ -64,7 +64,7 @@ describe('scope', function () {
station.isActive.should.be.true; station.isActive.should.be.true;
station.isUndeground.should.be.true; station.isUndeground.should.be.true;
done(); done();
}) });
}); });
it('should query all', function(done) { it('should query all', function(done) {
@ -111,7 +111,7 @@ describe('scope - order', function () {
db = getSchema(); db = getSchema();
Station = db.define('Station', { Station = db.define('Station', {
name: { type: String, index: true }, name: { type: String, index: true },
order: {type: Number, index: true} order: { type: Number, index: true },
}); });
Station.scope('reverse', { order: 'order DESC' }); Station.scope('reverse', { order: 'order DESC' });
}); });
@ -168,7 +168,7 @@ describe('scope - filtered count, updateAll and destroyAll', function () {
name: { type: String, index: true }, name: { type: String, index: true },
order: { type: Number, index: true }, order: { type: Number, index: true },
active: { type: Boolean, index: true, default: true }, active: { type: Boolean, index: true, default: true },
flagged: {type: Boolean, index: true, default: false} flagged: { type: Boolean, index: true, default: false },
}); });
Station.scope('ordered', { order: 'order' }); Station.scope('ordered', { order: 'order' });
Station.scope('active', { where: { active: true }}); Station.scope('active', { where: { active: true }});
@ -350,7 +350,7 @@ describe('scope - dynamic target class', function () {
Collection.destroyAll(function() { Collection.destroyAll(function() {
Image.destroyAll(function() { Image.destroyAll(function() {
Video.destroyAll(done); Video.destroyAll(done);
}) });
}); });
}); });
@ -425,13 +425,13 @@ describe('scope - dynamic function', function () {
Item.scope('dynamicQuery', function() { Item.scope('dynamicQuery', function() {
seed++; seed++;
return { where:{ creator:seed }}; return { where:{ creator:seed }};
}) });
}); });
beforeEach(function(done) { beforeEach(function(done) {
Item.create({ title:1, creator:1 }, function() { Item.create({ title:1, creator:1 }, function() {
Item.create({ title:2,creator:2 },done) Item.create({ title:2, creator:2 }, done);
}) });
}); });
it('should deduce item by runtime creator', function(done) { it('should deduce item by runtime creator', function(done) {
@ -442,7 +442,7 @@ describe('scope - dynamic function', function () {
should.not.exist(err); should.not.exist(err);
secondQuery.title.should.equal(2); secondQuery.title.should.equal(2);
done(); done();
}) });
}) });
}) });
}); });

View File

@ -33,7 +33,7 @@ function context(name, tests) {
}, },
after: function(f) { after: function(f) {
it('tearDown', f); it('tearDown', f);
} },
}); });
group_name = false; group_name = false;
} }

View File

@ -26,7 +26,7 @@ describe('Transient connector', function () {
Widget = db.define('Widget', { name: String }); Widget = db.define('Widget', { name: String });
Item = db.define('Item', { Item = db.define('Item', {
id: {type: Number, id: true}, name: String id: { type: Number, id: true }, name: String,
}); });
}); });

View File

@ -18,7 +18,7 @@ describe('util.fieldsToArray', function () {
return { return {
expect: function(arr) { expect: function(arr) {
should.deepEqual(fieldsToArray(fields, properties, excludeUnknown), arr); should.deepEqual(fieldsToArray(fields, properties, excludeUnknown), arr);
} },
}; };
} }
@ -76,7 +76,7 @@ describe('util.removeUndefined', function () {
should.deepEqual(removeUndefined(q5, 'nullify'), { where: { x: 1, y: null }}); should.deepEqual(removeUndefined(q5, 'nullify'), { where: { x: 1, y: null }});
var q6 = { where: { x: 1, y: undefined }}; var q6 = { where: { x: 1, y: undefined }};
(function(){ removeUndefined(q6, 'throw') }).should.throw(/`undefined` in query/); (function() { removeUndefined(q6, 'throw'); }).should.throw(/`undefined` in query/);
}); });
}); });
@ -163,7 +163,7 @@ describe('mergeSettings', function () {
{ permission: 'ALLOW', { permission: 'ALLOW',
property: 'findById', property: 'findById',
principalType: 'ROLE', principalType: 'ROLE',
principalId: '$owner' } principalId: '$owner' },
] }; ] };
var tgt = { strict: false, var tgt = { strict: false,
acls: [ acls: [
@ -174,7 +174,7 @@ describe('mergeSettings', function () {
{ principalType: 'ROLE', { principalType: 'ROLE',
principalId: '$owner', principalId: '$owner',
permission: 'ALLOW', permission: 'ALLOW',
property: 'removeById' } property: 'removeById' },
], ],
maxTTL: 31556926, maxTTL: 31556926,
ttl: 1209600 }; ttl: 1209600 };
@ -203,7 +203,7 @@ describe('mergeSettings', function () {
{ permission: 'ALLOW', { permission: 'ALLOW',
property: 'findById', property: 'findById',
principalType: 'ROLE', principalType: 'ROLE',
principalId: '$owner' } principalId: '$owner' },
], ],
maxTTL: 31556926, maxTTL: 31556926,
ttl: 1209600, ttl: 1209600,
@ -224,7 +224,7 @@ describe('sortObjectsByIds', function () {
{ id: 3, name: 'c' }, { id: 3, name: 'c' },
{ id: 4, name: 'd' }, { id: 4, name: 'd' },
{ id: 5, name: 'e' }, { id: 5, name: 'e' },
{ id: 6, name: 'f' } { id: 6, name: 'f' },
]; ];
it('should sort', function() { it('should sort', function() {
@ -260,7 +260,7 @@ describe('util.mergeIncludes', function () {
var updateInclude = 'relation2'; var updateInclude = 'relation2';
var expectedInclude = [ var expectedInclude = [
{ relation2: true }, { relation2: true },
{relation1: true} { relation1: true },
]; ];
checkInputOutput(baseInclude, updateInclude, expectedInclude); checkInputOutput(baseInclude, updateInclude, expectedInclude);
}); });
@ -270,7 +270,7 @@ describe('util.mergeIncludes', function () {
var updateInclude = ['relation2']; var updateInclude = ['relation2'];
var expectedInclude = [ var expectedInclude = [
{ relation2: true }, { relation2: true },
{relation1: true} { relation1: true },
]; ];
checkInputOutput(baseInclude, updateInclude, expectedInclude); checkInputOutput(baseInclude, updateInclude, expectedInclude);
}); });
@ -280,7 +280,7 @@ describe('util.mergeIncludes', function () {
var updateInclude = { relation2: 'relation2Include' }; var updateInclude = { relation2: 'relation2Include' };
var expectedInclude = [ var expectedInclude = [
{ relation2: 'relation2Include' }, { relation2: 'relation2Include' },
{relation1: true} { relation1: true },
]; ];
checkInputOutput(baseInclude, updateInclude, expectedInclude); checkInputOutput(baseInclude, updateInclude, expectedInclude);
}); });
@ -290,7 +290,7 @@ describe('util.mergeIncludes', function () {
var updateInclude = ['relation2']; var updateInclude = ['relation2'];
var expectedInclude = [ var expectedInclude = [
{ relation2: true }, { relation2: true },
{relation1: true} { relation1: true },
]; ];
checkInputOutput(baseInclude, updateInclude, expectedInclude); checkInputOutput(baseInclude, updateInclude, expectedInclude);
}); });
@ -300,7 +300,7 @@ describe('util.mergeIncludes', function () {
var updateInclude = { relation2: 'relation2Include' }; var updateInclude = { relation2: 'relation2Include' };
var expectedInclude = [ var expectedInclude = [
{ relation2: 'relation2Include' }, { relation2: 'relation2Include' },
{relation1: true} { relation1: true },
]; ];
checkInputOutput(baseInclude, updateInclude, expectedInclude); checkInputOutput(baseInclude, updateInclude, expectedInclude);
}); });
@ -310,7 +310,7 @@ describe('util.mergeIncludes', function () {
var updateInclude = { relation2: 'relation2Include' }; var updateInclude = { relation2: 'relation2Include' };
var expectedInclude = [ var expectedInclude = [
{ relation2: 'relation2Include' }, { relation2: 'relation2Include' },
{relation1: 'relation1Include'} { relation1: 'relation1Include' },
]; ];
checkInputOutput(baseInclude, updateInclude, expectedInclude); checkInputOutput(baseInclude, updateInclude, expectedInclude);
}); });
@ -319,7 +319,7 @@ describe('util.mergeIncludes', function () {
var baseInclude = { relation1: 'baseValue' }; var baseInclude = { relation1: 'baseValue' };
var updateInclude = { relation1: 'updateValue' }; var updateInclude = { relation1: 'updateValue' };
var expectedInclude = [ var expectedInclude = [
{relation1: 'updateValue'} { relation1: 'updateValue' },
]; ];
checkInputOutput(baseInclude, updateInclude, expectedInclude); checkInputOutput(baseInclude, updateInclude, expectedInclude);
}); });
@ -329,7 +329,7 @@ describe('util.mergeIncludes', function () {
var baseInclude = 'relation1'; var baseInclude = 'relation1';
var updateInclude = { relation: 'relation1' }; var updateInclude = { relation: 'relation1' };
var expectedInclude = [ var expectedInclude = [
{relation: 'relation1'} { relation: 'relation1' },
]; ];
checkInputOutput(baseInclude, updateInclude, expectedInclude); checkInputOutput(baseInclude, updateInclude, expectedInclude);
}); });
@ -338,10 +338,10 @@ describe('util.mergeIncludes', function () {
var baseInclude = 'relation1'; var baseInclude = 'relation1';
var updateInclude = { var updateInclude = {
relation: 'relation1', relation: 'relation1',
scope: {include: 'relation2'} scope: { include: 'relation2' },
}; };
var expectedInclude = [ var expectedInclude = [
{relation: 'relation1', scope: {include: 'relation2'}} { relation: 'relation1', scope: { include: 'relation2' }},
]; ];
checkInputOutput(baseInclude, updateInclude, expectedInclude); checkInputOutput(baseInclude, updateInclude, expectedInclude);
}); });
@ -352,11 +352,11 @@ describe('util.mergeIncludes', function () {
var baseInclude = ['relation2']; var baseInclude = ['relation2'];
var updateInclude = { var updateInclude = {
relation: 'relation1', relation: 'relation1',
scope: {include: 'relation2'} scope: { include: 'relation2' },
}; };
var expectedInclude = [{ var expectedInclude = [{
relation: 'relation1', relation: 'relation1',
scope: {include: 'relation2'} scope: { include: 'relation2' },
}, { relation2: true }]; }, { relation2: true }];
checkInputOutput(baseInclude, updateInclude, expectedInclude); checkInputOutput(baseInclude, updateInclude, expectedInclude);
@ -377,7 +377,7 @@ describe('util.mergeIncludes', function () {
it('Merge includes with mixture of strings, arrays & objects properly', function() { it('Merge includes with mixture of strings, arrays & objects properly', function() {
var baseInclude = ['relation1', { relation2: true }, var baseInclude = ['relation1', { relation2: true },
{ relation: 'relation3', scope: { where: { id: 'some id' }}}, { relation: 'relation3', scope: { where: { id: 'some id' }}},
{relation: 'relation5', scope: {where: {id: 'some id'}}} { relation: 'relation5', scope: { where: { id: 'some id' }}},
]; ];
var updateInclude = ['relation4', { relation3: true }, var updateInclude = ['relation4', { relation3: true },
{ relation: 'relation2', scope: { where: { id: 'some id' }}}]; { relation: 'relation2', scope: { where: { id: 'some id' }}}];

View File

@ -18,7 +18,7 @@ function getValidAttributes() {
age: 26, age: 26,
gender: 'male', gender: 'male',
createdByAdmin: false, createdByAdmin: false,
createdByScript: true createdByScript: true,
}; };
} }
@ -39,11 +39,11 @@ describe('validations', function () {
pendingPeriod: Number, pendingPeriod: Number,
createdByAdmin: Boolean, createdByAdmin: Boolean,
createdByScript: Boolean, createdByScript: Boolean,
updatedAt: Date updatedAt: Date,
}); });
Entry = db.define('Entry', { Entry = db.define('Entry', {
id: { type: 'string', id: true, generated: false }, id: { type: 'string', id: true, generated: false },
name: { type: 'string' } name: { type: 'string' },
}); });
Entry.validatesUniquenessOf('id'); Entry.validatesUniquenessOf('id');
db.automigrate(done); db.automigrate(done);
@ -192,7 +192,7 @@ describe('validations', function () {
should.not.exist(e); should.not.exist(e);
done(); done();
}); });
}) });
}); });
}); });
@ -327,7 +327,7 @@ describe('validations', function () {
it('should skip validation by property (if/unless)', function() { it('should skip validation by property (if/unless)', function() {
User.validatesPresenceOf('domain', { unless: 'createdByScript' }); User.validatesPresenceOf('domain', { unless: 'createdByScript' });
var user = new User(getValidAttributes()) var user = new User(getValidAttributes());
user.isValid().should.be.true; user.isValid().should.be.true;
user.createdByScript = false; user.createdByScript = false;
@ -390,7 +390,7 @@ describe('validations', function () {
var EMAIL = 'user@xample.com'; var EMAIL = 'user@xample.com';
var SiteUser = db.define('SiteUser', { var SiteUser = db.define('SiteUser', {
siteId: String, siteId: String,
email: String email: String,
}); });
SiteUser.validatesUniquenessOf('email', { scopedTo: ['siteId'] }); SiteUser.validatesUniquenessOf('email', { scopedTo: ['siteId'] });
async.waterfall([ async.waterfall([
@ -413,7 +413,7 @@ describe('validations', function () {
valid.should.be.false; valid.should.be.false;
next(); next();
}); });
} },
], function(err) { ], function(err) {
if (err && err.name == 'ValidationError') { if (err && err.name == 'ValidationError') {
console.error('ValidationError:', err.details.messages); console.error('ValidationError:', err.details.messages);
@ -440,7 +440,7 @@ describe('validations', function () {
it('should work with if/unless', function(done) { it('should work with if/unless', function(done) {
User.validatesUniquenessOf('email', { User.validatesUniquenessOf('email', {
if: function() { return true; }, if: function() { return true; },
unless: function() { return false; } unless: function() { return false; },
}); });
var u = new User({ email: 'hello' }); var u = new User({ email: 'hello' });
Boolean(u.isValid(function(valid) { Boolean(u.isValid(function(valid) {
@ -542,7 +542,7 @@ describe('validations', function () {
process.nextTick(next); process.nextTick(next);
}, { }, {
if: function() { return true; }, if: function() { return true; },
unless: function() { return false; } unless: function() { return false; },
}); });
var u = new User({ email: 'hello' }); var u = new User({ email: 'hello' });
Boolean(u.isValid(function(valid) { Boolean(u.isValid(function(valid) {
@ -611,7 +611,7 @@ describe('validations', function () {
var obj = { var obj = {
errors: errorVal, errors: errorVal,
toJSON: function() { return jsonVal; } toJSON: function() { return jsonVal; },
}; };
return new ValidationError(obj); return new ValidationError(obj);
} }