From e26986770d72c2007f3be0a2d99f0d6ec15445b5 Mon Sep 17 00:00:00 2001 From: jaketothepast Date: Sun, 27 Jan 2019 11:44:00 -0500 Subject: [PATCH] Corrected sqlite queries, added function to init or update row --- index.js | 20 ++++++++++++++++---- 1 file changed, 16 insertions(+), 4 deletions(-) diff --git a/index.js b/index.js index 0515893..63ee0c9 100644 --- a/index.js +++ b/index.js @@ -38,7 +38,7 @@ const processRequest = (request, response) => { logger.info({message: "Requesting: " + 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 // response object. req.pipe(http.request(req.url, (resp) => {resp.pipe(res)})); @@ -67,7 +67,7 @@ function startServer() { */ function initializeDatabase() { 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) { console.log("Error creating database, it likely exists already."); } @@ -82,17 +82,29 @@ function initializeDatabase() { */ function updateVisitCount(hostname) { 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(); } function addHostToTable(hostname) { db.serialize(() => { - db.run("insert into hosts (hostname visitcount) values (? ?)", [hostname, 0]) + db.run("insert into hosts (hostname, visitcount) values (?, 0)", [hostname]) }) // 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(); startServer();