apiserver.js 2.13 KB
"use strict";

const fs = require("fs");
const express = require("express");
const morgan = require("morgan");
const rfs = require("rotating-file-stream");

const logger = require("./logger");
const config = require("./config");
const messageTail = require("./message-tail");
const archive = require("./message-archive");

const app = express();

const logDirectory = process.cwd() + "/logs";
// ensure log directory exists
fs.existsSync(logDirectory) || fs.mkdirSync(logDirectory)

// create a rotating write stream
var accessLogStream = rfs('apiserver_access_log', {
  interval: '1d', // rotate daily
  path: logDirectory
})

// setup the logger
app.use(morgan('combined', {stream: accessLogStream}))

if (!config.api_port) {
    logger.info('Not running API SERVER because of undefined config.api_port');
    return;
}

app.listen(config.api_port, function () {
  logger.info('API SERVER listening on port ' + config.api_port)
});

function isValidApiKey(req, res, next) {
    if (req.params.apikey && (req.params.apikey == config.api_key)) {
        next();
    } else {
        res.end('Invalid apikey');
    }
}

function pageMessageTail(req, res, next) {
    res.json(messageTail.toArray());
}

function pageLogs(req, res, next) {
    const options = {json: true, order:'desc'};
    logger.query(options, function (err, results) {
        if (err) {
            res.end()
        }
        else {
            res.json(results);
        }
    });
}

function pageDupArchiveByRefId(req, res, next) {
    archive.findByRefId(req.params.refid, function(err, rows) {
        if (err) {
            res.end(err);
            return;
        }

        if (!rows) {
            res.end('Empty rows');
            return;
        }

        res.json(rows);
    });
}

function pageTerminate(req, res, next) {
    res.end('Terminating');
    setTimeout(function() {
        process.exit(0);
    }, 5)
}

app.use('/apikey/:apikey', isValidApiKey);
app.get('/apikey/:apikey/message-tail', pageMessageTail);
app.get('/apikey/:apikey/logs', pageLogs);
app.get('/apikey/:apikey/duparchive/by-refid/:refid', pageDupArchiveByRefId);
app.get('/apikey/:apikey/terminate', pageTerminate);