const http = require('http'); const url = require('url'); const { Client } = require('pg'); const fs = require('fs'); const config = JSON.parse(fs.readFileSync('config.json', 'utf-8')); const pg = new Client(config.database); pg.connect(); pg.query(fs.readFileSync('init.sql', 'utf-8')); const server = http.createServer(async (req, res) => { const queryUrl = url.parse(req.url, true); const query = queryUrl.query; if (!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", "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; } if (!query.client || query.client.length < 5) { res.writeHead(400); res.end(); return; } const client = query.client.substr(4); const app = query.client.substr(0, 4); let body; req.on('data', data => { body += data; }); req.on('end', () => { try { body = JSON.parse(/(?:undefined)*(.*)/.exec(body)[1]); console.log(app, client, body.message, body.misc, body.stack); pg.query( `INSERT INTO "Log" ("App", "Client", "Message", "Misc", "Stack") Values($1, $2, $3, $4, $5)`, [app, client, body.message, body.misc, body.stack] ); } catch (e) { console.error(e); } res.writeHead(201); res.end(); }); }); server.listen(config.port); console.log('server listening on', config.port);