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 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
async function getNextAnimal() {
try {
const response = await fetch('/getNextAnimal');
const data = await response.json();
document.getElementById('animal-name').textContent = data.animalName;
} catch (error) {
console.error('Error fetching data:', error);
}
try {
const response = await fetch("/getNextAnimal");
const data = await response.json();
document.getElementById("animal-name").textContent = data.animalName;
} catch (error) {
console.error("Error fetching data:", error);
}
}
// Function to set or retrieve the session ID cookie
function getSessionId() {
const sessionId = document.cookie.replace(/(?:(?:^|.*;\s*)sessionId\s*=\s*([^;]*).*$)|^.*$/, '$1');
if (!sessionId) {
const newSessionId = generateSessionId();
document.cookie = `sessionId=${newSessionId}`;
return newSessionId;
}
return sessionId;
const sessionId = document.cookie.replace(
/(?:(?:^|.*;\s*)sessionId\s*=\s*([^;]*).*$)|^.*$/,
"$1",
);
if (!sessionId) {
const newSessionId = generateSessionId();
document.cookie = `sessionId=${newSessionId}`;
return newSessionId;
}
return sessionId;
}
function clearSessionId() {
const newSessionId = generateSessionId();
document.cookie = `sessionId=${newSessionId}`;
setSessionStartTime();
getSessionId();
const newSessionId = generateSessionId();
document.cookie = `sessionId=${newSessionId}`;
setSessionStartTime();
getSessionId();
}
// Function to set session start time
function setSessionStartTime() {
sessionStartTime = new Date();
sessionStartTime = new Date();
}
// Function to calculate and display time difference
function displayTimeDifference() {
if (sessionStartTime && lastButtonClickTime) {
const timeDifference = lastButtonClickTime - sessionStartTime;
console.log(`Time since session start: ${timeDifference} milliseconds`);
// You can display the time difference on the page as needed
}
if (sessionStartTime && lastButtonClickTime) {
const timeDifference = lastButtonClickTime - sessionStartTime;
console.log(`Time since session start: ${timeDifference} milliseconds`);
// You can display the time difference on the page as needed
}
}
// Add click event listeners to the buttons
document.getElementById('isCritterButton').addEventListener('click', () => {
recordButtonClick('is critter', getSessionId());
document.getElementById("isCritterButton").addEventListener("click", () => {
recordButtonClick("is critter", getSessionId());
});
document.getElementById('isNotCritterButton').addEventListener('click', () => {
recordButtonClick('is not critter', getSessionId());
document.getElementById("isNotCritterButton").addEventListener("click", () => {
recordButtonClick("is not critter", getSessionId());
});
document.getElementById('startOverButton').addEventListener('click', () => {
document.getElementById("startOverButton").addEventListener("click", () => {
clearSessionId();
getNextAnimal();
});
// Function to record button clicks on the server
async function recordButtonClick(buttonName, sessionId) {
try {
const currentTime = new Date();
if (lastButtonClickTime) {
const timeDifference = currentTime - lastButtonClickTime;
// Include the time difference in the POST request data
const animal = document.getElementById('animal-name').textContent;
const bodyData = JSON.stringify({ "animal": animal, "button": buttonName, "session": sessionId, "difference": timeDifference, "time": sessionStartTime });
console.log(bodyData);
await fetch('/recordButtonClick', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: bodyData,
});
}
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);
try {
const currentTime = new Date();
if (lastButtonClickTime) {
const timeDifference = currentTime - lastButtonClickTime;
// Include the time difference in the POST request data
const animal = document.getElementById("animal-name").textContent;
const bodyData = JSON.stringify({
animal: animal,
button: buttonName,
session: sessionId,
difference: timeDifference,
time: sessionStartTime,
});
//console.log(bodyData);
await fetch("/recordButtonClick", {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: bodyData,
});
}
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
getNextAnimal();
setSessionStartTime();

View file

@ -1,19 +1,19 @@
const express = require('express');
const fs = require('fs');
const path = require('path');
const morgan = require('morgan');
const bodyParser = require('body-parser');
const sqlite3 = require('sqlite3').verbose();
const express = require("express");
const fs = require("fs");
const path = require("path");
const morgan = require("morgan");
const bodyParser = require("body-parser");
const sqlite3 = require("sqlite3").verbose();
const app = express();
const port = 3000;
// Create an SQLite database and initialize tables
const db = new sqlite3.Database('db/results.db', (err) => {
if (err) {
console.error('Error opening SQLite database:', err.message);
} else {
console.log('Connected to SQLite database');
db.run(`
const db = new sqlite3.Database("db/results.db", (err) => {
if (err) {
console.error("Error opening SQLite database:", err.message);
} else {
console.log("Connected to SQLite database");
db.run(`
CREATE TABLE IF NOT EXISTS button_clicks (
id INTEGER PRIMARY KEY AUTOINCREMENT,
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
)
`);
}
}
});
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(morgan('combined', { stream: accessLogStream }));
app.use(morgan("combined", { stream: accessLogStream }));
var animals;
// check and load animals into redis
try {
fs.readFile("./animals.json", function (err, data) {
if (err) {
throw err;
}
var jsondata = JSON.parse(data);
animals = jsondata.animals;
});
fs.readFile("./animals.json", function (err, data) {
if (err) {
throw err;
}
var jsondata = JSON.parse(data);
animals = jsondata.animals;
});
} catch (error) {
console.error('Error loading animals:', error);
animals = ['Dog', 'Cat', 'Elephant', 'Lion', 'Giraffe'];
console.error("Error loading animals:", error);
animals = ["Dog", "Cat", "Elephant", "Lion", "Giraffe"];
}
// Serve the HTML file
app.get('/', (req, res) => {
res.sendFile(__dirname + '/index.html');
app.get("/", (req, res) => {
res.sendFile(__dirname + "/index.html");
});
app.get('/asset/frontend.js', (req, res) => {
res.sendFile(__dirname + '/asset/frontend.js');
app.get("/asset/frontend.js", (req, res) => {
res.sendFile(__dirname + "/asset/frontend.js");
});
// Route to get a random animal name
app.get('/getNextAnimal', async (req, res) => {
try {
// 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 randomAnimal = animals[randomIndex];
res.json({ animalName: randomAnimal });
} catch (error) {
console.error('Error fetching random animal:', error);
res.status(500).json({ error: 'Internal server error' });
}
app.get("/getNextAnimal", async (req, res) => {
try {
// 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 randomAnimal = animals[randomIndex];
res.json({ animalName: randomAnimal });
} catch (error) {
console.error("Error fetching random animal:", error);
res.status(500).json({ error: "Internal server error" });
}
});
// Route to record button clicks along with session IDs in SQLite
app.post('/recordButtonClick', (req, res) => {
try {
//const { buttonName, sessionId } = req.body;
const result = req.body;
console.error(result);
app.post("/recordButtonClick", (req, res) => {
try {
//const { buttonName, sessionId } = req.body;
const result = req.body;
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) => {
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' });
}
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) => {
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
app.get('/results', (req, res) => {
try {
db.all('SELECT animal_name, button_name, COUNT(*) as count FROM button_clicks GROUP BY button_name, animal_name', (err, rows) => {
if (err) {
console.error('Error fetching results:', err.message);
res.status(500).json({ error: 'Internal server error' });
} else {
const results = { count: {} };
rows.forEach((row) => {
if (typeof results.count[row.animal_name] == 'undefined') {
results.count[row.animal_name] = {}
}
results.count[row.animal_name][row.button_name] = row.count;
});
res.json(results);
app.get("/results", (req, res) => {
try {
db.all(
"SELECT animal_name, button_name, COUNT(*) as count FROM button_clicks GROUP BY button_name, animal_name",
(err, rows) => {
if (err) {
console.error("Error fetching results:", err.message);
res.status(500).json({ error: "Internal server error" });
} else {
const results = { count: {} };
rows.forEach((row) => {
if (typeof results.count[row.animal_name] == "undefined") {
results.count[row.animal_name] = {};
}
});
} catch (error) {
console.error('Error fetching results:', error);
res.status(500).json({ error: 'Internal server error' });
}
results.count[row.animal_name][row.button_name] = row.count;
});
res.json(results);
}
},
);
} catch (error) {
console.error("Error fetching results:", error);
res.status(500).json({ error: "Internal server error" });
}
});
app.listen(port, () => {
console.log(`Server is running on port ${port}`);
console.log(`Server is running on port ${port}`);
});