apiserver.js
2.13 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
"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);