*: standard js lint

Signed-off-by: Vincent Batts <vbatts@hashbangbash.com>
This commit is contained in:
Vincent Batts 2023-09-28 21:31:05 -04:00
parent 380ec821b1
commit bde4828074
Signed by: vbatts
GPG key ID: E30EFAA812C6E5ED
6 changed files with 202 additions and 201 deletions

226
app.js
View file

@ -1,23 +1,23 @@
const express = require('express'); const express = require('express')
const session = require('express-session'); const session = require('express-session')
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 bole = require('bole'); const bole = require('bole')
const config = require('./config'); const config = require('./config')
const log = bole('app'); const log = bole('app')
const app = express(); const app = express()
// Create an SQLite database and initialize tables // Create an SQLite database and initialize tables
const db = new sqlite3.Database(config.db_path, (err) => { const db = new sqlite3.Database(config.db_path, (err) => {
if (err) { if (err) {
log.error("Error opening SQLite database:", err.message); log.error('Error opening SQLite database:', err.message)
} else { } else {
log.info("Connected to SQLite database", config.db_path); log.info('Connected to SQLite database', config.db_path)
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,
@ -27,133 +27,133 @@ const db = new sqlite3.Database(config.db_path, (err) => {
timestamp DATETIME DEFAULT CURRENT_TIMESTAMP NOT NULL, timestamp DATETIME DEFAULT CURRENT_TIMESTAMP NOT NULL,
time_difference INTEGER -- Add this column for time difference time_difference INTEGER -- Add this column for time difference
) )
`); `)
db.run(` db.run(`
CREATE TABLE IF NOT EXISTS animals ( CREATE TABLE IF NOT EXISTS animals (
id INTEGER PRIMARY KEY AUTOINCREMENT, id INTEGER PRIMARY KEY AUTOINCREMENT,
name TEXT NOT NULL UNIQUE, name TEXT NOT NULL UNIQUE,
timestamp DATETIME DEFAULT CURRENT_TIMESTAMP NOT NULL timestamp DATETIME DEFAULT CURRENT_TIMESTAMP NOT NULL
) )
`); `)
} }
}); })
var accessLogStream = fs.createWriteStream( const accessLogStream = fs.createWriteStream(
path.join(__dirname, "log", "access.log"), path.join(__dirname, 'log', 'access.log'),
{ flags: "a" }, { flags: 'a' }
); )
app.use(bodyParser.json()); app.use(bodyParser.json())
app.use(morgan("combined", { stream: accessLogStream })); app.use(morgan('combined', { stream: accessLogStream }))
app.use(session({ app.use(session({
resave: false, resave: false,
saveUninitialized: false, saveUninitialized: false,
secret: config.session_token, secret: config.session_token
})); }))
var animals; let 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); const jsondata = JSON.parse(data)
animals = jsondata.animals; animals = jsondata.animals
for (const animal of animals) { for (const animal of animals) {
db.run(` db.run(`
INSERT INTO animals(name) INSERT INTO animals(name)
SELECT ? SELECT ?
WHERE NOT EXISTS(SELECT 1 FROM animals WHERE name = ?); WHERE NOT EXISTS(SELECT 1 FROM animals WHERE name = ?);
`, `,
[animal, animal], [animal, animal],
(err) => { (err) => {
if (err) { if (err) {
log.error(`Error inserting animal ${animal}: `, err.message); log.error(`Error inserting animal ${animal}: `, err.message)
} else { } else {
log.info(`Success inserting animal ${animal}`); log.info(`Success inserting animal ${animal}`)
} }
}, }
); )
} }
}); })
} catch (error) { } catch (error) {
log.error("Error loading animals:", error); log.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) => {
if (typeof req.session.cookie.expires == "undefined") { if (typeof req.session.cookie.expires === 'undefined') {
var hour = 3600000; const hour = 3600000
req.session.cookie.expires = new Date(Date.now() + hour); req.session.cookie.expires = new Date(Date.now() + hour)
req.session.cookie.maxAge = hour; req.session.cookie.maxAge = hour
} }
res.sendFile(__dirname + "/index.html"); res.sendFile(path.join(__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(path.join(__dirname, 'asset/frontend.js'))
}); })
app.get("/newSession", (req, res) => { app.get('/newSession', (req, res) => {
// XXX // XXX
log.info(req.session); log.info(req.session)
req.session.regenerate(); req.session.regenerate()
log.info(req.session); log.info(req.session)
}); })
// 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) {
log.error("Error fetching random animal:", error); log.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
log.error(result); log.error(result)
db.run( db.run(
"INSERT INTO button_clicks (session_id, animal_name, button_name, timestamp, time_difference) VALUES (?, ?, ?, ?, ?)", 'INSERT INTO button_clicks (session_id, animal_name, button_name, timestamp, time_difference) VALUES (?, ?, ?, ?, ?)',
[ [
result.session, result.session,
result.animal, result.animal,
result.button, result.button,
result.time, result.time,
result.difference, result.difference
], ],
(err) => { (err) => {
if (err) { if (err) {
log.error("Error recording button click:", err.message); log.error('Error recording button click:', err.message)
res.status(500).json({ error: "Internal server error" }); res.status(500).json({ error: 'Internal server error' })
} else { } else {
res.sendStatus(200); res.sendStatus(200)
} }
}, }
); )
} catch (error) { } catch (error) {
log.error("Error recording button click:", error); log.error('Error recording button click:', error)
res.status(500).json({ error: "Internal server 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", async (req, res) => { app.get('/results', async (req, res) => {
try { try {
const results = { const results = {
count: {}, count: {},
avgTimes: {}, avgTimes: {}
}; }
const getCount = new Promise((resolve, reject) => { const getCount = new Promise((resolve, reject) => {
db.all( db.all(
` `
@ -163,19 +163,19 @@ app.get("/results", async (req, res) => {
`, `,
(err, rows) => { (err, rows) => {
if (err) { if (err) {
reject("getCount: " + err.message); reject(new Error('getCount: ' + err.message))
} else { } else {
rows.forEach((row) => { rows.forEach((row) => {
if (typeof results.count[row.animal_name] == "undefined") { if (typeof results.count[row.animal_name] === 'undefined') {
results.count[row.animal_name] = {}; results.count[row.animal_name] = {}
} }
results.count[row.animal_name][row.button_name] = row.count; results.count[row.animal_name][row.button_name] = row.count
}); })
resolve(); resolve()
} }
}, }
); )
}); })
const getAvgTime = new Promise((resolve, reject) => { const getAvgTime = new Promise((resolve, reject) => {
db.all( db.all(
` `
@ -185,19 +185,19 @@ app.get("/results", async (req, res) => {
`, `,
(err, rows) => { (err, rows) => {
if (err) { if (err) {
reject("getAvgTime: " + err.message); reject(new Error('getAvgTime: ' + err.message))
} else { } else {
rows.forEach((row) => { rows.forEach((row) => {
if (typeof results.avgTimes[row.animal_name] == "undefined") { if (typeof results.avgTimes[row.animal_name] === 'undefined') {
results.avgTimes[row.animal_name] = {}; results.avgTimes[row.animal_name] = {}
} }
results.avgTimes[row.animal_name][row.button_name] = row.time; results.avgTimes[row.animal_name][row.button_name] = row.time
}); })
resolve(); resolve()
} }
}, }
); )
}); })
const getTotalAvgTime = new Promise((resolve, reject) => { const getTotalAvgTime = new Promise((resolve, reject) => {
db.all( db.all(
` `
@ -207,27 +207,27 @@ app.get("/results", async (req, res) => {
`, `,
(err, rows) => { (err, rows) => {
if (err) { if (err) {
reject("getTotalAvgTime: " + err.message); reject(new Error('getTotalAvgTime: ' + err.message))
} else { } else {
rows.forEach((row) => { rows.forEach((row) => {
if (typeof results.avgTimes[row.animal_name] == "undefined") { if (typeof results.avgTimes[row.animal_name] === 'undefined') {
results.avgTimes[row.animal_name] = {}; results.avgTimes[row.animal_name] = {}
} }
results.avgTimes[row.animal_name]["total"] = row.time; results.avgTimes[row.animal_name].total = row.time
}); })
resolve(); resolve()
} }
}, }
); )
}); })
await Promise.all([getCount, getTotalAvgTime, getAvgTime]); await Promise.all([getCount, getTotalAvgTime, getAvgTime])
res.json(results); res.json(results)
} catch (error) { } catch (error) {
log.error("Error fetching results:", error); log.error('Error fetching results:', error)
res.status(500).json({ error: "Internal server error" }); res.status(500).json({ error: 'Internal server error' })
} }
}); })
module.exports = app; module.exports = app
// vim:set sts=2 sw=2 et: // vim:set sts=2 sw=2 et:

View file

@ -1,29 +1,29 @@
// app.test.js // app.test.js
const request = require('supertest'); const request = require('supertest')
const app = require('./app'); const app = require('./app')
describe('GET /', () => { describe('GET /', () => {
it('should respond with 200 status', async () => { it('should respond with 200 status', async () => {
const response = await request(app).get('/'); const response = await request(app).get('/')
expect(response.statusCode).toBe(200); expect(response.statusCode).toBe(200)
//expect(response.body.message).toBe('Hello, World!'); // expect(response.body.message).toBe('Hello, World!');
}); })
}); })
describe('GET /asset/frontend.js', () => { describe('GET /asset/frontend.js', () => {
it('should respond with 200 status', async () => { it('should respond with 200 status', async () => {
const response = await request(app).get('/asset/frontend.js'); const response = await request(app).get('/asset/frontend.js')
expect(response.statusCode).toBe(200); expect(response.statusCode).toBe(200)
//expect(response.body.message).toBe('Hello, World!'); // expect(response.body.message).toBe('Hello, World!');
}); })
}); })
describe('GET /getNextAnimal', () => { describe('GET /getNextAnimal', () => {
it('should respond with 200 status', async () => { it('should respond with 200 status', async () => {
const response = await request(app).get('/getNextAnimal'); const response = await request(app).get('/getNextAnimal')
expect(response.statusCode).toBe(200); expect(response.statusCode).toBe(200)
//expect(response.body.message).toBe('Hello, World!'); // expect(response.body.message).toBe('Hello, World!');
}); })
}); })
// vim:set sts=2 sw=2 et: // vim:set sts=2 sw=2 et:

View file

@ -1,103 +1,103 @@
// Initialize session variables // Initialize session variables
let sessionStartTime; let sessionStartTime
let lastButtonClickTime; let lastButtonClickTime
// 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( const sessionId = document.cookie.replace(
/(?:(?:^|.*;\s*)sessionId\s*=\s*([^;]*).*$)|^.*$/, /(?:(?:^|.*;\s*)sessionId\s*=\s*([^;]*).*$)|^.*$/,
"$1", '$1'
); )
if (!sessionId) { if (!sessionId) {
return newSession(); return newSession()
} }
return sessionId; return sessionId
} }
async function newSession() { async function newSession () {
setSessionStartTime(); setSessionStartTime()
try { try {
const response = await fetch("/newSession"); const response = await fetch('/newSession')
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)
} }
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
} }
} }
// 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({ const bodyData = JSON.stringify({
animal: animal, animal,
button: buttonName, button: buttonName,
session: sessionId, session: sessionId,
difference: timeDifference, difference: timeDifference,
time: sessionStartTime, time: sessionStartTime
}); })
//console.log(bodyData); // console.log(bodyData);
await fetch("/recordButtonClick", { await fetch('/recordButtonClick', {
method: "POST", method: 'POST',
headers: { headers: {
"Content-Type": "application/json", 'Content-Type': 'application/json'
}, },
body: bodyData, body: bodyData
}); })
} }
lastButtonClickTime = currentTime; // Record the timestamp of the button click lastButtonClickTime = currentTime // Record the timestamp of the button click
displayTimeDifference(); // Calculate and display time difference displayTimeDifference() // Calculate and display time difference
// TODO - slight delay before loading next animal, to show the user how long that decision took them // TODO - slight delay before loading next animal, to show the user how long that decision took them
getNextAnimal(); // Load another random animal getNextAnimal() // Load another random animal
} catch (error) { } catch (error) {
console.error("Error recording button click:", error); console.error('Error recording button click:', error)
} }
} }
// 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', () => {
newSession(); newSession()
getNextAnimal(); getNextAnimal()
}); })
// 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 config = module.exports; const config = module.exports
const PRODUCTION = process.env.NODE_ENV === 'production'; const PRODUCTION = process.env.NODE_ENV === 'production'
const bole = require('bole'); const bole = require('bole')
config.express = { config.express = {
port: process.env.EXPRESS_PORT || 3000, port: process.env.EXPRESS_PORT || 3000,
ip: '127.0.0.1', ip: '127.0.0.1'
}; }
if (PRODUCTION) { if (PRODUCTION) {
config.express.ip = '0.0.0.0'; config.express.ip = '0.0.0.0'
config.db_path = 'db/results.db'; config.db_path = 'db/results.db'
config.session_token = process.env.SESSION_TOKEN; config.session_token = process.env.SESSION_TOKEN
bole.output({ level: 'info', stream: process.stdout }) bole.output({ level: 'info', stream: process.stdout })
} else { } else {
config.db_path = ':memory:'; config.db_path = ':memory:'
config.session_token = 'cat bag'; config.session_token = 'cat bag'
bole.output({ level: 'debug', stream: process.stdout }) bole.output({ level: 'debug', stream: process.stdout })
} }

View file

@ -5,6 +5,7 @@
"main": "server.js", "main": "server.js",
"scripts": { "scripts": {
"test": "./node_modules/.bin/jest", "test": "./node_modules/.bin/jest",
"lint": "./node_modules/.bin/standard --ignore *.test.js .",
"start": "node server.js", "start": "node server.js",
"act": "act -W ./.gitea/workflows/" "act": "act -W ./.gitea/workflows/"
}, },

View file

@ -1,15 +1,15 @@
const bole = require('bole'); const bole = require('bole')
const config = require('./config'); const config = require('./config')
const app = require('./app'); const app = require('./app')
const log = bole('server'); const log = bole('server')
app.listen(config.express.port, config.express.ip, function(error) { app.listen(config.express.port, config.express.ip, function (error) {
if (error) { if (error) {
log.error('Unable to listen for connections', error); log.error('Unable to listen for connections', error)
process.exit(10); process.exit(10)
} }
log.info('express is listening on http://' + log.info('express is listening on http://' +
config.express.ip + ':' + config.express.port) config.express.ip + ':' + config.express.port)
}); })
// vim:set sts=2 sw=2 et: // vim:set sts=2 sw=2 et: