Merge pull request #734 from strongloop/feature/jscs-style-check-and-cleanup

jscs style check and cleanup
This commit is contained in:
Miroslav Bajtoš 2014-11-04 13:16:52 +01:00
commit 2f1a1bcd7a
18 changed files with 254 additions and 222 deletions

22
.jscsrc Normal file
View File

@ -0,0 +1,22 @@
{
"preset": "google",
"requireCurlyBraces": [
"else",
"for",
"while",
"do",
"try",
"catch"
],
"disallowSpacesInsideObjectBrackets": null,
"maximumLineLength": {
"value": 150,
"allowComments": true,
"allowRegex": true
},
"validateJSDoc": {
"checkParamNames": false,
"checkRedundantParams": true,
"requireParamTypes": true
}
}

View File

@ -9,6 +9,7 @@
"trailing": true,
"newcap": true,
"nonew": true,
"sub": true,
"laxcomma": true,
"laxbreak": true
}

View File

@ -33,9 +33,16 @@ module.exports = function(grunt) {
lib: {
src: ['lib/**/*.js']
},
test: {
src: ['test/**/*.js']
}
// TODO(bajtos) - common/**/*.js
// TODO tests don't pass yet
// test: {
// src: ['test/**/*.js']
// }
},
jscs: {
gruntfile: 'Gruntfile.js',
lib: ['lib/**/*.js']
// TODO(bajtos) - common/**/*.js
},
watch: {
gruntfile: {
@ -80,7 +87,7 @@ module.exports = function(grunt) {
karma: {
'unit-once': {
configFile: 'test/karma.conf.js',
browsers: [ 'PhantomJS' ],
browsers: ['PhantomJS'],
singleRun: true,
reporters: ['dots', 'junit'],
@ -182,6 +189,7 @@ module.exports = function(grunt) {
grunt.loadNpmTasks('grunt-contrib-uglify');
grunt.loadNpmTasks('grunt-contrib-jshint');
grunt.loadNpmTasks('grunt-contrib-watch');
grunt.loadNpmTasks('grunt-jscs');
grunt.loadNpmTasks('grunt-karma');
grunt.registerTask('e2e-server', function() {
@ -196,6 +204,8 @@ module.exports = function(grunt) {
grunt.registerTask('default', ['browserify']);
grunt.registerTask('test', [
'jscs',
'jshint',
process.env.JENKINS_HOME ? 'mochaTest:unit-xml' : 'mochaTest:unit',
'karma:unit-once']);

View File

@ -38,13 +38,13 @@ function AccessContext(context) {
this.method = context.method;
this.sharedMethod = context.sharedMethod;
this.sharedClass = this.sharedMethod && this.sharedMethod.sharedClass;
if(this.sharedMethod) {
if (this.sharedMethod) {
this.methodNames = this.sharedMethod.aliases.concat([this.sharedMethod.name]);
} else {
this.methodNames = [];
}
if(this.sharedMethod) {
if (this.sharedMethod) {
this.accessType = this.model._getAccessTypeForMethod(this.sharedMethod);
}
@ -100,7 +100,7 @@ AccessContext.permissionOrder = {
* @param {String} [principalName] The principal name
* @returns {boolean}
*/
AccessContext.prototype.addPrincipal = function (principalType, principalId, principalName) {
AccessContext.prototype.addPrincipal = function(principalType, principalId, principalName) {
var principal = new Principal(principalType, principalId, principalName);
for (var i = 0; i < this.principals.length; i++) {
var p = this.principals[i];
@ -126,7 +126,6 @@ AccessContext.prototype.getUserId = function() {
return null;
};
/**
* Get the application id
* @returns {*}
@ -154,9 +153,9 @@ AccessContext.prototype.isAuthenticated = function() {
*/
AccessContext.prototype.debug = function() {
if(debug.enabled) {
if (debug.enabled) {
debug('---AccessContext---');
if(this.principals && this.principals.length) {
if (this.principals && this.principals.length) {
debug('principals:');
this.principals.forEach(function(principal) {
debug('principal: %j', principal);
@ -169,7 +168,7 @@ AccessContext.prototype.debug = function() {
debug('property %s', this.property);
debug('method %s', this.method);
debug('accessType %s', this.accessType);
if(this.accessToken) {
if (this.accessToken) {
debug('accessToken:');
debug(' id %j', this.accessToken.id);
debug(' ttl %j', this.accessToken.ttl);
@ -206,9 +205,9 @@ Principal.SCOPE = 'SCOPE';
/**
* Compare if two principals are equal
* Returns true if argument principal is equal to this principal.
* @param {Object} principal The other principal
* @param {Object} p The other principal
*/
Principal.prototype.equals = function (p) {
Principal.prototype.equals = function(p) {
if (p instanceof Principal) {
return this.type === p.type && String(this.id) === String(p.id);
}
@ -250,7 +249,7 @@ function AccessRequest(model, property, accessType, permission, methodNames) {
*
* @returns {Boolean}
*/
AccessRequest.prototype.isWildcard = function () {
AccessRequest.prototype.isWildcard = function() {
return this.model === AccessContext.ALL ||
this.property === AccessContext.ALL ||
this.accessType === AccessContext.ALL;
@ -268,7 +267,7 @@ AccessRequest.prototype.exactlyMatches = function(acl) {
var matchesMethodName = this.methodNames.indexOf(acl.property) !== -1;
var matchesAccessType = acl.accessType === this.accessType;
if(matchesModel && matchesAccessType) {
if (matchesModel && matchesAccessType) {
return matchesProperty || matchesMethodName;
}
@ -286,7 +285,7 @@ AccessRequest.prototype.isAllowed = function() {
};
AccessRequest.prototype.debug = function() {
if(debug.enabled) {
if (debug.enabled) {
debug('---AccessRequest---');
debug(' model %s', this.model);
debug(' property %s', this.property);
@ -300,6 +299,3 @@ AccessRequest.prototype.debug = function() {
module.exports.AccessContext = AccessContext;
module.exports.Principal = Principal;
module.exports.AccessRequest = AccessRequest;

View File

@ -2,15 +2,15 @@
* Module dependencies.
*/
var DataSource = require('loopback-datasource-juggler').DataSource
, registry = require('./registry')
, assert = require('assert')
, fs = require('fs')
, extend = require('util')._extend
, _ = require('underscore')
, RemoteObjects = require('strong-remoting')
, stringUtils = require('underscore.string')
, path = require('path');
var DataSource = require('loopback-datasource-juggler').DataSource;
var registry = require('./registry');
var assert = require('assert');
var fs = require('fs');
var extend = require('util')._extend;
var _ = require('underscore');
var RemoteObjects = require('strong-remoting');
var stringUtils = require('underscore.string');
var path = require('path');
/**
* The `App` object represents a Loopback application.
@ -41,7 +41,7 @@ function App() {
* Export the app prototype.
*/
var app = exports = module.exports = {};
var app = module.exports = {};
/**
* Lazily load a set of [remote objects](http://apidocs.strongloop.com/strong-remoting/#remoteobjectsoptions).
@ -50,13 +50,13 @@ var app = exports = module.exports = {};
* @returns {RemoteObjects}
*/
app.remotes = function () {
if(this._remotes) {
app.remotes = function() {
if (this._remotes) {
return this._remotes;
} else {
var options = {};
if(this.get) {
if (this.get) {
options = this.get('remoting');
}
@ -68,10 +68,10 @@ app.remotes = function () {
* Remove a route by reference.
*/
app.disuse = function (route) {
if(this.stack) {
app.disuse = function(route) {
if (this.stack) {
for (var i = 0; i < this.stack.length; i++) {
if(this.stack[i].route === route) {
if (this.stack[i].route === route) {
this.stack.splice(i, 1);
}
}
@ -102,7 +102,7 @@ app.disuse = function (route) {
* @returns {ModelConstructor} the model class
*/
app.model = function (Model, config) {
app.model = function(Model, config) {
var isPublic = true;
if (arguments.length > 1) {
config = config || {};
@ -166,7 +166,7 @@ app.model = function (Model, config) {
* ```js
* var models = app.models();
*
* models.forEach(function (Model) {
* models.forEach(function(Model) {
* console.log(Model.modelName); // color
* });
* ```
@ -205,7 +205,7 @@ app.model = function (Model, config) {
* @returns {Array} Array of model classes.
*/
app.models = function () {
app.models = function() {
return this._models || (this._models = []);
};
@ -215,7 +215,7 @@ app.models = function () {
* @param {String} name The data source name
* @param {Object} config The data source config
*/
app.dataSource = function (name, config) {
app.dataSource = function(name, config) {
var ds = dataSourcesFromConfig(config, this.connectors);
this.dataSources[name] =
this.dataSources[classify(name)] =
@ -248,7 +248,7 @@ app.connector = function(name, connector) {
* @returns {Object} [Remote objects](http://apidocs.strongloop.com/strong-remoting/#remoteobjectsoptions).
*/
app.remoteObjects = function () {
app.remoteObjects = function() {
var result = {};
this.remotes().classes().forEach(function(sharedClass) {
@ -263,9 +263,9 @@ app.remoteObjects = function () {
* @triggers `mounted` events on shared class constructors (models)
*/
app.handler = function (type, options) {
app.handler = function(type, options) {
var handlers = this._handlers || (this._handlers = {});
if(handlers[type]) {
if (handlers[type]) {
return handlers[type];
}
@ -301,21 +301,21 @@ app.enableAuth = function() {
var modelSettings = Model.settings || {};
var errStatusCode = modelSettings.aclErrorStatus || app.get('aclErrorStatus') || 401;
if(!req.accessToken){
if (!req.accessToken) {
errStatusCode = 401;
}
if(Model.checkAccess) {
if (Model.checkAccess) {
Model.checkAccess(
req.accessToken,
modelId,
method,
ctx,
function(err, allowed) {
if(err) {
if (err) {
console.log(err);
next(err);
} else if(allowed) {
} else if (allowed) {
next();
} else {
@ -358,7 +358,7 @@ function dataSourcesFromConfig(config, connectorRegistry) {
assert(typeof config === 'object',
'cannont create data source without config object');
if(typeof config.connector === 'string') {
if (typeof config.connector === 'string') {
var name = config.connector;
if (connectorRegistry[name]) {
config.connector = connectorRegistry[name];
@ -380,14 +380,16 @@ function configureModel(ModelCtor, config, app) {
var dataSource = config.dataSource;
if(dataSource) {
if(typeof dataSource === 'string') {
if (dataSource) {
if (typeof dataSource === 'string') {
dataSource = app.dataSources[dataSource];
}
assert(dataSource instanceof DataSource,
ModelCtor.modelName + ' is referencing a dataSource that does not exist: "' +
config.dataSource +'"');
assert(
dataSource instanceof DataSource,
ModelCtor.modelName + ' is referencing a dataSource that does not exist: "' +
config.dataSource + '"'
);
}
config = extend({}, config);

View File

@ -8,11 +8,11 @@ module.exports = Connector;
* Module dependencies.
*/
var EventEmitter = require('events').EventEmitter
, debug = require('debug')('connector')
, util = require('util')
, inherits = util.inherits
, assert = require('assert');
var EventEmitter = require('events').EventEmitter;
var debug = require('debug')('connector');
var util = require('util');
var inherits = util.inherits;
var assert = require('assert');
/**
* Create a new `Connector` with the given `options`.
@ -38,9 +38,9 @@ inherits(Connector, EventEmitter);
* Create an connector instance from a JugglingDB adapter.
*/
Connector._createJDBAdapter = function (jdbModule) {
Connector._createJDBAdapter = function(jdbModule) {
var fauxSchema = {};
jdbModule.initialize(fauxSchema, function () {
jdbModule.initialize(fauxSchema, function() {
// connected
});
};
@ -49,6 +49,6 @@ Connector._createJDBAdapter = function (jdbModule) {
* Add default crud operations from a JugglingDB adapter.
*/
Connector.prototype._addCrudOperationsFromJDBAdapter = function (connector) {
Connector.prototype._addCrudOperationsFromJDBAdapter = function(connector) {
};

View File

@ -2,10 +2,10 @@
* Dependencies.
*/
var mailer = require('nodemailer')
, assert = require('assert')
, debug = require('debug')('loopback:connector:mail')
, loopback = require('../loopback');
var mailer = require('nodemailer');
var assert = require('assert');
var debug = require('debug')('loopback:connector:mail');
var loopback = require('../loopback');
/**
* Export the MailConnector class.
@ -24,19 +24,19 @@ function MailConnector(settings) {
var transports = settings.transports;
//if transports is not in settings object AND settings.transport exists
if(!transports && settings.transport){
if (!transports && settings.transport) {
//then wrap single transport in an array and assign to transports
transports = [settings.transport];
}
if(!transports){
if (!transports) {
transports = [];
}
this.transportsIndex = {};
this.transports = [];
if(loopback.isServer) {
if (loopback.isServer) {
transports.forEach(this.setupTransport.bind(this));
}
}
@ -48,7 +48,6 @@ MailConnector.initialize = function(dataSource, callback) {
MailConnector.prototype.DataAccessObject = Mailer;
/**
* Add a transport to the available transports. See https://github.com/andris9/Nodemailer#setting-up-a-transport-method.
*
@ -132,7 +131,7 @@ MailConnector.prototype.defaultTransport = function() {
* @param {Function} callback Called after the e-mail is sent or the sending failed
*/
Mailer.send = function (options, fn) {
Mailer.send = function(options, fn) {
var dataSource = this.dataSource;
var settings = dataSource && dataSource.settings;
var connector = dataSource.connector;
@ -140,13 +139,13 @@ Mailer.send = function (options, fn) {
var transport = connector.transportForName(options.transport);
if(!transport) {
if (!transport) {
transport = connector.defaultTransport();
}
if(debug.enabled || settings && settings.debug) {
if (debug.enabled || settings && settings.debug) {
console.log('Sending Mail:');
if(options.transport) {
if (options.transport) {
console.log('\t TRANSPORT:', options.transport);
}
console.log('\t TO:', options.to);
@ -156,12 +155,12 @@ Mailer.send = function (options, fn) {
console.log('\t HTML:', options.html);
}
if(transport) {
if (transport) {
assert(transport.sendMail, 'You must supply an Email.settings.transports containing a valid transport');
transport.sendMail(options, fn);
} else {
console.warn('Warning: No email transport specified for sending email.'
+ ' Setup a transport to send mail messages.');
console.warn('Warning: No email transport specified for sending email.' +
' Setup a transport to send mail messages.');
process.nextTick(function() {
fn(null, options);
});
@ -172,7 +171,7 @@ Mailer.send = function (options, fn) {
* Send an email instance using `modelInstance.send()`.
*/
Mailer.prototype.send = function (fn) {
Mailer.prototype.send = function(fn) {
this.constructor.send(this, fn);
};

View File

@ -8,12 +8,12 @@ module.exports = Memory;
* Module dependencies.
*/
var Connector = require('./base-connector')
, debug = require('debug')('memory')
, util = require('util')
, inherits = util.inherits
, assert = require('assert')
, JdbMemory = require('loopback-datasource-juggler/lib/connectors/memory');
var Connector = require('./base-connector');
var debug = require('debug')('memory');
var util = require('util');
var inherits = util.inherits;
var assert = require('assert');
var JdbMemory = require('loopback-datasource-juggler/lib/connectors/memory');
/**
* Create a new `Memory` connector with the given `options`.

View File

@ -12,7 +12,7 @@ function safeRequire(m) {
}
function createMiddlewareNotInstalled(memberName, moduleName) {
return function () {
return function() {
var msg = 'The middleware loopback.' + memberName + ' is not installed.\n' +
'Run `npm install --save ' + moduleName + '` to fix the problem.';
throw new Error(msg);
@ -47,7 +47,7 @@ for (var m in middlewareModules) {
// serve-favicon requires a path
var favicon = middlewares.favicon;
middlewares.favicon = function (icon, options) {
middlewares.favicon = function(icon, options) {
icon = icon || path.join(__dirname, '../favicon.ico');
return favicon(icon, options);
};

View File

@ -2,13 +2,13 @@
* Module dependencies.
*/
var express = require('express')
, proto = require('./application')
, fs = require('fs')
, ejs = require('ejs')
, path = require('path')
, merge = require('util')._extend
, assert = require('assert');
var express = require('express');
var proto = require('./application');
var fs = require('fs');
var ejs = require('ejs');
var path = require('path');
var merge = require('util')._extend;
var assert = require('assert');
/**
* LoopBack core module. It provides static properties and
@ -28,7 +28,7 @@ var express = require('express')
* @header loopback
*/
var loopback = exports = module.exports = createApplication;
var loopback = module.exports = createApplication;
/*!
* Framework version.
@ -118,10 +118,10 @@ if (loopback.isServer) {
if (loopback.isServer) {
fs
.readdirSync(path.join(__dirname, 'middleware'))
.filter(function (file) {
.filter(function(file) {
return file.match(/\.js$/);
})
.forEach(function (m) {
.forEach(function(m) {
loopback[m.replace(/\.js$/, '')] = require('./middleware/' + m);
});
}
@ -157,10 +157,10 @@ loopback.errorHandler.title = 'Loopback';
* @param {Object} options (optional)
*/
loopback.remoteMethod = function (fn, options) {
loopback.remoteMethod = function(fn, options) {
fn.shared = true;
if(typeof options === 'object') {
Object.keys(options).forEach(function (key) {
if (typeof options === 'object') {
Object.keys(options).forEach(function(key) {
fn[key] = options[key];
});
}
@ -177,13 +177,12 @@ loopback.remoteMethod = function (fn, options) {
* @returns {Function}
*/
loopback.template = function (file) {
loopback.template = function(file) {
var templates = this._templates || (this._templates = {});
var str = templates[file] || (templates[file] = fs.readFileSync(file, 'utf8'));
return ejs.compile(str);
};
/*!
* Built in models / services
*/

View File

@ -12,7 +12,7 @@ module.exports = rest;
/**
* Expose models over REST.
*
*
* For example:
* ```js
* app.use(loopback.rest());
@ -23,13 +23,13 @@ module.exports = rest;
function rest() {
var tokenParser = null;
return function (req, res, next) {
return function(req, res, next) {
var app = req.app;
var handler = app.handler('rest');
if(req.url === '/routes') {
if (req.url === '/routes') {
res.send(handler.adapter.allRoutes());
} else if(req.url === '/models') {
} else if (req.url === '/models') {
return res.send(app.remotes().toJSON());
} else if (app.isAuthEnabled) {
if (!tokenParser) {
@ -55,4 +55,3 @@ function rest() {
}
};
}

View File

@ -27,4 +27,3 @@ function status() {
});
};
}

View File

@ -48,7 +48,7 @@ function token(options) {
var TokenModel = options.model || loopback.AccessToken;
assert(TokenModel, 'loopback.token() middleware requires a AccessToken model');
return function (req, res, next) {
return function(req, res, next) {
if (req.accessToken !== undefined) return next();
TokenModel.findForRequest(req, options, function(err, token) {
req.accessToken = token || null;
@ -56,4 +56,3 @@ function token(options) {
});
};
}

View File

@ -57,7 +57,7 @@ var stringUtils = require('underscore.string');
*
* ```js
* MyModel.on('deletedAll', function(where) {
* if(where) {
* if (where) {
* console.log('all models where ', where, ' have been deleted');
* // => all models where
* // => {price: {gt: 100}}
@ -98,7 +98,7 @@ var Model = module.exports = registry.modelBuilder.define('Model');
* Called when a model is extended.
*/
Model.setup = function () {
Model.setup = function() {
var ModelCtor = this;
var options = this.settings;
var typeName = this.modelName;
@ -119,17 +119,17 @@ Model.setup = function () {
});
// support remoting prototype methods
ModelCtor.sharedCtor = function (data, id, fn) {
ModelCtor.sharedCtor = function(data, id, fn) {
var ModelCtor = this;
if(typeof data === 'function') {
if (typeof data === 'function') {
fn = data;
data = null;
id = null;
} else if (typeof id === 'function') {
fn = id;
if(typeof data !== 'object') {
if (typeof data !== 'object') {
id = data;
data = null;
} else {
@ -137,17 +137,17 @@ Model.setup = function () {
}
}
if(id && data) {
if (id && data) {
var model = new ModelCtor(data);
model.id = id;
fn(null, model);
} else if(data) {
} else if (data) {
fn(null, new ModelCtor(data));
} else if(id) {
ModelCtor.findById(id, function (err, model) {
if(err) {
} else if (id) {
ModelCtor.findById(id, function(err, model) {
if (err) {
fn(err);
} else if(model) {
} else if (model) {
fn(null, model);
} else {
err = new Error('could not find a model with id ' + id);
@ -175,34 +175,34 @@ Model.setup = function () {
ModelCtor.sharedCtor.returns = {root: true};
// before remote hook
ModelCtor.beforeRemote = function (name, fn) {
ModelCtor.beforeRemote = function(name, fn) {
var self = this;
if(this.app) {
if (this.app) {
var remotes = this.app.remotes();
var className = self.modelName;
remotes.before(className + '.' + name, function (ctx, next) {
remotes.before(className + '.' + name, function(ctx, next) {
fn(ctx, ctx.result, next);
});
} else {
var args = arguments;
this.once('attached', function () {
this.once('attached', function() {
self.beforeRemote.apply(self, args);
});
}
};
// after remote hook
ModelCtor.afterRemote = function (name, fn) {
ModelCtor.afterRemote = function(name, fn) {
var self = this;
if(this.app) {
if (this.app) {
var remotes = this.app.remotes();
var className = self.modelName;
remotes.after(className + '.' + name, function (ctx, next) {
remotes.after(className + '.' + name, function(ctx, next) {
fn(ctx, ctx.result, next);
});
} else {
var args = arguments;
this.once('attached', function () {
this.once('attached', function() {
self.afterRemote.apply(self, args);
});
}
@ -246,11 +246,11 @@ Model.setup = function () {
*/
var _aclModel = null;
Model._ACL = function getACL(ACL) {
if(ACL !== undefined) {
if (ACL !== undefined) {
// The function is used as a setter
_aclModel = ACL;
}
if(_aclModel) {
if (_aclModel) {
return _aclModel;
}
var aclModel = registry.getModel('ACL');
@ -276,7 +276,7 @@ Model.checkAccess = function(token, modelId, sharedMethod, ctx, callback) {
var aclModel = Model._ACL();
ctx = ctx || {};
if(typeof ctx === 'function' && callback === undefined) {
if (typeof ctx === 'function' && callback === undefined) {
callback = ctx;
ctx = {};
}
@ -291,7 +291,7 @@ Model.checkAccess = function(token, modelId, sharedMethod, ctx, callback) {
accessType: this._getAccessTypeForMethod(sharedMethod),
remotingContext: ctx
}, function(err, accessRequest) {
if(err) return callback(err);
if (err) return callback(err);
callback(null, accessRequest.isAllowed());
});
};
@ -304,7 +304,7 @@ Model.checkAccess = function(token, modelId, sharedMethod, ctx, callback) {
*/
Model._getAccessTypeForMethod = function(method) {
if(typeof method === 'string') {
if (typeof method === 'string') {
method = {name: method};
}
assert(
@ -314,7 +314,7 @@ Model._getAccessTypeForMethod = function(method) {
var ACL = Model._ACL();
switch(method.name) {
switch (method.name) {
case'create':
return ACL.WRITE;
case 'updateOrCreate':
@ -353,7 +353,7 @@ Model._getAccessTypeForMethod = function(method) {
Model.getApp = function(callback) {
var Model = this;
if(this.app) {
if (this.app) {
callback(null, this.app);
} else {
Model.once('attached', function() {
@ -378,7 +378,7 @@ Model.getApp = function(callback) {
*/
Model.remoteMethod = function(name, options) {
if(options.isStatic === undefined) {
if (options.isStatic === undefined) {
options.isStatic = true;
}
this.sharedClass.defineMethod(name, options);
@ -423,7 +423,7 @@ Model.hasOneRemoting = function(relationName, relation, define) {
}, fn);
};
Model.hasManyRemoting = function (relationName, relation, define) {
Model.hasManyRemoting = function(relationName, relation, define) {
var pathName = (relation.options.http && relation.options.http.path) || relationName;
var toModelName = relation.modelTo.modelName;
@ -519,7 +519,7 @@ Model.hasManyRemoting = function (relationName, relation, define) {
rest: {
// After hook to map exists to 200/404 for HEAD
after: function(ctx, cb) {
if(ctx.result === false) {
if (ctx.result === false) {
var modelName = ctx.method.sharedClass.name;
var id = ctx.getArgByName('id');
var msg = 'Unknown "' + modelName + '" id "' + id + '".';
@ -536,8 +536,9 @@ Model.hasManyRemoting = function (relationName, relation, define) {
};
Model.scopeRemoting = function(scopeName, scope, define) {
var pathName = (scope.options && scope.options.http && scope.options.http.path)
|| scopeName;
var pathName =
(scope.options && scope.options.http && scope.options.http.path) || scopeName;
var isStatic = scope.isStatic;
var toModelName = scope.modelTo.modelName;
@ -592,10 +593,12 @@ Model.nestRemoting = function(relationName, options, cb) {
var paramName = options.paramName || 'nk';
var http = [].concat(sharedToClass.http || [])[0];
var httpPath;
var acceptArgs;
if (relation.multiple) {
var httpPath = pathName + '/:' + paramName;
var acceptArgs = [
httpPath = pathName + '/:' + paramName;
acceptArgs = [
{
arg: paramName, type: 'any', http: { source: 'path' },
description: 'Foreign key for ' + relation.name,
@ -603,8 +606,8 @@ Model.nestRemoting = function(relationName, options, cb) {
}
];
} else {
var httpPath = pathName;
var acceptArgs = [];
httpPath = pathName;
acceptArgs = [];
}
// A method should return the method name to use, if it is to be
@ -721,4 +724,3 @@ Model.ValidationError = require('loopback-datasource-juggler').ValidationError;
// setup the initial model
Model.setup();

View File

@ -37,7 +37,7 @@ PersistedModel.setup = function setupPersistedModel() {
var PersistedModel = this;
// enable change tracking (usually for replication)
if(this.settings.trackChanges) {
if (this.settings.trackChanges) {
PersistedModel._defineChangeModel();
PersistedModel.once('dataSourceAttached', function() {
PersistedModel.enableChangeTracking();
@ -53,9 +53,9 @@ PersistedModel.setup = function setupPersistedModel() {
function throwNotAttached(modelName, methodName) {
throw new Error(
'Cannot call ' + modelName + '.'+ methodName + '().'
+ ' The ' + methodName + ' method has not been setup.'
+ ' The PersistedModel has not been correctly attached to a DataSource!'
'Cannot call ' + modelName + '.' + methodName + '().' +
' The ' + methodName + ' method has not been setup.' +
' The PersistedModel has not been correctly attached to a DataSource!'
);
}
@ -84,7 +84,7 @@ function convertNullToNotFoundError(ctx, cb) {
* where `err` is error object and `obj` is null or Model instance.
*/
PersistedModel.create = function (data, callback) {
PersistedModel.create = function(data, callback) {
throwNotAttached(this.modelName, 'create');
};
@ -277,7 +277,7 @@ PersistedModel.deleteById = PersistedModel.destroyById;
* @param {Function} cb Callback function called with (err, count).
*/
PersistedModel.count = function (where, cb) {
PersistedModel.count = function(where, cb) {
throwNotAttached(this.modelName, 'count');
};
@ -290,7 +290,7 @@ PersistedModel.count = function (where, cb) {
* @param {Function} [callback] Callback function called with (err, obj).
*/
PersistedModel.prototype.save = function (options, callback) {
PersistedModel.prototype.save = function(options, callback) {
var Model = this.constructor;
if (typeof options == 'function') {
@ -298,7 +298,7 @@ PersistedModel.prototype.save = function (options, callback) {
options = {};
}
callback = callback || function () {
callback = callback || function() {
};
options = options || {};
@ -322,7 +322,7 @@ PersistedModel.prototype.save = function (options, callback) {
return save();
}
inst.isValid(function (valid) {
inst.isValid(function(valid) {
if (valid) {
save();
} else {
@ -337,12 +337,12 @@ PersistedModel.prototype.save = function (options, callback) {
// then save
function save() {
inst.trigger('save', function (saveDone) {
inst.trigger('update', function (updateDone) {
inst.trigger('save', function(saveDone) {
inst.trigger('update', function(updateDone) {
Model.upsert(inst, function(err) {
inst._initProperties(data);
updateDone.call(inst, function () {
saveDone.call(inst, function () {
updateDone.call(inst, function() {
saveDone.call(inst, function() {
callback(err, inst);
});
});
@ -357,7 +357,7 @@ PersistedModel.prototype.save = function (options, callback) {
* @returns {Boolean} Returns true if the data model is new; false otherwise.
*/
PersistedModel.prototype.isNewRecord = function () {
PersistedModel.prototype.isNewRecord = function() {
throwNotAttached(this.constructor.modelName, 'isNewRecord');
};
@ -367,7 +367,7 @@ PersistedModel.prototype.isNewRecord = function () {
* @param {Function} callback Callback function.
*/
PersistedModel.prototype.destroy = function (cb) {
PersistedModel.prototype.destroy = function(cb) {
throwNotAttached(this.constructor.modelName, 'destroy');
};
@ -440,7 +440,7 @@ PersistedModel.prototype.setId = function(val) {
PersistedModel.prototype.getId = function() {
var data = this.toObject();
if(!data) return;
if (!data) return;
return data[this.getIdName()];
};
@ -464,7 +464,7 @@ PersistedModel.getIdName = function() {
var Model = this;
var ds = Model.getDataSource();
if(ds.idName) {
if (ds.idName) {
return ds.idName(Model.modelName);
} else {
return 'id';
@ -513,7 +513,7 @@ PersistedModel.setupRemoting = function() {
// For GET, return {exists: true|false} as is
return cb();
}
if(!ctx.result.exists) {
if (!ctx.result.exists) {
var modelName = ctx.method.sharedClass.name;
var id = ctx.getArgByName('id');
var msg = 'Unknown "' + modelName + '" id "' + id + '".';
@ -594,7 +594,7 @@ PersistedModel.setupRemoting = function() {
http: {verb: 'put', path: '/'}
});
if(options.trackChanges) {
if (options.trackChanges) {
setRemoting(PersistedModel, 'diff', {
description: 'Get a set of deltas and conflicts since the given checkpoint',
accepts: [
@ -607,8 +607,8 @@ PersistedModel.setupRemoting = function() {
});
setRemoting(PersistedModel, 'changes', {
description: 'Get the changes to a model since a given checkpoint.'
+ 'Provide a filter object to reduce the number of results returned.',
description: 'Get the changes to a model since a given checkpoint.' +
'Provide a filter object to reduce the number of results returned.',
accepts: [
{arg: 'since', type: 'number', description: 'Only return changes since this checkpoint'},
{arg: 'filter', type: 'object', description: 'Only include changes that match this filter'}
@ -683,12 +683,12 @@ PersistedModel.diff = function(since, remoteChanges, callback) {
*/
PersistedModel.changes = function(since, filter, callback) {
if(typeof since === 'function') {
if (typeof since === 'function') {
filter = {};
callback = since;
since = -1;
}
if(typeof filter === 'function') {
if (typeof filter === 'function') {
callback = filter;
since = -1;
filter = {};
@ -708,18 +708,18 @@ PersistedModel.changes = function(since, filter, callback) {
checkpoint: {gt: since},
modelName: this.modelName
}, function(err, changes) {
if(err) return callback(err);
if (err) return callback(err);
var ids = changes.map(function(change) {
return change.getModelId();
});
filter.where[idName] = {inq: ids};
model.find(filter, function(err, models) {
if(err) return callback(err);
if (err) return callback(err);
var modelIds = models.map(function(m) {
return m[idName].toString();
});
callback(null, changes.filter(function(ch) {
if(ch.type() === Change.DELETE) return true;
if (ch.type() === Change.DELETE) return true;
return modelIds.indexOf(ch.modelId) > -1;
}));
});
@ -735,7 +735,7 @@ PersistedModel.changes = function(since, filter, callback) {
PersistedModel.checkpoint = function(cb) {
var Checkpoint = this.getChangeModel().getCheckpointModel();
this.getSourceId(function(err, sourceId) {
if(err) return cb(err);
if (err) return cb(err);
Checkpoint.create({
sourceId: sourceId
}, cb);
@ -772,11 +772,11 @@ PersistedModel.currentCheckpoint = function(cb) {
PersistedModel.replicate = function(since, targetModel, options, callback) {
var lastArg = arguments[arguments.length - 1];
if(typeof lastArg === 'function' && arguments.length > 1) {
if (typeof lastArg === 'function' && arguments.length > 1) {
callback = lastArg;
}
if(typeof since === 'function' && since.modelName) {
if (typeof since === 'function' && since.modelName) {
targetModel = since;
since = -1;
}
@ -796,7 +796,7 @@ PersistedModel.replicate = function(since, targetModel, options, callback) {
);
callback = callback || function defaultReplicationCallback(err) {
if(err) throw err;
if (err) throw err;
};
var tasks = [
@ -820,7 +820,7 @@ PersistedModel.replicate = function(since, targetModel, options, callback) {
function createSourceUpdates(_diff, cb) {
diff = _diff;
diff.conflicts = diff.conflicts || [];
if(diff && diff.deltas && diff.deltas.length) {
if (diff && diff.deltas && diff.deltas.length) {
sourceModel.createUpdates(diff.deltas, cb);
} else {
// nothing to replicate
@ -838,7 +838,7 @@ PersistedModel.replicate = function(since, targetModel, options, callback) {
}
function done(err) {
if(err) return callback(err);
if (err) return callback(err);
var conflicts = diff.conflicts.map(function(change) {
return new Change.Conflict(
@ -846,11 +846,11 @@ PersistedModel.replicate = function(since, targetModel, options, callback) {
);
});
if(conflicts.length) {
if (conflicts.length) {
sourceModel.emit('conflicts', conflicts);
}
callback && callback(null, conflicts);
if (callback) callback(null, conflicts);
}
};
@ -869,21 +869,21 @@ PersistedModel.createUpdates = function(deltas, cb) {
var tasks = [];
deltas.forEach(function(change) {
var change = new Change(change);
change = new Change(change);
var type = change.type();
var update = {type: type, change: change};
switch(type) {
switch (type) {
case Change.CREATE:
case Change.UPDATE:
tasks.push(function(cb) {
Model.findById(change.modelId, function(err, inst) {
if(err) return cb(err);
if(!inst) {
if (err) return cb(err);
if (!inst) {
console.error('missing data for change:', change);
return cb && cb(new Error('missing data for change: '
+ change.modelId));
return cb &&
cb(new Error('missing data for change: ' + change.modelId));
}
if(inst.toObject) {
if (inst.toObject) {
update.data = inst.toObject();
} else {
update.data = inst;
@ -892,15 +892,15 @@ PersistedModel.createUpdates = function(deltas, cb) {
cb();
});
});
break;
break;
case Change.DELETE:
updates.push(update);
break;
break;
}
});
async.parallel(tasks, function(err) {
if(err) return cb(err);
if (err) return cb(err);
cb(null, updates);
});
};
@ -921,7 +921,7 @@ PersistedModel.bulkUpdate = function(updates, callback) {
var Change = this.getChangeModel();
updates.forEach(function(update) {
switch(update.type) {
switch (update.type) {
case Change.UPDATE:
case Change.CREATE:
// var model = new Model(update.data);
@ -930,13 +930,13 @@ PersistedModel.bulkUpdate = function(updates, callback) {
var model = new Model(update.data);
model.save(cb);
});
break;
break;
case Change.DELETE:
var data = {};
data[idName] = update.change.modelId;
var model = new Model(data);
tasks.push(model.destroy.bind(model));
break;
break;
}
});
@ -969,7 +969,7 @@ PersistedModel.getChangeModel = function() {
PersistedModel.getSourceId = function(cb) {
var dataSource = this.dataSource;
if(!dataSource) {
if (!dataSource) {
this.once('dataSourceAttached', this.getSourceId.bind(this, cb));
}
assert(
@ -1005,21 +1005,21 @@ PersistedModel.enableChangeTracking = function() {
Model.on('deletedAll', cleanup);
if(runtime.isServer) {
if (runtime.isServer) {
// initial cleanup
cleanup();
// cleanup
setInterval(cleanup, cleanupInterval);
}
function cleanup() {
Model.rectifyAllChanges(function(err) {
if(err) {
console.error(Model.modelName + ' Change Cleanup Error:');
console.error(err);
}
});
}
function cleanup() {
Model.rectifyAllChanges(function(err) {
if (err) {
console.error(Model.modelName + ' Change Cleanup Error:');
console.error(err);
}
});
}
};
@ -1028,12 +1028,14 @@ PersistedModel._defineChangeModel = function() {
assert(BaseChangeModel,
'Change model must be defined before enabling change replication');
return this.Change = BaseChangeModel.extend(this.modelName + '-change',
this.Change = BaseChangeModel.extend(this.modelName + '-change',
{},
{
trackModel: this
}
);
return this.Change;
};
PersistedModel.rectifyAllChanges = function(callback) {
@ -1048,7 +1050,7 @@ PersistedModel.rectifyAllChanges = function(callback) {
*/
PersistedModel.handleChangeError = function(err) {
if(err) {
if (err) {
console.error(Model.modelName + ' Change Tracking Error:');
console.error(err);
}

View File

@ -84,7 +84,7 @@ registry.modelBuilder = new ModelBuilder();
* @header loopback.createModel
*/
registry.createModel = function (name, properties, options) {
registry.createModel = function(name, properties, options) {
if (arguments.length === 1 && typeof name === 'object') {
var config = name;
name = config.name;
@ -98,7 +98,7 @@ registry.createModel = function (name, properties, options) {
options = options || {};
var BaseModel = options.base || options.super;
if(typeof BaseModel === 'string') {
if (typeof BaseModel === 'string') {
var baseName = BaseModel;
BaseModel = this.getModel(BaseModel);
@ -121,7 +121,7 @@ registry.createModel = function (name, properties, options) {
// try to attach
try {
this.autoAttachModel(model);
} catch(e) {}
} catch (e) {}
return model;
};
@ -228,8 +228,8 @@ registry.getModelByType = function(modelType) {
assert(typeof modelType === 'function',
'The model type must be a constructor');
var models = this.modelBuilder.models;
for(var m in models) {
if(models[m].prototype instanceof modelType) {
for (var m in models) {
if (models[m].prototype instanceof modelType) {
return models[m];
}
}
@ -248,10 +248,10 @@ registry.getModelByType = function(modelType) {
* @header loopback.createDataSource(name, options)
*/
registry.createDataSource = function (name, options) {
registry.createDataSource = function(name, options) {
var self = this;
var ds = new DataSource(name, options, self.modelBuilder);
ds.createModel = function (name, properties, settings) {
ds.createModel = function(name, properties, settings) {
settings = settings || {};
var BaseModel = settings.base || settings.super;
if (!BaseModel) {
@ -270,7 +270,7 @@ registry.createDataSource = function (name, options) {
return ModelCtor;
};
if(ds.settings && ds.settings.defaultForType) {
if (ds.settings && ds.settings.defaultForType) {
this.setDefaultDataSourceForType(ds.settings.defaultForType, ds);
}
@ -286,13 +286,13 @@ registry.createDataSource = function (name, options) {
* @header loopback.memory([name])
*/
registry.memory = function (name) {
registry.memory = function(name) {
name = name || 'default';
var memory = (
this._memoryDataSources || (this._memoryDataSources = {})
)[name];
if(!memory) {
if (!memory) {
memory = this._memoryDataSources[name] = this.createDataSource({
connector: 'memory'
});
@ -313,7 +313,7 @@ registry.memory = function (name) {
registry.setDefaultDataSourceForType = function(type, dataSource) {
var defaultDataSources = this.defaultDataSources;
if(!(dataSource instanceof DataSource)) {
if (!(dataSource instanceof DataSource)) {
dataSource = this.createDataSource(dataSource);
}
@ -346,19 +346,21 @@ registry.autoAttach = function() {
var ModelCtor = models[modelName];
// Only auto attach if the model doesn't have an explicit data source
if(ModelCtor && (!(ModelCtor.dataSource instanceof DataSource))) {
if (ModelCtor && (!(ModelCtor.dataSource instanceof DataSource))) {
this.autoAttachModel(ModelCtor);
}
}, this);
};
registry.autoAttachModel = function(ModelCtor) {
if(ModelCtor.autoAttach) {
if (ModelCtor.autoAttach) {
var ds = this.getDefaultDataSourceForType(ModelCtor.autoAttach);
assert(ds instanceof DataSource, 'cannot autoAttach model "'
+ ModelCtor.modelName
+ '". No dataSource found of type ' + ModelCtor.autoAttach);
assert(
ds instanceof DataSource,
'cannot autoAttach model "' + ModelCtor.modelName +
'". No dataSource found of type ' + ModelCtor.autoAttach
);
ModelCtor.attachTo(ds);
}

View File

@ -19,4 +19,3 @@ runtime.isBrowser = typeof window !== 'undefined';
*/
runtime.isServer = !runtime.isBrowser;

View File

@ -57,14 +57,16 @@
"cookie-parser": "~1.3.3",
"errorhandler": "~1.2.0",
"es5-shim": "^4.0.3",
"grunt": "~0.4.5",
"grunt": "^0.4.5",
"grunt-browserify": "~3.0.1",
"grunt-cli": "^0.1.13",
"grunt-contrib-jshint": "~0.10.0",
"grunt-contrib-uglify": "~0.5.1",
"grunt-contrib-watch": "~0.6.1",
"grunt-jscs": "^0.8.1",
"grunt-karma": "~0.9.0",
"grunt-mocha-test": "^0.11.0",
"karma": "~0.12.23",
"karma-browserify": "~0.2.1",
"karma-chrome-launcher": "~0.1.4",
"karma-firefox-launcher": "~0.1.3",
@ -79,8 +81,7 @@
"mocha": "~1.21.4",
"serve-favicon": "~2.1.3",
"strong-task-emitter": "0.0.x",
"supertest": "~0.13.0",
"karma": "~0.12.23"
"supertest": "~0.13.0"
},
"repository": {
"type": "git",