You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@ignite.apache.org by an...@apache.org on 2016/02/12 07:42:06 UTC

ignite git commit: IGNITE-843 Refactor serve to es6.

Repository: ignite
Updated Branches:
  refs/heads/ignite-843-rc2 0a7ac460f -> 0e11d4109


IGNITE-843 Refactor serve to es6.


Project: http://git-wip-us.apache.org/repos/asf/ignite/repo
Commit: http://git-wip-us.apache.org/repos/asf/ignite/commit/0e11d410
Tree: http://git-wip-us.apache.org/repos/asf/ignite/tree/0e11d410
Diff: http://git-wip-us.apache.org/repos/asf/ignite/diff/0e11d410

Branch: refs/heads/ignite-843-rc2
Commit: 0e11d4109d72a3cb34ac7ff6b56e220e35c0502b
Parents: 0a7ac46
Author: Andrey <an...@gridgain.com>
Authored: Fri Feb 12 13:42:12 2016 +0700
Committer: Andrey <an...@gridgain.com>
Committed: Fri Feb 12 13:42:12 2016 +0700

----------------------------------------------------------------------
 .../src/main/js/serve/agent.js                  | 544 ++++++++++---------
 .../control-center-web/src/main/js/serve/app.js |   4 +-
 .../src/main/js/serve/configure.js              |  23 +-
 .../src/main/js/serve/mongo.js                  |   3 +-
 .../src/main/js/serve/routes/agent.js           |  52 +-
 5 files changed, 318 insertions(+), 308 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/ignite/blob/0e11d410/modules/control-center-web/src/main/js/serve/agent.js
----------------------------------------------------------------------
diff --git a/modules/control-center-web/src/main/js/serve/agent.js b/modules/control-center-web/src/main/js/serve/agent.js
index f750047..3470dfe 100644
--- a/modules/control-center-web/src/main/js/serve/agent.js
+++ b/modules/control-center-web/src/main/js/serve/agent.js
@@ -15,360 +15,368 @@
  * limitations under the License.
  */
 
-// Fire me up!
 'use strict';
 
+// Fire me up!
+
 module.exports = {
     implements: 'agent',
     inject: ['require(fs)', 'require(ws)', 'require(apache-ignite)', 'mongo']
 };
 
-module.exports.factory = function(fs, ws, apacheIgnite, mongo) {
-    /**
-     * @constructor
-     */
-    function AgentManager() {
-        this._clients = {};
-    }
-
-    /**
-     *
-     */
-    AgentManager.prototype.listen = function(srv) {
-        if (this._server)
-            throw 'Agent server already started!';
-
-        this._server = srv;
+module.exports.factory = function (fs, ws, apacheIgnite, mongo) {
+    class Agent {
+        /**
+         * @param {AgentManager} manager
+         * @param {WebSocket} _wsSrv
+         */
+        constructor(_wsSrv, manager) {
+            const self = this;
 
-        this._wss = new ws.Server({server: this._server});
+            this._manager = manager;
 
-        const self = this;
+            this._wsSrv = _wsSrv;
 
-        this._wss.on('connection', (_ws) => new Client(_ws, self));
-    };
-
-    /**
-     * @param userId
-     * @param {Client} client
-     */
-    AgentManager.prototype._removeClient = function(userId, client) {
-        const connections = this._clients[userId];
-
-        if (connections) {
-            let idx;
-
-            while ((idx = connections.indexOf(client)) !== -1)
-                connections.splice(idx, 1);
+            this._wsSrv.on('close', () => {
+                if (self._user)
+                    self._manager._removeClient(self._user._id, self);
+            });
 
-            if (connections.length === 0)
-                delete this._clients[userId];
-        }
-    };
+            this._wsSrv.on('message', (msgStr) => {
+                const msg = JSON.parse(msgStr);
 
-    /**
-     * @param userId
-     * @param {Client} client
-     */
-    AgentManager.prototype._addClient = function(userId, client) {
-        let existingConnections = this._clients[userId];
+                self['_rmt' + msg.type](msg);
+            });
 
-        if (!existingConnections) {
-            existingConnections = [];
+            this._reqCounter = 0;
 
-            this._clients[userId] = existingConnections;
+            this._cbMap = {};
         }
 
-        existingConnections.push(client);
-    };
+        _runCommand(method, args) {
+            const self = this;
 
-    /**
-     * @param userId
-     * @returns {Client}
-     */
-    AgentManager.prototype.findClient = function(userId) {
-        const clientsList = this._clients[userId];
+            return new Promise((resolve, reject) =>
+                self._invokeRmtMethod(method, args, (error, res) => {
+                    if (error)
+                        return reject(error);
 
-        if (!clientsList || clientsList.length === 0)
-            return null;
+                    resolve(res);
+                })
+            );
+        };
 
-        return clientsList[0];
-    };
+        /**
+         * @param {String} uri
+         * @param {Object} params
+         * @param {Boolean} demo
+         * @param {String} [method]
+         * @param {Object} [headers]
+         * @param {String} [body]
+         * @param {Function} [cb] Callback. Take 3 arguments: {Number} successStatus, {String} error,  {String} response.
+         */
+        executeRest(uri, params, demo, method, headers, body, cb) {
+            if (typeof (params) !== 'object')
+                throw '"params" argument must be an object';
 
-    /**
-     * Creates an instance of server for Ignite
-     *
-     * @constructor
-     * @this {AgentServer}
-     * @param {Client} client Connected client
-     * @param {Boolean} demo Use demo node for request
-     */
-    function AgentServer(client, demo) {
-        this._client = client;
-        this._demo = !!demo;
-    }
+            if (typeof (cb) !== 'function')
+                throw 'callback must be a function';
 
-    /**
-     * Run http request
-     *
-     * @this {AgentServer}
-     * @param {cmd} cmd Command
-     * @param {callback} callback on finish
-     */
-    AgentServer.prototype.runCommand = function(cmd, callback) {
-        const params = { cmd: cmd.name() };
+            if (body && typeof (body) !== 'string')
+                throw 'body must be a string';
 
-        for (var param of cmd._params)
-            params[param.key] = param.value;
+            if (headers && typeof (headers) !== 'object')
+                throw 'headers must be an object';
 
-        let body;
+            if (!method)
+                method = 'GET';
+            else
+                method = method.toUpperCase();
 
-        let headers;
+            if (method !== 'GET' && method !== 'POST')
+                throw 'Unknown HTTP method: ' + method;
 
-        let method = 'GET';
+            const _cb = (error, restResult) => {
+                if (error)
+                    return cb(error);
 
-        if (cmd._isPost()) {
-            body = cmd.postData();
+                const restError = restResult.error;
 
-            method = 'POST';
+                if (restError)
+                    return cb(restError);
 
-            headers = {JSONObject: 'application/json'};
-        }
+                const restCode = restResult.restCode;
 
-        this._client.executeRest('ignite', params, this._demo, method, headers, body, callback);
-    };
+                if (restCode !== 200) {
+                    if (restCode === 401)
+                        return cb.call({code: restCode, message: 'Failed to authenticate on node.'});
 
-    /**
-     * @constructor
-     * @param {AgentManager} manager
-     * @param {WebSocket} ws
-     */
-    function Client(ws, manager) {
-        const self = this;
+                    return cb.call({
+                        code: restCode,
+                        message: restError || 'Failed connect to node and execute REST command.'
+                    });
+                }
 
-        this._manager = manager;
-        this._ws = ws;
+                try {
+                    const nodeResponse = JSON.parse(restResult.response);
+
+                    if (nodeResponse.successStatus === 0)
+                        return cb(null, nodeResponse.response);
+
+                    switch (nodeResponse.successStatus) {
+                        case 1:
+                            return cb({code: 500, message: nodeResponse.error});
+                        case 2:
+                            return cb({code: 401, message: nodeResponse.error});
+                        case 3:
+                            return cb({code: 403, message: nodeResponse.error});
+                        default:
+                            return cb(nodeResponse.error);
+                    }
+                }
+                catch (e) {
+                    return cb(e);
+                }
+            };
 
-        ws.on('close', function() {
-            if (self._user)
-                self._manager._removeClient(self._user._id, self);
-        });
+            this._invokeRmtMethod('executeRest', [uri, params, demo, method, headers, body], _cb);
+        };
 
-        ws.on('message', function(msgStr) {
-            const msg = JSON.parse(msgStr);
+        /**
+         * @param {?String} error
+         */
+        authResult(error) {
+            return this._runCommand('authResult', [error]);
+        }
 
-            self['_rmt' + msg.type](msg);
-        });
+        /**
+         * @param {String} driverPath
+         * @param {String} driverClass
+         * @param {String} url
+         * @param {Object} info
+         * @returns {Promise} Promise on list of tables (see org.apache.ignite.schema.parser.DbTable java class)
+         */
+        metadataSchemas(driverPath, driverClass, url, info) {
+            return this._runCommand('schemas', [driverPath, driverClass, url, info]);
+        }
 
-        this._reqCounter = 0;
+        /**
+         * @param {String} driverPath
+         * @param {String} driverClass
+         * @param {String} url
+         * @param {Object} info
+         * @param {Array} schemas
+         * @param {Boolean} tablesOnly
+         * @returns {Promise} Promise on list of tables (see org.apache.ignite.schema.parser.DbTable java class)
+         */
+        metadataTables(driverPath, driverClass, url, info, schemas, tablesOnly) {
+            return this._runCommand('metadata', [driverPath, driverClass, url, info, schemas, tablesOnly]);
+        }
 
-        this._cbMap = {};
-    }
+        /**
+         * @returns {Promise} Promise on list of jars from driver folder.
+         */
+        availableDrivers() {
+            return this._runCommand('availableDrivers', []);
+        };
 
-    Client.prototype._runCommand = function(method, args) {
-        const self = this;
+        /**
+         * Run http request
+         *
+         * @this {AgentServer}
+         * @param {String} method Command name.
+         * @param {Array} args Command params.
+         * @param {Function} callback on finish
+         */
+        _invokeRmtMethod(method, args, callback) {
+            if (this._wsSrv.readyState !== 1) {
+                if (callback)
+                    callback('org.apache.ignite.agent.AgentException: Connection is closed');
+
+                return;
+            }
 
-        return new Promise(function(resolve, reject) {
-            self._invokeRmtMethod(method, args, function(error, res) {
-                if (error !== null)
-                    return reject(error);
+            const msg = {method, args};
 
-                resolve(res);
-            });
-        });
-    };
+            if (callback) {
+                const reqId = this._reqCounter++;
 
-    /**
-     * @param {String} uri
-     * @param {Object} params
-     * @param {Boolean} demo
-     * @param {String} [method]
-     * @param {Object} [headers]
-     * @param {String} [body]
-     * @param {callback} [callback] Callback. Take 3 arguments: {Number} successStatus, {String} error,  {String} response.
-     */
-    Client.prototype.executeRest = function(uri, params, demo, method, headers, body, callback) {
-        if (typeof (params) !== 'object')
-            throw '"params" argument must be an object';
+                this._cbMap[reqId] = callback;
 
-        if (typeof (callback) !== 'function')
-            throw 'callback must be a function';
+                msg.reqId = reqId;
+            }
 
-        if (body && typeof (body) !== 'string')
-            throw 'body must be a string';
+            this._wsSrv.send(JSON.stringify(msg));
+        };
 
-        if (headers && typeof (headers) !== 'object')
-            throw 'headers must be an object';
+        _rmtAuthMessage(msg) {
+            const self = this;
 
-        if (!method)
-            method = 'GET';
-        else
-            method = method.toUpperCase();
+            fs.stat('public/agent/ignite-web-agent-1.5.0.final.zip', (errFs, stats) => {
+                let relDate = 0;
 
-        if (method !== 'GET' && method !== 'POST')
-            throw 'Unknown HTTP method: ' + method;
+                if (!errFs)
+                    relDate = stats.birthtime.getTime();
 
-        const cb = function(error, restResult) {
-            if (error)
-                return callback(error);
+                if ((msg.relDate || 0) < relDate)
+                    self.authResult('You are using an older version of the agent. Please reload agent archive');
 
-            const restError = restResult.error;
+                mongo.Account.findOne({token: msg.token}, (err, account) => {
+                    // TODO IGNITE-1379 send error to web master.
+                    if (err)
+                        self.authResult('Failed to authorize user');
+                    else if (!account)
+                        self.authResult('Invalid token, user not found');
+                    else {
+                        self.authResult(null);
 
-            if (restError)
-                return callback(restError);
+                        self._user = account;
 
-            const restCode = restResult.restCode;
+                        self._manager._addAgent(account._id, self);
 
-            if (restCode !== 200) {
-                if (restCode === 401)
-                    return callback.call({code: restCode, message: 'Failed to authenticate on node.'});
+                        self._cluster = new apacheIgnite.Ignite(new AgentServer(self));
 
-                return callback.call({
-                    code: restCode,
-                    message: restError || 'Failed connect to node and execute REST command.'
+                        self._demo = new apacheIgnite.Ignite(new AgentServer(self, true));
+                    }
                 });
-            }
+            });
+        };
 
-            try {
-                const nodeResponse = JSON.parse(restResult.response);
+        _rmtCallRes(msg) {
+            const callback = this._cbMap[msg.reqId];
 
-                if (nodeResponse.successStatus === 0)
-                    return callback(null, nodeResponse.response);
+            if (!callback)
+                return;
 
-                switch (nodeResponse.successStatus) {
-                    case 1:
-                        return callback({code: 500, message: nodeResponse.error});
-                    case 2:
-                        return callback({code: 401, message: nodeResponse.error});
-                    case 3:
-                        return callback({code: 403, message: nodeResponse.error});
-                }
+            delete this._cbMap[msg.reqId];
 
-                callback(nodeResponse.error);
-            }
-            catch (e) {
-                callback(e);
-            }
+            callback(msg.error, msg.response);
         };
 
-        this._invokeRmtMethod('executeRest', [uri, params, demo, method, headers, body], cb);
-    };
+        /**
+         * @returns {Ignite}
+         */
+        ignite(demo) {
+            return demo ? this._demo : this._cluster;
+        };
+    }
 
     /**
-     * @param {string} error
+     * Creates an instance of server for Ignite.
      */
-    Client.prototype.authResult = function(error) {
-        return this._runCommand('authResult', [].slice.call(arguments));
-    };
+    class AgentServer {
+        /**
+         * @this {AgentServer}
+         * @param {Agent} agent Connected agent
+         * @param {Boolean} demo Use demo node for request
+         */
+        constructor(agent, demo) {
+            this._agent = agent;
+            this._demo = !!demo;
+        }
 
-    /**
-     * @param {String} driverPath
-     * @param {String} driverClass
-     * @param {String} url
-     * @param {Object} info
-     * @returns {Promise} Promise on list of tables (see org.apache.ignite.schema.parser.DbTable java class)
-     */
-    Client.prototype.metadataSchemas = function(driverPath, driverClass, url, info) {
-        return this._runCommand('schemas', [].slice.call(arguments));
-    };
+        /**
+         * Run http request
+         *
+         * @this {AgentServer}
+         * @param {cmd} cmd Command
+         * @param {callback} callback on finish
+         */
+        runCommand(cmd, callback) {
+            const params = {cmd: cmd.name()};
 
-    /**
-     * @param {String} driverPath
-     * @param {String} driverClass
-     * @param {String} url
-     * @param {Object} info
-     * @param {Array} schemas
-     * @param {Boolean} tablesOnly
-     * @returns {Promise} Promise on list of tables (see org.apache.ignite.schema.parser.DbTable java class)
-     */
-    Client.prototype.metadataTables = function(driverPath, driverClass, url, info, schemas, tablesOnly) {
-        return this._runCommand('metadata', [].slice.call(arguments));
-    };
+            for (const param of cmd._params)
+                params[param.key] = param.value;
 
-    /**
-     * @returns {Promise} Promise on list of jars from driver folder.
-     */
-    Client.prototype.availableDrivers = function() {
-        return this._runCommand('availableDrivers', [].slice.call(arguments));
-    };
+            let body;
 
-    /**
-     * Run http request
-     *
-     * @this {AgentServer}
-     * @param {String} method Command name.
-     * @param {Array} args Command params.
-     * @param {Function} callback on finish
-     */
-    Client.prototype._invokeRmtMethod = function(method, args, callback) {
-        if (this._ws.readyState !== 1) {
-            if (callback)
-                callback('org.apache.ignite.agent.AgentException: Connection is closed');
+            let headers;
 
-            return;
-        }
+            let method = 'GET';
+
+            if (cmd._isPost()) {
+                body = cmd.postData();
 
-        const msg = { method, args };
+                method = 'POST';
 
-        if (callback) {
-            const reqId = this._reqCounter++;
+                headers = {JSONObject: 'application/json'};
+            }
 
-            this._cbMap[reqId] = callback;
+            this._agent.executeRest('ignite', params, this._demo, method, headers, body, callback);
+        };
+    }
 
-            msg.reqId = reqId;
+    class AgentManager {
+        /**
+         * @constructor
+         */
+        constructor() {
+            this._agents = {};
         }
 
-        this._ws.send(JSON.stringify(msg));
-    };
+        /**
+         *
+         */
+        listen(srv) {
+            if (this._server)
+                throw 'Agent server already started!';
 
-    Client.prototype._rmtAuthMessage = function(msg) {
-        const self = this;
+            this._server = srv;
 
-        fs.stat('public/agent/ignite-web-agent-1.5.0.final.zip', function(err, stats) {
-            let relDate = 0;
+            this._wsSrv = new ws.Server({server: this._server});
 
-            if (!err)
-                relDate = stats.birthtime.getTime();
+            const self = this;
+
+            this._wsSrv.on('connection', (_wsSrv) => new Agent(_wsSrv, self));
+        };
 
-            if ((msg.relDate || 0) < relDate)
-                self.authResult('You are using an older version of the agent. Please reload agent archive');
+        /**
+         * @param userId
+         * @param {Agent} client
+         */
+        _removeClient(userId, client) {
+            const agents = this._agents[userId];
 
-            mongo.Account.findOne({token: msg.token}, function(err, account) {
-                if (err)
-                    self.authResult('Failed to authorize user'); // TODO IGNITE-1379 send error to web master.
-                else if (!account)
-                    self.authResult('Invalid token, user not found');
-                else {
-                    self.authResult(null);
+            if (agents) {
+                let idx;
 
-                    self._user = account;
+                while ((idx = agents.indexOf(client)) !== -1)
+                    agents.splice(idx, 1);
 
-                    self._manager._addClient(account._id, self);
+                if (agents.length === 0)
+                    delete this._agents[userId];
+            }
+        };
 
-                    self._cluster = new apacheIgnite.Ignite(new AgentServer(self));
+        /**
+         * @param {ObjectId} userId
+         * @param {Agent} agent
+         */
+        _addAgent(userId, agent) {
+            let agents = this._agents[userId];
 
-                    self._demo = new apacheIgnite.Ignite(new AgentServer(self, true));
-                }
-            });
-        });
-    };
+            if (!agents) {
+                agents = [];
 
-    Client.prototype._rmtCallRes = function(msg) {
-        const callback = this._cbMap[msg.reqId];
+                this._agents[userId] = agents;
+            }
 
-        if (!callback)
-            return;
+            agents.push(agent);
+        };
 
-        delete this._cbMap[msg.reqId];
+        /**
+         * @param {ObjectId} userId
+         * @returns {Agent}
+         */
+        findClient(userId) {
+            const agents = this._agents[userId];
 
-        callback(msg.error, msg.response);
-    };
+            if (!agents || agents.length === 0)
+                return null;
 
-    /**
-     * @returns {Ignite}
-     */
-    Client.prototype.ignite = function(demo) {
-        return demo ? this._demo : this._cluster;
-    };
+            return agents[0];
+        };
+    }
 
     return new AgentManager();
 };

http://git-wip-us.apache.org/repos/asf/ignite/blob/0e11d410/modules/control-center-web/src/main/js/serve/app.js
----------------------------------------------------------------------
diff --git a/modules/control-center-web/src/main/js/serve/app.js b/modules/control-center-web/src/main/js/serve/app.js
index cc93ed9..6d19b44 100644
--- a/modules/control-center-web/src/main/js/serve/app.js
+++ b/modules/control-center-web/src/main/js/serve/app.js
@@ -22,8 +22,8 @@ module.exports = {
     inject: ['require(express)', 'configure', 'routes']
 };
 
-module.exports.factory = function(express, configure, routes) {
-    const app = new express();
+module.exports.factory = function(Express, configure, routes) {
+    const app = new Express();
 
     configure(app);
 

http://git-wip-us.apache.org/repos/asf/ignite/blob/0e11d410/modules/control-center-web/src/main/js/serve/configure.js
----------------------------------------------------------------------
diff --git a/modules/control-center-web/src/main/js/serve/configure.js b/modules/control-center-web/src/main/js/serve/configure.js
index ea8a484..9d8b1d3 100644
--- a/modules/control-center-web/src/main/js/serve/configure.js
+++ b/modules/control-center-web/src/main/js/serve/configure.js
@@ -15,21 +15,20 @@
  * limitations under the License.
  */
 
-// Fire me up!
 'use strict';
 
+// Fire me up!
+
 module.exports = {
     implements: 'configure',
     inject: ['require(morgan)', 'require(cookie-parser)', 'require(body-parser)', 'require(express-force-ssl)',
         'require(express-session)', 'require(connect-mongo)', 'require(passport)', 'settings', 'mongo']
 };
 
-module.exports.factory = function(logger, cookieParser, bodyParser, forceSSL, session, connectMongo, passport, settings, mongo) {
+module.exports.factory = function(logger, cookieParser, bodyParser, forceSSL, session, connectMongo, Passport, settings, mongo) {
     return (app) => {
         app.use(logger('dev', {
-            skip: function(req, res) {
-                return res.statusCode < 400;
-            }
+            skip: (req, res) => res.statusCode < 400
         }));
 
         app.use(cookieParser(settings.sessionSecret));
@@ -37,7 +36,7 @@ module.exports.factory = function(logger, cookieParser, bodyParser, forceSSL, se
         app.use(bodyParser.json({limit: '50mb'}));
         app.use(bodyParser.urlencoded({limit: '50mb', extended: true}));
 
-        const mongoStore = connectMongo(session);
+        const MongoStore = connectMongo(session);
 
         app.use(session({
             secret: settings.sessionSecret,
@@ -47,16 +46,16 @@ module.exports.factory = function(logger, cookieParser, bodyParser, forceSSL, se
                 expires: new Date(Date.now() + settings.cookieTTL),
                 maxAge: settings.cookieTTL
             },
-            store: new mongoStore({mongooseConnection: mongo.connection})
+            store: new MongoStore({mongooseConnection: mongo.connection})
         }));
 
-        app.use(passport.initialize());
-        app.use(passport.session());
+        app.use(Passport.initialize());
+        app.use(Passport.session());
 
-        passport.serializeUser(mongo.Account.serializeUser());
-        passport.deserializeUser(mongo.Account.deserializeUser());
+        Passport.serializeUser(mongo.Account.serializeUser());
+        Passport.deserializeUser(mongo.Account.deserializeUser());
 
-        passport.use(mongo.Account.createStrategy());
+        Passport.use(mongo.Account.createStrategy());
 
         if (settings.SSLOptions) {
             app.set('forceSSLOptions', settings.SSLOptions);

http://git-wip-us.apache.org/repos/asf/ignite/blob/0e11d410/modules/control-center-web/src/main/js/serve/mongo.js
----------------------------------------------------------------------
diff --git a/modules/control-center-web/src/main/js/serve/mongo.js b/modules/control-center-web/src/main/js/serve/mongo.js
index f31267d..3768e77 100644
--- a/modules/control-center-web/src/main/js/serve/mongo.js
+++ b/modules/control-center-web/src/main/js/serve/mongo.js
@@ -15,9 +15,10 @@
  * limitations under the License.
  */
 
-// Fire me up!
 'use strict';
 
+// Fire me up!
+
 module.exports = {
     implements: 'mongo',
     inject: ['require(mongoose-deep-populate)', 'require(passport-local-mongoose)', 'settings', 'ignite_modules/mongo:*']

http://git-wip-us.apache.org/repos/asf/ignite/blob/0e11d410/modules/control-center-web/src/main/js/serve/routes/agent.js
----------------------------------------------------------------------
diff --git a/modules/control-center-web/src/main/js/serve/routes/agent.js b/modules/control-center-web/src/main/js/serve/routes/agent.js
index d98400f..39f9a88 100644
--- a/modules/control-center-web/src/main/js/serve/routes/agent.js
+++ b/modules/control-center-web/src/main/js/serve/routes/agent.js
@@ -15,6 +15,8 @@
  * limitations under the License.
  */
 
+'use strict';
+
 // Fire me up!
 
 module.exports = {
@@ -29,21 +31,21 @@ module.exports = {
  * @param fs
  * @param JSZip
  * @param settings
- * @param {AgentManager} agent
+ * @param {AgentManager} agentMgr
  * @returns {Promise}
  */
-module.exports.factory = function(_, express, apacheIgnite, fs, JSZip, settings, agent) {
+module.exports.factory = function (_, express, apacheIgnite, fs, JSZip, settings, agentMgr) {
     return new Promise((resolve) => {
         const router = express.Router();
 
         const SqlFieldsQuery = apacheIgnite.SqlFieldsQuery, ScanQuery = apacheIgnite.ScanQuery;
 
         const _client = (userId) => {
-            return new Promise(function(resolve, reject) {
-                var client = agent.findClient(userId);
+            return new Promise((resolve, reject) => {
+                const agent = agentMgr.findClient(userId);
 
-                if (client)
-                    return resolve(client);
+                if (agent)
+                    return resolve(agent);
 
                 reject({code: 503, message: 'Connection to Ignite Web Agent is not established'});
             });
@@ -54,7 +56,7 @@ module.exports.factory = function(_, express, apacheIgnite, fs, JSZip, settings,
         };
 
         const _handleException = (res) => {
-            return function(error) {
+            return function (error) {
                 if (_.isObject(error))
                     return res.status(error.code).send(error.message);
 
@@ -63,17 +65,17 @@ module.exports.factory = function(_, express, apacheIgnite, fs, JSZip, settings,
         };
 
         /* Get grid topology. */
-        router.get('/download/zip', function(req, res) {
+        router.get('/download/zip', function (req, res) {
             var agentFld = settings.agent.file;
             var agentZip = agentFld + '.zip';
             var agentPathZip = 'public/agent/' + agentFld + '.zip';
 
-            fs.stat(agentPathZip, function(err, stats) {
+            fs.stat(agentPathZip, function (err, stats) {
                 if (err)
                     return res.download(agentPathZip, agentZip);
 
                 // Read a zip file.
-                fs.readFile(agentPathZip, function(err, data) {
+                fs.readFile(agentPathZip, function (err, data) {
                     if (err)
                         return res.download(agentPathZip, agentZip);
 
@@ -89,7 +91,7 @@ module.exports.factory = function(_, express, apacheIgnite, fs, JSZip, settings,
                     prop.push('#node-uri=http://localhost:8080');
                     prop.push('#driver-folder=./jdbc-drivers');
                     prop.push('');
-                    prop.push('#Note: Do not change this auto generated line');
+                    prop.push("#Note: Don't change this auto generated line");
                     prop.push('rel-date=' + stats.birthtime.getTime());
 
                     zip.file(agentFld + '/default.properties', prop.join('\n'));
@@ -105,7 +107,7 @@ module.exports.factory = function(_, express, apacheIgnite, fs, JSZip, settings,
         });
 
         /* Get grid topology. */
-        router.post('/topology', function(req, res) {
+        router.post('/topology', function (req, res) {
             _client(req.currentUserId())
                 .then((client) => client.ignite(req.body.demo).cluster(req.body.attr, req.body.mtr))
                 .then((clusters) => res.json(clusters))
@@ -113,7 +115,7 @@ module.exports.factory = function(_, express, apacheIgnite, fs, JSZip, settings,
         });
 
         /* Execute query. */
-        router.post('/query', function(req, res) {
+        router.post('/query', function (req, res) {
             _client(req.currentUserId())
                 .then((client) => {
                     // Create sql query.
@@ -133,7 +135,7 @@ module.exports.factory = function(_, express, apacheIgnite, fs, JSZip, settings,
         });
 
         /* Execute query getAll. */
-        router.post('/query/getAll', function(req, res) {
+        router.post('/query/getAll', function (req, res) {
             _client(req.currentUserId())
                 .then((client) => {
                     // Create sql query.
@@ -145,7 +147,7 @@ module.exports.factory = function(_, express, apacheIgnite, fs, JSZip, settings,
                     // Get query cursor.
                     const cursor = client.ignite(req.body.demo).cache(req.body.cacheName).query(qry);
 
-                    return new Promise(function(resolve) {
+                    return new Promise(function (resolve) {
                         cursor.getAll().then(rows => resolve({meta: cursor.fieldsMetadata(), rows}))
                     });
                 })
@@ -154,7 +156,7 @@ module.exports.factory = function(_, express, apacheIgnite, fs, JSZip, settings,
         });
 
         /* Execute query. */
-        router.post('/scan', function(req, res) {
+        router.post('/scan', function (req, res) {
             _client(req.currentUserId())
                 .then((client) => {
                     // Create sql query.
@@ -175,7 +177,7 @@ module.exports.factory = function(_, express, apacheIgnite, fs, JSZip, settings,
         });
 
         /* Get next query page. */
-        router.post('/query/fetch', function(req, res) {
+        router.post('/query/fetch', function (req, res) {
             _client(req.currentUserId())
                 .then((client) => {
                     var cache = client.ignite(req.body.demo).cache(req.body.cacheName);
@@ -191,7 +193,7 @@ module.exports.factory = function(_, express, apacheIgnite, fs, JSZip, settings,
         });
 
         /* Close query cursor by id. */
-        router.post('/query/close', function(req, res) {
+        router.post('/query/close', function (req, res) {
             _client(req.currentUserId())
                 .then((client) => {
                     var cache = client.ignite(req.body.demo).cache(req.body.cacheName);
@@ -203,14 +205,14 @@ module.exports.factory = function(_, express, apacheIgnite, fs, JSZip, settings,
         });
 
         /* Get metadata for cache. */
-        router.post('/cache/metadata', function(req, res) {
+        router.post('/cache/metadata', function (req, res) {
             _client(req.currentUserId())
                 .then((client) => client.ignite(req.body.demo).cache(req.body.cacheName).metadata())
                 .then((caches) => {
                     var types = [];
 
                     for (var meta of caches) {
-                        var cacheTypes = meta.types.map(function(typeName) {
+                        var cacheTypes = meta.types.map(function (typeName) {
                             var fields = meta.fields[typeName];
 
                             var columns = [];
@@ -222,7 +224,7 @@ module.exports.factory = function(_, express, apacheIgnite, fs, JSZip, settings,
                                     type: 'field',
                                     name: fieldName,
                                     clazz: fieldClass,
-                                    system: fieldName === "_KEY" || fieldName === "_VAL",
+                                    system: fieldName == "_KEY" || fieldName == "_VAL",
                                     cacheName: meta.cacheName,
                                     typeName: typeName
                                 });
@@ -283,14 +285,14 @@ module.exports.factory = function(_, express, apacheIgnite, fs, JSZip, settings,
         });
 
         /* Ping client. */
-        router.post('/ping', function(req, res) {
+        router.post('/ping', function (req, res) {
             _client(req.currentUserId())
                 .then(() => res.sendStatus(200))
                 .catch(_handleException(res));
         });
 
         /* Get JDBC drivers list. */
-        router.post('/drivers', function(req, res) {
+        router.post('/drivers', function (req, res) {
             _client(req.currentUserId())
                 .then((client) => client.availableDrivers())
                 .then((arr) => res.json(arr))
@@ -298,7 +300,7 @@ module.exports.factory = function(_, express, apacheIgnite, fs, JSZip, settings,
         });
 
         /** Get database schemas. */
-        router.post('/schemas', function(req, res) {
+        router.post('/schemas', function (req, res) {
             _client(req.currentUserId())
                 .then((client) => {
                     var args = req.body;
@@ -312,7 +314,7 @@ module.exports.factory = function(_, express, apacheIgnite, fs, JSZip, settings,
         });
 
         /** Get database tables. */
-        router.post('/tables', function(req, res) {
+        router.post('/tables', function (req, res) {
             _client(req.currentUserId())
                 .then((client) => {
                     var args = req.body;