inital commit

This commit is contained in:
2025-05-28 04:04:41 -07:00
commit c7ee97d6a9
9 changed files with 3263 additions and 0 deletions

70
server.js Normal file
View File

@@ -0,0 +1,70 @@
// server.js
const express = require('express');
const bodyParser = require('body-parser');
const sqlite3 = require('sqlite3').verbose();
const path = require('path');
const http = require('http');
const { Server } = require('socket.io');
const app = express();
const server = http.createServer(app);
const io = new Server(server);
app.use(bodyParser.json());
app.use(express.static(path.join(__dirname, 'public')));
// open (or create) the SQLite database file
const db = new sqlite3.Database('positions.db', err => {
if (err) {
console.error('Could not open DB', err);
process.exit(1);
}
});
// create table if not exists
db.run(
`CREATE TABLE IF NOT EXISTS positions (
square_id TEXT PRIMARY KEY,
fruit TEXT
)`,
(err) => {
if (err) console.error('Could not ensure table', err);
}
);
// get all saved positions
app.get('/api/positions', (req, res) => {
db.all('SELECT square_id, fruit FROM positions', (err, rows) => {
if (err) return res.status(500).json({ error: err.message });
// convert to an object. should look like this: { "1": "Apple", "2": "Banana", … }
const mapping = {};
rows.forEach(r => (mapping[r.square_id] = r.fruit));
res.json(mapping);
});
});
// save (or update) a single squares item
app.post('/api/positions', (req, res) => {
const { squareId, fruit } = req.body;
if (!squareId || typeof fruit !== 'string') {
return res.status(400).json({ error: 'squareId and fruit required' });
}
db.run(
`INSERT INTO positions (square_id, fruit)
VALUES (?, ?)
ON CONFLICT(square_id) DO UPDATE SET fruit=excluded.fruit`,
[squareId, fruit],
function (err) {
if (err) return res.status(500).json({ error: err.message });
// broadcast update via Socket.io
io.emit('update', { squareId, fruit });
res.json({ success: true });
}
);
});
// start server
const PORT = process.env.PORT || 3000;
server.listen(PORT, () => {
console.log(`Listening on http://localhost:${PORT}`);
});