From e2f1eadddefe39f9f7a3f8be75152ffa0a8dd203 Mon Sep 17 00:00:00 2001 From: wolf4ood Date: Tue, 4 Sep 2018 14:11:24 +0200 Subject: [PATCH] Added token expiration handling --- lib/db/db.js | 52 +++++++++++++++++++++++++++++++++++++++++++++------- 1 file changed, 45 insertions(+), 7 deletions(-) diff --git a/lib/db/db.js b/lib/db/db.js index b9c788e0..bc386335 100644 --- a/lib/db/db.js +++ b/lib/db/db.js @@ -14,6 +14,9 @@ var utils = require('../utils'), EventEmitter = require('events').EventEmitter, fast = require('fast.js'), parseFn = require("parse-function")(); +var extend = require("util")._extend; + + /** @@ -152,6 +155,7 @@ Db.prototype.open = function () { return Promise.resolve(this); } + this.server.logger.debug('opening database connection to ' + this.name); return this.server.send('db-open', { name: this.name, @@ -206,20 +210,52 @@ Db.prototype.close = function () { * @promise {Mixed} The result of the operation. */ Db.prototype.send = function (operation, data) { - return this.open() + return this.retryIfExpired(function(){ + return this.open() .bind(this) .then(function () { data = data || {}; - data.token = data.token || this.token; - data.sessionId = this.sessionId; - data.database = this.name; - data.db = this; - data.transformerFunctions = this.transformerFunctions; + var options = extend({}, data); + options.token = data.token || this.token; + options.sessionId = this.sessionId; + options.database = this.name; + options.db = this; + options.transformerFunctions = this.transformerFunctions; this.server.logger.debug('sending operation ' + operation + ' for database ' + this.name); - return this.server.send(operation, data); + return this.server.send(operation, options); + }) + .bind(this) + .then(function(response){ + if(response.status.token && response.status.token.length >0){ + this.token = response.status.token; + } + return response; }); + }.bind(this)); }; +Db.prototype.retryIfExpired = function(callback) { + return new Promise(function(resolve,reject){ + callback().then(resolve).catch(function(err){ + if(err.message === 'The token provided is expired') { + if(!this.reopening) { + this.sessionId = -1; + this.token = null; + this.reopening = this.open(); + } + this.reopening.then(function(){ + this.reopening = null; + callback().then(resolve).catch(reject); + }).catch(function(e){ + reject(err); + }).bind(this); + }else { + reject(err); + } + }); + }) + .bind(this); +}; /** * Reload the configuration for the database. @@ -265,6 +301,8 @@ Db.prototype.exec = function (query, options) { else if (!options) { options = {}; } + + var data = { query: query, mode: options.mode || 's',