API now handles file uploads.

This commit is contained in:
Paul Black 2024-07-01 04:29:52 +00:00
parent 488013c808
commit 212cdb158e

View file

@ -3,6 +3,9 @@ const bodyParser = require('body-parser');
const mysql = require("mysql"); const mysql = require("mysql");
const fs = require("fs"); const fs = require("fs");
const yaml = require("js-yaml"); const yaml = require("js-yaml");
const multer = require("multer");
const path = require("path");
const os = require("os");
const app = express(); const app = express();
const port = 3000; const port = 3000;
@ -31,10 +34,29 @@ const authenticate = (req, res, next) => {
} }
}; };
// Set up multer for file uploads
const storage = multer.diskStorage({
destination: (req, file, cb) => {
const gameId = req.params.id;
const homeDir = os.homedir();
const dir = path.join(homeDir, 'game-images', gameId);
if (!fs.existsSync(dir)){
fs.mkdirSync(dir, { recursive: true });
}
cb(null, dir);
},
filename: (req, file, cb) => {
const gameId = req.params.id;
cb(null, gameId); // Save the file with the ID as its name, without extension
}
});
const upload = multer({ storage });
// Serve static files (HTML, CSS, JavaScript) // Serve static files (HTML, CSS, JavaScript)
app.use(express.static("public")); app.use(express.static("public"));
// json data parser // JSON data parser
app.use(bodyParser.json()); app.use(bodyParser.json());
// Define a route to retrieve game data // Define a route to retrieve game data
@ -48,7 +70,6 @@ app.get("/games", (req, res) => {
} }
res.setHeader("Content-Type", "application/json"); res.setHeader("Content-Type", "application/json");
res.json(results); res.json(results);
}); });
}); });
@ -73,11 +94,16 @@ app.post('/add-game', authenticate, (req, res) => {
res.status(500).json({ error: 'Internal Server Error' }); res.status(500).json({ error: 'Internal Server Error' });
} else { } else {
console.log('Data inserted into the games table:', results); console.log('Data inserted into the games table:', results);
res.json({ message: 'Game added successfully!' }); res.json({ message: 'Game added successfully!', gameId: results.insertId });
} }
}); });
}); });
// Endpoint to upload an image for a game
app.post('/upload-image/:id', authenticate, upload.single('gameImage'), (req, res) => {
res.json({ message: 'Image uploaded successfully!' });
});
app.listen(port, () => { app.listen(port, () => {
console.log(`Server is running on port ${port}`); console.log(`Server is running on port ${port}`);
}); });