neoxmlinutil.js 2.48 KB
var oracledb = require('oracledb');
var LRU = require('lru-cache');

var config = require("./config.json");
var logger = console;

var oraCon;

var reverseUrlCache = LRU({max: 20, maxAge: 60 * 1000});

function init(options) {
    if (options && options.logger) {
        logger = options.logger;
    }
}

function connectToOracle(callback) {
    oracledb.getConnection(config.oracle, function(err, connection) {
        if (err) {
            logger.warn('Can not connect to oracle db: ' + err);
            process.exit(1);
        }

        oraCon = connection;
        logger.info("Oracle db connected")

        if (callback) {
            callback(null, oraCon);
        }
    })
}

function getTransactionIdFromMessage(message) {
    try {
        var matches = message.match(/ID=(\d+)/);
        return matches[1];
    }
    catch(err) {
        return '0';
    }
}

function getReverseUrlFromDb(msisdn, callback) {
    oraCon.execute(
        "SELECT trim(A.MSISDN) MSISDN, trim(B.REVERSE_URL) REVERSE_URL FROM T_STORE_USER_MSISDN A, T_STORE_USER B WHERE A.STORE_ID = B.STORE_ID AND A.USER_NAME = B.USER_NAME AND B.REVERSE_URL IS NOT NULL AND A.MSISDN = :msisdn",
        [msisdn],
        function(err, result) {
            if (err) {
                logger.warn('Error retrieving reverse url from oracle: ' + err);
                callback(err);
                return;
            }

            var rowCount = result.rows.length;

            var retval = [];
            for (var i = 0; i < rowCount; i++) {
                retval.push(result.rows[i][1]);
            }

            if (retval.length) {
                reverseUrlCache.set(msisdn, retval);
            }

            callback(null, retval);
        }
    );
}

function getReverseUrl(msisdn, callback) {
    var urls = reverseUrlCache.get(msisdn);

    if (!urls) {
        logger.verbose('Cache Miss on reverse url for ' + msisdn, '. Trying to get from DB.');
        getReverseUrlFromDb(msisdn, callback);
    } else {
        //logger.verbose('Got cache hit on reverse url for ' + msisdn);
        callback(null, urls);
    }
}

function getRequestIdFromResponseMessage(message) {
    try {
        var tokens = message.split('.');
        return tokens[4];
    }
    catch(err) {
        return;
    }

}

exports.init = init;
exports.connectToOracle = connectToOracle;
exports.getReverseUrl = getReverseUrl;
exports.getTransactionIdFromMessage = getTransactionIdFromMessage;
exports.getRequestIdFromResponseMessage = getRequestIdFromResponseMessage;