express: format with prettier

Signed-off-by: Vincent Batts <vbatts@hashbangbash.com>
This commit is contained in:
Vincent Batts 2023-09-15 10:42:37 -04:00
parent 6ddaefdb84
commit 0e4212d114
Signed by: vbatts
GPG key ID: E30EFAA812C6E5ED
2 changed files with 156 additions and 131 deletions

View file

@ -4,94 +4,105 @@ let lastButtonClickTime;
// Function to generate a random session ID // Function to generate a random session ID
function generateSessionId() { function generateSessionId() {
return Math.random().toString(36).substring(2, 15) + Math.random().toString(36).substring(2, 15); return (
Math.random().toString(36).substring(2, 15) +
Math.random().toString(36).substring(2, 15)
);
} }
// Function to fetch a random animal name from the server // Function to fetch a random animal name from the server
async function getNextAnimal() { async function getNextAnimal() {
try { try {
const response = await fetch('/getNextAnimal'); const response = await fetch("/getNextAnimal");
const data = await response.json(); const data = await response.json();
document.getElementById('animal-name').textContent = data.animalName; document.getElementById("animal-name").textContent = data.animalName;
} catch (error) { } catch (error) {
console.error('Error fetching data:', error); console.error("Error fetching data:", error);
} }
} }
// Function to set or retrieve the session ID cookie // Function to set or retrieve the session ID cookie
function getSessionId() { function getSessionId() {
const sessionId = document.cookie.replace(/(?:(?:^|.*;\s*)sessionId\s*=\s*([^;]*).*$)|^.*$/, '$1'); const sessionId = document.cookie.replace(
if (!sessionId) { /(?:(?:^|.*;\s*)sessionId\s*=\s*([^;]*).*$)|^.*$/,
const newSessionId = generateSessionId(); "$1",
document.cookie = `sessionId=${newSessionId}`; );
return newSessionId; if (!sessionId) {
} const newSessionId = generateSessionId();
return sessionId; document.cookie = `sessionId=${newSessionId}`;
return newSessionId;
}
return sessionId;
} }
function clearSessionId() { function clearSessionId() {
const newSessionId = generateSessionId(); const newSessionId = generateSessionId();
document.cookie = `sessionId=${newSessionId}`; document.cookie = `sessionId=${newSessionId}`;
setSessionStartTime(); setSessionStartTime();
getSessionId(); getSessionId();
} }
// Function to set session start time // Function to set session start time
function setSessionStartTime() { function setSessionStartTime() {
sessionStartTime = new Date(); sessionStartTime = new Date();
} }
// Function to calculate and display time difference // Function to calculate and display time difference
function displayTimeDifference() { function displayTimeDifference() {
if (sessionStartTime && lastButtonClickTime) { if (sessionStartTime && lastButtonClickTime) {
const timeDifference = lastButtonClickTime - sessionStartTime; const timeDifference = lastButtonClickTime - sessionStartTime;
console.log(`Time since session start: ${timeDifference} milliseconds`); console.log(`Time since session start: ${timeDifference} milliseconds`);
// You can display the time difference on the page as needed // You can display the time difference on the page as needed
} }
} }
// Add click event listeners to the buttons // Add click event listeners to the buttons
document.getElementById('isCritterButton').addEventListener('click', () => { document.getElementById("isCritterButton").addEventListener("click", () => {
recordButtonClick('is critter', getSessionId()); recordButtonClick("is critter", getSessionId());
}); });
document.getElementById('isNotCritterButton').addEventListener('click', () => { document.getElementById("isNotCritterButton").addEventListener("click", () => {
recordButtonClick('is not critter', getSessionId()); recordButtonClick("is not critter", getSessionId());
}); });
document.getElementById('startOverButton').addEventListener('click', () => { document.getElementById("startOverButton").addEventListener("click", () => {
clearSessionId(); clearSessionId();
getNextAnimal(); getNextAnimal();
}); });
// Function to record button clicks on the server // Function to record button clicks on the server
async function recordButtonClick(buttonName, sessionId) { async function recordButtonClick(buttonName, sessionId) {
try { try {
const currentTime = new Date(); const currentTime = new Date();
if (lastButtonClickTime) { if (lastButtonClickTime) {
const timeDifference = currentTime - lastButtonClickTime; const timeDifference = currentTime - lastButtonClickTime;
// Include the time difference in the POST request data // Include the time difference in the POST request data
const animal = document.getElementById('animal-name').textContent; const animal = document.getElementById("animal-name").textContent;
const bodyData = JSON.stringify({ "animal": animal, "button": buttonName, "session": sessionId, "difference": timeDifference, "time": sessionStartTime }); const bodyData = JSON.stringify({
console.log(bodyData); animal: animal,
await fetch('/recordButtonClick', { button: buttonName,
method: 'POST', session: sessionId,
headers: { difference: timeDifference,
'Content-Type': 'application/json', time: sessionStartTime,
}, });
body: bodyData, //console.log(bodyData);
}); await fetch("/recordButtonClick", {
} method: "POST",
lastButtonClickTime = currentTime; // Record the timestamp of the button click headers: {
displayTimeDifference(); // Calculate and display time difference "Content-Type": "application/json",
// TODO - slight delay before loading next animal, to show the user how long that decision took them },
getNextAnimal(); // Load another random animal body: bodyData,
} catch (error) { });
console.error('Error recording button click:', error);
} }
lastButtonClickTime = currentTime; // Record the timestamp of the button click
displayTimeDifference(); // Calculate and display time difference
// TODO - slight delay before loading next animal, to show the user how long that decision took them
getNextAnimal(); // Load another random animal
} catch (error) {
console.error("Error recording button click:", error);
}
} }
// Initial random animal load and session start time // Initial random animal load and session start time
getNextAnimal(); getNextAnimal();
setSessionStartTime(); setSessionStartTime();

View file

@ -1,19 +1,19 @@
const express = require('express'); const express = require("express");
const fs = require('fs'); const fs = require("fs");
const path = require('path'); const path = require("path");
const morgan = require('morgan'); const morgan = require("morgan");
const bodyParser = require('body-parser'); const bodyParser = require("body-parser");
const sqlite3 = require('sqlite3').verbose(); const sqlite3 = require("sqlite3").verbose();
const app = express(); const app = express();
const port = 3000; const port = 3000;
// Create an SQLite database and initialize tables // Create an SQLite database and initialize tables
const db = new sqlite3.Database('db/results.db', (err) => { const db = new sqlite3.Database("db/results.db", (err) => {
if (err) { if (err) {
console.error('Error opening SQLite database:', err.message); console.error("Error opening SQLite database:", err.message);
} else { } else {
console.log('Connected to SQLite database'); console.log("Connected to SQLite database");
db.run(` db.run(`
CREATE TABLE IF NOT EXISTS button_clicks ( CREATE TABLE IF NOT EXISTS button_clicks (
id INTEGER PRIMARY KEY AUTOINCREMENT, id INTEGER PRIMARY KEY AUTOINCREMENT,
session_id TEXT, session_id TEXT,
@ -23,97 +23,111 @@ const db = new sqlite3.Database('db/results.db', (err) => {
time_difference INTEGER -- Add this column for time difference time_difference INTEGER -- Add this column for time difference
) )
`); `);
} }
}); });
var accessLogStream = fs.createWriteStream(path.join(__dirname, 'log', 'access.log'), { flags: 'a' }) var accessLogStream = fs.createWriteStream(
path.join(__dirname, "log", "access.log"),
{ flags: "a" },
);
app.use(bodyParser.json()); app.use(bodyParser.json());
app.use(morgan('combined', { stream: accessLogStream })); app.use(morgan("combined", { stream: accessLogStream }));
var animals; var animals;
// check and load animals into redis // check and load animals into redis
try { try {
fs.readFile("./animals.json", function (err, data) { fs.readFile("./animals.json", function (err, data) {
if (err) { if (err) {
throw err; throw err;
} }
var jsondata = JSON.parse(data); var jsondata = JSON.parse(data);
animals = jsondata.animals; animals = jsondata.animals;
}); });
} catch (error) { } catch (error) {
console.error('Error loading animals:', error); console.error("Error loading animals:", error);
animals = ['Dog', 'Cat', 'Elephant', 'Lion', 'Giraffe']; animals = ["Dog", "Cat", "Elephant", "Lion", "Giraffe"];
} }
// Serve the HTML file // Serve the HTML file
app.get('/', (req, res) => { app.get("/", (req, res) => {
res.sendFile(__dirname + '/index.html'); res.sendFile(__dirname + "/index.html");
}); });
app.get('/asset/frontend.js', (req, res) => { app.get("/asset/frontend.js", (req, res) => {
res.sendFile(__dirname + '/asset/frontend.js'); res.sendFile(__dirname + "/asset/frontend.js");
}); });
// Route to get a random animal name // Route to get a random animal name
app.get('/getNextAnimal', async (req, res) => { app.get("/getNextAnimal", async (req, res) => {
try { try {
// TODO this is currently random, and should have a bit of reasoning behind the next choice // TODO this is currently random, and should have a bit of reasoning behind the next choice
const randomIndex = Math.floor(Math.random() * animals.length); const randomIndex = Math.floor(Math.random() * animals.length);
const randomAnimal = animals[randomIndex]; const randomAnimal = animals[randomIndex];
res.json({ animalName: randomAnimal }); res.json({ animalName: randomAnimal });
} catch (error) { } catch (error) {
console.error('Error fetching random animal:', error); console.error("Error fetching random animal:", error);
res.status(500).json({ error: 'Internal server error' }); res.status(500).json({ error: "Internal server error" });
} }
}); });
// Route to record button clicks along with session IDs in SQLite // Route to record button clicks along with session IDs in SQLite
app.post('/recordButtonClick', (req, res) => { app.post("/recordButtonClick", (req, res) => {
try { try {
//const { buttonName, sessionId } = req.body; //const { buttonName, sessionId } = req.body;
const result = req.body; const result = req.body;
console.error(result); console.error(result);
db.run('INSERT INTO button_clicks (session_id, animal_name, button_name, timestamp, time_difference) VALUES (?, ?, ?, ?, ?)', [result.session, result.animal, result.button, result.time, result.difference], (err) => { db.run(
if (err) { "INSERT INTO button_clicks (session_id, animal_name, button_name, timestamp, time_difference) VALUES (?, ?, ?, ?, ?)",
console.error('Error recording button click:', err.message); [
res.status(500).json({ error: 'Internal server error' }); result.session,
} else { result.animal,
res.sendStatus(200); result.button,
} result.time,
}); result.difference,
} catch (error) { ],
console.error('Error recording button click:', error); (err) => {
res.status(500).json({ error: 'Internal server error' }); if (err) {
} console.error("Error recording button click:", err.message);
res.status(500).json({ error: "Internal server error" });
} else {
res.sendStatus(200);
}
},
);
} catch (error) {
console.error("Error recording button click:", error);
res.status(500).json({ error: "Internal server error" });
}
}); });
// Route to show the current results from SQLite // Route to show the current results from SQLite
app.get('/results', (req, res) => { app.get("/results", (req, res) => {
try { try {
db.all('SELECT animal_name, button_name, COUNT(*) as count FROM button_clicks GROUP BY button_name, animal_name', (err, rows) => { db.all(
if (err) { "SELECT animal_name, button_name, COUNT(*) as count FROM button_clicks GROUP BY button_name, animal_name",
console.error('Error fetching results:', err.message); (err, rows) => {
res.status(500).json({ error: 'Internal server error' }); if (err) {
} else { console.error("Error fetching results:", err.message);
const results = { count: {} }; res.status(500).json({ error: "Internal server error" });
rows.forEach((row) => { } else {
if (typeof results.count[row.animal_name] == 'undefined') { const results = { count: {} };
results.count[row.animal_name] = {} rows.forEach((row) => {
} if (typeof results.count[row.animal_name] == "undefined") {
results.count[row.animal_name][row.button_name] = row.count; results.count[row.animal_name] = {};
});
res.json(results);
} }
}); results.count[row.animal_name][row.button_name] = row.count;
} catch (error) { });
console.error('Error fetching results:', error); res.json(results);
res.status(500).json({ error: 'Internal server error' }); }
} },
);
} catch (error) {
console.error("Error fetching results:", error);
res.status(500).json({ error: "Internal server error" });
}
}); });
app.listen(port, () => { app.listen(port, () => {
console.log(`Server is running on port ${port}`); console.log(`Server is running on port ${port}`);
}); });