*: beginning unittest setup
All checks were successful
Basic Checking / Explore-Gitea-Actions (push) Successful in 7s

Signed-off-by: Vincent Batts <vbatts@hashbangbash.com>
This commit is contained in:
Vincent Batts 2023-09-22 16:39:37 -04:00
parent 0997f578c5
commit 94eac4f89b
Signed by: vbatts
GPG key ID: E30EFAA812C6E5ED
6 changed files with 3819 additions and 212 deletions

210
express/app.js Normal file
View file

@ -0,0 +1,210 @@
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();
// 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(`
CREATE TABLE IF NOT EXISTS button_clicks (
id INTEGER PRIMARY KEY AUTOINCREMENT,
session_id TEXT,
animal_name TEXT,
button_name TEXT,
timestamp DATETIME DEFAULT CURRENT_TIMESTAMP NOT NULL,
time_difference INTEGER -- Add this column for time difference
)
`);
db.run(`
CREATE TABLE IF NOT EXISTS animals (
id INTEGER PRIMARY KEY AUTOINCREMENT,
name TEXT NOT NULL UNIQUE,
timestamp DATETIME DEFAULT CURRENT_TIMESTAMP NOT NULL
)
`);
}
});
var accessLogStream = fs.createWriteStream(
path.join(__dirname, "log", "access.log"),
{ flags: "a" },
);
app.use(bodyParser.json());
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;
for (const animal of animals) {
db.run(`
INSERT INTO animals(name)
SELECT ?
WHERE NOT EXISTS(SELECT 1 FROM animals WHERE name = ?);
`,
[animal, animal],
(err) => {
if (err) {
console.error(`Error inserting animal ${animal}: `, err.message);
} else {
console.log(`Success inserting animal ${animal}`);
}
},
);
}
});
} catch (error) {
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("/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" });
}
});
// 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);
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", async (req, res) => {
try {
const results = {
count: {},
avgTimes: {},
};
const getCount = new Promise((resolve, reject) => {
db.all(
`
SELECT animal_name, button_name, COUNT(*) AS count
FROM button_clicks
GROUP BY button_name, animal_name
`,
(err, rows) => {
if (err) {
reject("getCount: " + err.message);
} else {
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;
});
resolve();
}
},
);
});
const getAvgTime = new Promise((resolve, reject) => {
db.all(
`
SELECT animal_name, button_name, AVG(time_difference) AS time
FROM button_clicks
GROUP BY animal_name, button_name;
`,
(err, rows) => {
if (err) {
reject("getAvgTime: " + err.message);
} else {
rows.forEach((row) => {
if (typeof results.avgTimes[row.animal_name] == "undefined") {
results.avgTimes[row.animal_name] = {};
}
results.avgTimes[row.animal_name][row.button_name] = row.time;
});
resolve();
}
},
);
});
const getTotalAvgTime = new Promise((resolve, reject) => {
db.all(
`
SELECT animal_name, AVG(time_difference) AS time
FROM button_clicks
GROUP BY animal_name;
`,
(err, rows) => {
if (err) {
reject("getTotalAvgTime: " + err.message);
} else {
rows.forEach((row) => {
if (typeof results.avgTimes[row.animal_name] == "undefined") {
results.avgTimes[row.animal_name] = {};
}
results.avgTimes[row.animal_name]["total"] = row.time;
});
resolve();
}
},
);
});
await Promise.all([getCount, getTotalAvgTime, getAvgTime]);
res.json(results);
} catch (error) {
console.error("Error fetching results:", error);
res.status(500).json({ error: "Internal server error" });
}
});
module.exports = app;
// vim:set sts=2 sw=2 et:

29
express/app.test.js Normal file
View file

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

15
express/config.js Normal file
View file

@ -0,0 +1,15 @@
var config = module.exports;
var PRODUCTION = process.env.NODE_ENV === 'production';
const bole = require('bole');
config.express = {
port: process.env.EXPRESS_PORT || 3000,
ip: '127.0.0.1',
};
if (PRODUCTION) {
config.express.ip = '0.0.0.0';
bole.output({ level: 'debug', stream: process.stdout })
} else {
bole.output({ level: 'info', stream: process.stdout })
}

3551
express/package-lock.json generated

File diff suppressed because it is too large Load diff

View file

@ -4,7 +4,7 @@
"description": "", "description": "",
"main": "server.js", "main": "server.js",
"scripts": { "scripts": {
"test": "echo \"Error: no test specified\" && exit 1", "test": "jest",
"start": "node server.js" "start": "node server.js"
}, },
"repository": { "repository": {
@ -15,8 +15,13 @@
"license": "MIT", "license": "MIT",
"dependencies": { "dependencies": {
"body-parser": "^1.20.2", "body-parser": "^1.20.2",
"bole": "^5.0.7",
"express": "^4.18.2", "express": "^4.18.2",
"morgan": "^1.10.0", "morgan": "^1.10.0",
"sqlite3": "^5.1.6" "sqlite3": "^5.1.6"
},
"devDependencies": {
"jest": "^29.7.0",
"supertest": "^6.3.3"
} }
} }

View file

@ -1,212 +1,15 @@
const express = require("express"); const config = require('./config');
const fs = require("fs"); const app = require('./app');
const path = require("path"); const bole = require('bole');
const morgan = require("morgan"); const log = bole('server');
const bodyParser = require("body-parser");
const sqlite3 = require("sqlite3").verbose();
const app = express();
const port = 3000;
// Create an SQLite database and initialize tables app.listen(config.express.port, config.express.ip, function(error) {
const db = new sqlite3.Database("db/results.db", (err) => { if (error) {
if (err) { log.error('Unable to listen for connections', error);
console.error("Error opening SQLite database:", err.message); process.exit(10);
} else {
console.log("Connected to SQLite database");
db.run(`
CREATE TABLE IF NOT EXISTS button_clicks (
id INTEGER PRIMARY KEY AUTOINCREMENT,
session_id TEXT,
animal_name TEXT,
button_name TEXT,
timestamp DATETIME DEFAULT CURRENT_TIMESTAMP NOT NULL,
time_difference INTEGER -- Add this column for time difference
)
`);
db.run(`
CREATE TABLE IF NOT EXISTS animals (
id INTEGER PRIMARY KEY AUTOINCREMENT,
name TEXT NOT NULL UNIQUE,
timestamp DATETIME DEFAULT CURRENT_TIMESTAMP NOT NULL
)
`);
} }
}); log.info('express is listening on http://' +
config.express.ip + ':' + config.express.port)
var accessLogStream = fs.createWriteStream(
path.join(__dirname, "log", "access.log"),
{ flags: "a" },
);
app.use(bodyParser.json());
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;
for (const animal of animals) {
db.run(`
INSERT INTO animals(name)
SELECT ?
WHERE NOT EXISTS(SELECT 1 FROM animals WHERE name = ?);
`,
[animal, animal],
(err) => {
if (err) {
console.error(`Error inserting animal ${animal}: `, err.message);
} else {
console.log(`Success inserting animal ${animal}`);
}
},
);
}
});
} catch (error) {
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("/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" });
}
});
// 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);
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", async (req, res) => {
try {
const results = {
count: {},
avgTimes: {},
};
const getCount = new Promise((resolve, reject) => {
db.all(
`
SELECT animal_name, button_name, COUNT(*) AS count
FROM button_clicks
GROUP BY button_name, animal_name
`,
(err, rows) => {
if (err) {
reject("getCount: " + err.message);
} else {
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;
});
resolve();
}
},
);
});
const getAvgTime = new Promise((resolve, reject) => {
db.all(
`
SELECT animal_name, button_name, AVG(time_difference) AS time
FROM button_clicks
GROUP BY animal_name, button_name;
`,
(err, rows) => {
if (err) {
reject("getAvgTime: " + err.message);
} else {
rows.forEach((row) => {
if (typeof results.avgTimes[row.animal_name] == "undefined") {
results.avgTimes[row.animal_name] = {};
}
results.avgTimes[row.animal_name][row.button_name] = row.time;
});
resolve();
}
},
);
});
const getTotalAvgTime = new Promise((resolve, reject) => {
db.all(
`
SELECT animal_name, AVG(time_difference) AS time
FROM button_clicks
GROUP BY animal_name;
`,
(err, rows) => {
if (err) {
reject("getTotalAvgTime: " + err.message);
} else {
rows.forEach((row) => {
if (typeof results.avgTimes[row.animal_name] == "undefined") {
results.avgTimes[row.animal_name] = {};
}
results.avgTimes[row.animal_name]["total"] = row.time;
});
resolve();
}
},
);
});
await Promise.all([getCount, getTotalAvgTime, getAvgTime]);
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}`);
}); });
// vim:set sts=2 sw=2 et: // vim:set sts=2 sw=2 et: