API now handles file uploads.
This commit is contained in:
parent
488013c808
commit
212cdb158e
1 changed files with 29 additions and 3 deletions
32
server.js
32
server.js
|
@ -3,6 +3,9 @@ const bodyParser = require('body-parser');
|
|||
const mysql = require("mysql");
|
||||
const fs = require("fs");
|
||||
const yaml = require("js-yaml");
|
||||
const multer = require("multer");
|
||||
const path = require("path");
|
||||
const os = require("os");
|
||||
|
||||
const app = express();
|
||||
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)
|
||||
app.use(express.static("public"));
|
||||
|
||||
// json data parser
|
||||
// JSON data parser
|
||||
app.use(bodyParser.json());
|
||||
|
||||
// Define a route to retrieve game data
|
||||
|
@ -48,7 +70,6 @@ app.get("/games", (req, res) => {
|
|||
}
|
||||
|
||||
res.setHeader("Content-Type", "application/json");
|
||||
|
||||
res.json(results);
|
||||
});
|
||||
});
|
||||
|
@ -73,11 +94,16 @@ app.post('/add-game', authenticate, (req, res) => {
|
|||
res.status(500).json({ error: 'Internal Server Error' });
|
||||
} else {
|
||||
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, () => {
|
||||
console.log(`Server is running on port ${port}`);
|
||||
});
|
||||
|
|
Loading…
Reference in a new issue