index.js 2.38 KB
var config = require('./config.json');
var oracledb = require('oracledb');
var express = require('express');
var util = require('util');
var nunjucks = require('nunjucks');

var app = express();
app.set('views', './views');
nunjucks.configure('views', {
    autoescape: true,
    express: app
});

var logger = console;
var oraCon;

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 getTrx(callback) {
    if (!oraCon) {
        callback('DB not ready');
    }

    oraCon.execute(
        "SELECT T_TRANS.*, TO_CHAR(TIME_START, 'YYYY-MM-DD HH24:MI:SS') AS TIME_START_SIMPLE, T_STORE_USER.FULL_NAME FROM T_TRANS LEFT JOIN T_STORE_USER ON T_TRANS.USER_NAME = T_STORE_USER.USER_NAME WHERE TRUNC(TIME_START) = TRUNC(sysdate) AND TRANS_STAT='1200' ORDER BY T_TRANS.TIME_START DESC",
        function(err, result) {
            if (err) {
                callback(err);
                return;
            }

            //logger.info(result.metaData);
            var metadata = result.metaData;
            var metadataCount = metadata.length;

            var retval = [];

            var count = result.rows.length;
            for (var i=1; i <= count; i++) {
                row = result.rows[i-1];

                var data = {};

                for (var metadataIdx = 0; metadataIdx < metadataCount; metadataIdx++) {
                    data[metadata[metadataIdx].name] = row[metadataIdx];
                }
                retval.push(data);
            }

            callback(err, retval);
        }
    );

}

function init() {
    connectToOracle();

    app.listen(config.listen_port, function () {
      console.log('Example app listening on port ' + config.listen_port);
    });
}

function renderTrx(req, res, next) {
    //res.send('Hello World!');
    getTrx(function(err, transactions) {
        if (err) {
            res.end('Something wrong');
            return;
        }

        //res.end(JSON.stringify(result));
        res.render('index.html', {title: "Pending Trx", timestamp: new Date(), transactions: transactions});

    });
}

app.get('/', renderTrx);

init();