Skip to content

Commit

Permalink
Added token expiration handling
Browse files Browse the repository at this point in the history
  • Loading branch information
wolf4ood committed Sep 4, 2018
1 parent 6b1d0a0 commit e2f1ead
Showing 1 changed file with 45 additions and 7 deletions.
52 changes: 45 additions & 7 deletions lib/db/db.js
Original file line number Diff line number Diff line change
Expand Up @@ -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;




/**
Expand Down Expand Up @@ -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,
Expand Down Expand Up @@ -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.
Expand Down Expand Up @@ -265,6 +301,8 @@ Db.prototype.exec = function (query, options) {
else if (!options) {
options = {};
}


var data = {
query: query,
mode: options.mode || 's',
Expand Down

0 comments on commit e2f1ead

Please sign in to comment.