Corrected sqlite queries, added function to init or update row

This commit is contained in:
Jacob Windle 2019-01-27 11:44:00 -05:00
parent 16b5d88d05
commit e26986770d

View File

@ -38,7 +38,7 @@ const processRequest = (request, response) => {
logger.info({message: "Requesting: " + req.url}); logger.info({message: "Requesting: " + req.url});
const hostUrl = new url.URL(req.url); const hostUrl = new url.URL(req.url);
addHostToTable(hostUrl.hostname); visitHost(hostUrl.hostname);
// Complicated line of JS to forward request, and pipe it to the // Complicated line of JS to forward request, and pipe it to the
// response object. // response object.
req.pipe(http.request(req.url, (resp) => {resp.pipe(res)})); req.pipe(http.request(req.url, (resp) => {resp.pipe(res)}));
@ -67,7 +67,7 @@ function startServer() {
*/ */
function initializeDatabase() { function initializeDatabase() {
db.serialize(() => { db.serialize(() => {
db.run("create table hosts (hostname TEXT visitcount INTEGER)", (res, err) => { db.run("create table hosts (hostname TEXT, visitcount Int)", (err, row) => {
if (err !== undefined || err !== null) { if (err !== undefined || err !== null) {
console.log("Error creating database, it likely exists already."); console.log("Error creating database, it likely exists already.");
} }
@ -82,17 +82,29 @@ function initializeDatabase() {
*/ */
function updateVisitCount(hostname) { function updateVisitCount(hostname) {
db.serialize(() => { db.serialize(() => {
db.run("update hosts set visitcount = visitcount + 1 where hostname = (?)", [hostname]); db.run("update hosts set visitcount = visitcount + 1 where hostname = ?", [hostname]);
}); });
// db.close(); // db.close();
} }
function addHostToTable(hostname) { function addHostToTable(hostname) {
db.serialize(() => { db.serialize(() => {
db.run("insert into hosts (hostname visitcount) values (? ?)", [hostname, 0]) db.run("insert into hosts (hostname, visitcount) values (?, 0)", [hostname])
}) })
// db.close(); // db.close();
} }
function visitHost(hostname) {
return db.serialize(() => {
db.get("select * from hosts where hostname = ?", [hostname], (err, row) => {
if (row === undefined) {
addHostToTable(hostname);
} else {
updateVisitCount(hostname);
}
})
});
}
initializeDatabase(); initializeDatabase();
startServer(); startServer();