AppReports/index.js
2019-08-29 11:35:53 +02:00

63 lines
1.7 KiB
JavaScript

const http = require('http');
const url = require('url');
const fs = require('fs');
const config = JSON.parse(fs.readFileSync('config.json', 'utf-8'));
const pg = require('postgresupdater')(
config.database.host,
config.database.port,
config.database.user,
config.database.password,
config.database.database
);
const server = http.createServer(async (req, res) => {
await pg.waitForInit();
const queryUrl = url.parse(req.url, true);
let body;
req.on('data', data => {
body += data;
});
req.on('end', async () => {
if (!body && !queryUrl.search) {
fs.readFile('view.html', (err, file) => {
res.writeHead(200, { 'content-type': 'text/html' });
res.end(file);
});
return;
} else if (queryUrl.search == '?json') {
const data = await pg.query(
`SELECT "Timestamp", "Type", "App", "Client", "Message", "Misc", "Stack" FROM "LogView"`
);
const rows = [];
for (let row of data.rows) {
rows.push(Object.values(row));
}
res.writeHead(200, { 'content-type': 'application/json' });
res.end(JSON.stringify(rows));
return;
}
try {
body = JSON.parse(/(?:undefined)*(.*)/.exec(body)[1]);
console.log(body.app, body.client, body.message, body.misc, body.stack);
pg.query(
`INSERT INTO "Log" ("App", "Type", "Client", "Message", "Misc", "Stack") Values($1, $2, $3, $4, $5, $6)`,
[body.app, body.type, body.client, body.message, body.misc, body.stack]
);
} catch (e) {
console.error(e);
if (body) console.error(body);
}
res.writeHead(201);
res.end();
});
});
server.listen(config.port);
console.log('server listening on', config.port);