2023-09-15 00:38:32 +00:00
|
|
|
const express = require('express');
|
2023-09-15 01:35:41 +00:00
|
|
|
const fs = require('fs');
|
2023-09-15 00:38:32 +00:00
|
|
|
const bodyParser = require('body-parser');
|
2023-09-15 01:35:41 +00:00
|
|
|
const Redis = require('ioredis');
|
2023-09-15 00:38:32 +00:00
|
|
|
const app = express();
|
|
|
|
const port = 3000;
|
|
|
|
|
2023-09-15 01:35:41 +00:00
|
|
|
// Create a Redis Client
|
|
|
|
const redis = new Redis();
|
2023-09-15 00:38:32 +00:00
|
|
|
|
|
|
|
app.use(bodyParser.json());
|
|
|
|
|
2023-09-15 01:35:41 +00:00
|
|
|
var animals;
|
|
|
|
// check and load animals into redis
|
|
|
|
fs.readFile("./animals.json", function (err, data) {
|
|
|
|
if (err) {
|
|
|
|
throw err;
|
|
|
|
}
|
|
|
|
var jsondata = JSON.parse(data);
|
|
|
|
animals = jsondata.animals;
|
|
|
|
//await redis.set('animals', jsondata.animals, 'EX', 3000);
|
|
|
|
});
|
|
|
|
|
|
|
|
|
2023-09-15 00:38:32 +00:00
|
|
|
// Serve the HTML file
|
|
|
|
app.get('/', (req, res) => {
|
|
|
|
res.sendFile(__dirname + '/index.html');
|
|
|
|
});
|
|
|
|
|
|
|
|
// Route to get a random animal name
|
|
|
|
app.get('/getRandomAnimal', (req, res) => {
|
|
|
|
const randomAnimal = animals[Math.floor(Math.random() * animals.length)];
|
|
|
|
res.json({ animalName: randomAnimal });
|
|
|
|
});
|
|
|
|
|
|
|
|
// Route to record button clicks
|
|
|
|
app.post('/recordButtonClick', (req, res) => {
|
2023-09-15 01:35:41 +00:00
|
|
|
try {
|
|
|
|
const { buttonName, sessionId } = req.body;
|
|
|
|
|
|
|
|
// Use a Redis hash to store button clicks associated with session IDs
|
|
|
|
await redis.hincrby('buttonClicks', `${sessionId}:${buttonName}`, 1);
|
|
|
|
|
|
|
|
res.sendStatus(200);
|
|
|
|
|
2023-09-15 00:38:32 +00:00
|
|
|
if (buttonClicks.hasOwnProperty(buttonName)) {
|
|
|
|
buttonClicks[buttonName]++;
|
|
|
|
res.sendStatus(200);
|
|
|
|
} else {
|
|
|
|
res.status(400).json({ error: 'Invalid button name' });
|
|
|
|
}
|
2023-09-15 01:35:41 +00:00
|
|
|
} catch (error) {
|
|
|
|
console.error('Error recording button click:', error);
|
|
|
|
res.status(500).json({ error: 'Internal server error' });
|
|
|
|
}
|
|
|
|
});
|
|
|
|
|
|
|
|
|
|
|
|
// Route to show the current results
|
|
|
|
app.get('/results', async (req, res) => {
|
|
|
|
try {
|
|
|
|
// Get the current random animal from Redis
|
|
|
|
const randomAnimal = await redis.get('randomAnimal');
|
|
|
|
|
|
|
|
// Get the button click counts from the Redis hash
|
|
|
|
const buttonClicks = await redis.hgetall('buttonClicks');
|
|
|
|
|
|
|
|
res.json({ randomAnimal, buttonClicks });
|
|
|
|
} catch (error) {
|
|
|
|
console.error('Error fetching results:', error);
|
|
|
|
res.status(500).json({ error: 'Internal server error' });
|
|
|
|
}
|
2023-09-15 00:38:32 +00:00
|
|
|
});
|
|
|
|
|
|
|
|
app.listen(port, () => {
|
|
|
|
console.log(`Server is running on port ${port}`);
|
|
|
|
});
|
|
|
|
|