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, "trailing": true,
"newcap": true, "newcap": true,
"nonew": true, "nonew": true,
"sub": true,
"laxcomma": true, "laxcomma": true,
"laxbreak": true "laxbreak": true
} }

View File

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

View File

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

View File

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

View File

@ -8,11 +8,11 @@ module.exports = Connector;
* Module dependencies. * Module dependencies.
*/ */
var EventEmitter = require('events').EventEmitter var EventEmitter = require('events').EventEmitter;
, debug = require('debug')('connector') var debug = require('debug')('connector');
, util = require('util') var util = require('util');
, inherits = util.inherits var inherits = util.inherits;
, assert = require('assert'); var assert = require('assert');
/** /**
* Create a new `Connector` with the given `options`. * Create a new `Connector` with the given `options`.
@ -38,9 +38,9 @@ inherits(Connector, EventEmitter);
* Create an connector instance from a JugglingDB adapter. * Create an connector instance from a JugglingDB adapter.
*/ */
Connector._createJDBAdapter = function (jdbModule) { Connector._createJDBAdapter = function(jdbModule) {
var fauxSchema = {}; var fauxSchema = {};
jdbModule.initialize(fauxSchema, function () { jdbModule.initialize(fauxSchema, function() {
// connected // connected
}); });
}; };
@ -49,6 +49,6 @@ Connector._createJDBAdapter = function (jdbModule) {
* Add default crud operations from a JugglingDB adapter. * 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. * Dependencies.
*/ */
var mailer = require('nodemailer') var mailer = require('nodemailer');
, assert = require('assert') var assert = require('assert');
, debug = require('debug')('loopback:connector:mail') var debug = require('debug')('loopback:connector:mail');
, loopback = require('../loopback'); var loopback = require('../loopback');
/** /**
* Export the MailConnector class. * Export the MailConnector class.
@ -24,19 +24,19 @@ function MailConnector(settings) {
var transports = settings.transports; var transports = settings.transports;
//if transports is not in settings object AND settings.transport exists //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 //then wrap single transport in an array and assign to transports
transports = [settings.transport]; transports = [settings.transport];
} }
if(!transports){ if (!transports) {
transports = []; transports = [];
} }
this.transportsIndex = {}; this.transportsIndex = {};
this.transports = []; this.transports = [];
if(loopback.isServer) { if (loopback.isServer) {
transports.forEach(this.setupTransport.bind(this)); transports.forEach(this.setupTransport.bind(this));
} }
} }
@ -48,7 +48,6 @@ MailConnector.initialize = function(dataSource, callback) {
MailConnector.prototype.DataAccessObject = Mailer; MailConnector.prototype.DataAccessObject = Mailer;
/** /**
* Add a transport to the available transports. See https://github.com/andris9/Nodemailer#setting-up-a-transport-method. * 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 * @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 dataSource = this.dataSource;
var settings = dataSource && dataSource.settings; var settings = dataSource && dataSource.settings;
var connector = dataSource.connector; var connector = dataSource.connector;
@ -140,13 +139,13 @@ Mailer.send = function (options, fn) {
var transport = connector.transportForName(options.transport); var transport = connector.transportForName(options.transport);
if(!transport) { if (!transport) {
transport = connector.defaultTransport(); transport = connector.defaultTransport();
} }
if(debug.enabled || settings && settings.debug) { if (debug.enabled || settings && settings.debug) {
console.log('Sending Mail:'); console.log('Sending Mail:');
if(options.transport) { if (options.transport) {
console.log('\t TRANSPORT:', options.transport); console.log('\t TRANSPORT:', options.transport);
} }
console.log('\t TO:', options.to); console.log('\t TO:', options.to);
@ -156,12 +155,12 @@ Mailer.send = function (options, fn) {
console.log('\t HTML:', options.html); console.log('\t HTML:', options.html);
} }
if(transport) { if (transport) {
assert(transport.sendMail, 'You must supply an Email.settings.transports containing a valid transport'); assert(transport.sendMail, 'You must supply an Email.settings.transports containing a valid transport');
transport.sendMail(options, fn); transport.sendMail(options, fn);
} else { } else {
console.warn('Warning: No email transport specified for sending email.' console.warn('Warning: No email transport specified for sending email.' +
+ ' Setup a transport to send mail messages.'); ' Setup a transport to send mail messages.');
process.nextTick(function() { process.nextTick(function() {
fn(null, options); fn(null, options);
}); });
@ -172,7 +171,7 @@ Mailer.send = function (options, fn) {
* Send an email instance using `modelInstance.send()`. * Send an email instance using `modelInstance.send()`.
*/ */
Mailer.prototype.send = function (fn) { Mailer.prototype.send = function(fn) {
this.constructor.send(this, fn); this.constructor.send(this, fn);
}; };

View File

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

View File

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

View File

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

View File

@ -12,7 +12,7 @@ module.exports = rest;
/** /**
* Expose models over REST. * Expose models over REST.
* *
* For example: * For example:
* ```js * ```js
* app.use(loopback.rest()); * app.use(loopback.rest());
@ -23,13 +23,13 @@ module.exports = rest;
function rest() { function rest() {
var tokenParser = null; var tokenParser = null;
return function (req, res, next) { return function(req, res, next) {
var app = req.app; var app = req.app;
var handler = app.handler('rest'); var handler = app.handler('rest');
if(req.url === '/routes') { if (req.url === '/routes') {
res.send(handler.adapter.allRoutes()); res.send(handler.adapter.allRoutes());
} else if(req.url === '/models') { } else if (req.url === '/models') {
return res.send(app.remotes().toJSON()); return res.send(app.remotes().toJSON());
} else if (app.isAuthEnabled) { } else if (app.isAuthEnabled) {
if (!tokenParser) { 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; var TokenModel = options.model || loopback.AccessToken;
assert(TokenModel, 'loopback.token() middleware requires a AccessToken model'); 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(); if (req.accessToken !== undefined) return next();
TokenModel.findForRequest(req, options, function(err, token) { TokenModel.findForRequest(req, options, function(err, token) {
req.accessToken = token || null; req.accessToken = token || null;
@ -56,4 +56,3 @@ function token(options) {
}); });
}; };
} }

View File

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

View File

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

View File

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

View File

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

View File

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