UNPKG

@axway/api-builder-plugin-dc-mbs

Version:

Mobile Backend Services connector

79 lines (72 loc) 2.23 kB
const MBS = require('arrowdb'); const { getTranslatedError } = require('../utils'); function keepAlive(pingInterval, { db, logger }) { // boolean to prevent multiple keepAlive calls happening at the same time let inProgress = false; const interval = setInterval((cb) => { if (inProgress || !db || !db.usersShowMe) { cb && cb(); return; } inProgress = true; logger.trace('Checking MBS session liveliness'); // Get the current logged in user. This will fail if the session is invalid // or if MBS cannot be reached. db.usersShowMe(err => { if (err) { logger.trace(`MBS: ${err.message}`); // After we hit the configured number of tries just throw an error // and kill the server. The callback is only here for test purposes, // converting the interval to async results in an uncaughtPromiseRejection // which isn't handled by runtime yet and doesn't cause a shutdown (unlike // unhandledException). clearInterval(interval); const ex = new Error('MBS session expired or inaccessible'); cb && cb(ex); throw ex; } logger.trace('MBS session OK'); inProgress = false; cb && cb(); }); }, pingInterval); return interval; } function connect(next) { const { key, baseurl, username, password } = this.config; // Default ping interval to 24 hours const pingInterval = this.config.pingInterval || 1000 * 60 * 60 * 24; const details = { pingInterval }; const mbsOpts = {}; if (baseurl) { details.baseurl = baseurl; mbsOpts.apiEntryPoint = baseurl; } this.logger.trace('MBS.connect', details); try { this.db = new MBS(key, mbsOpts); } catch (ex) { // Do not expose `err` via callback (information disclosure) return next(getTranslatedError(this, ex)); } this.db.usersLogin({ login: username, password }, err => { if (err) { // Do not expose `err` via callback (information disclosure) return next(getTranslatedError(this, err, 'Login failed')); } this.logger.trace('successfully logged in'); // Disable keepAlive ping if config.pingInterval is set to -1. if (!this.keepAlive && pingInterval !== -1) { this.keepAlive = keepAlive(pingInterval, this); } next(null); }); } module.exports = { connect };