AppReports/index.js
2019-09-03 08:30:47 +02:00

113 lines
2.9 KiB
JavaScript

// const http = require('http');
// const url = require('url');
const path = require('path');
const fs = require('fs');
const express = require('express');
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 app = express();
app.use(express.json());
app.use(express.static(path.join(__dirname, 'html')));
app.post('/', (req, res, next) => {
console.log('post');
if (req.query.json) {
// json mod requests
} else {
console.log(req.body);
pg.query(
`INSERT INTO "Log" ("App", "Type", "Client", "Message", "Misc", "Stack") Values($1, $2, $3, $4, $5, $6)`,
[
req.body.app,
req.body.type,
req.body.client,
req.body.message,
req.body.misc,
req.body.stack
]
);
}
res.status(201).end();
next();
});
app.get('/', async (req, res, next) => {
console.log('get');
if (req.query.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
.status(200)
.type('application/json')
.end(JSON.stringify(rows));
return;
}
next();
});
app.listen(config.port);
// 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);