From 1d3e2337a2cf73bc0a3406240e7d7a48ff2b9669 Mon Sep 17 00:00:00 2001 From: Alexander Zobnin Date: Sun, 31 Jan 2016 13:40:24 +0300 Subject: [PATCH] Call login() once. --- plugins/datasource-zabbix/zabbixAPI.js | 43 ++++++++++++++++++++------ 1 file changed, 33 insertions(+), 10 deletions(-) diff --git a/plugins/datasource-zabbix/zabbixAPI.js b/plugins/datasource-zabbix/zabbixAPI.js index 34b4092..c1ddd9c 100644 --- a/plugins/datasource-zabbix/zabbixAPI.js +++ b/plugins/datasource-zabbix/zabbixAPI.js @@ -26,6 +26,8 @@ function (angular, _) { basicAuth: basicAuth, withCredentials: withCredentials }; + + this.loginPromise = null; } var p = ZabbixAPI.prototype; @@ -45,24 +47,45 @@ function (angular, _) { // Handle errors function(error) { if (error.message === "Session terminated, re-login, please.") { - return ZabbixAPIService.login(self.url, self.username, self.password, self.requestOptions) - .then(function(auth) { - self.auth = auth; - return ZabbixAPIService.request(self.url, method, params, self.requestOptions, self.auth); - }); + throw 'expired'; + return self.login().then(function(auth) { + self.auth = auth; + return ZabbixAPIService.request(self.url, method, params, self.requestOptions, self.auth); + }); } }); } else { // Login first - return ZabbixAPIService.login(this.url, this.username, this.password, this.requestOptions) - .then(function(auth) { - self.auth = auth; - return ZabbixAPIService.request(self.url, method, params, self.requestOptions, self.auth); - }); + //throw 'unauthenticated'; + return self.loginOnce().then(function(auth) { + self.auth = auth; + return ZabbixAPIService.request(self.url, method, params, self.requestOptions, self.auth); + }); } }; + /** + * When API unauthenticated or auth token expired each request produce login() + * call. But auth token is common to all requests. This function wraps login() method + * and call it once. If login() already called just wait for it (return its promise). + * @return login promise + */ + p.loginOnce = function() { + var self = this; + var deferred = $q.defer(); + if (!self.loginPromise) { + self.loginPromise = deferred.promise; + self.login().then(function(auth) { + self.loginPromise = null; + deferred.resolve(auth); + }); + } else { + return self.loginPromise; + } + return deferred.promise; + }; + /** * Get authentication token. */