Added NodeJS Server files

This commit is contained in:
Luca Warmenhoven
2024-05-24 10:53:14 +02:00
parent fdfb216617
commit cb53000eb3
7 changed files with 896 additions and 30 deletions

View File

@@ -8,4 +8,69 @@
// die een `app` parameter en een `pool` parameter accepteert.
// Deze moet dan geëxporteerd worden om deze te kunnen gebruiken in `server.js`.
// Dit is een voorbeeld van hoe je dat zou kunnen doen:
// module.exports = function(app, pool) { ... }
// module.exports = function(app, pool) { ... }
/**
*
* @param {Request} request The incoming request
* @param {Response} response The response to send back
* @param {Express} app Express app instance
* @param {Pool} pool MariaDB pool instance
*/
function handleIncoming(request, response, app, pool)
{
if (!request.hasOwnProperty('uid') || typeof request.uid !== 'number')
{
response
.status(400)
.send(JSON.stringify({error: 'Missing valid UID in request'}));
return;
}
// Acquire database connection
pool.getConnection()
.then(conn => {
conn.query('SELECT * FROM Exercise WHERE ExerciseID = ?', [request.uid])
.then(rows => {
if (rows.length === 0)
{
response
.status(404)
.send(JSON.stringify({error: 'Exercise not found'}));
}
else
{
// Send back the data in the right format
let firstRow = rows[0];
response
.status(200)
.send(JSON.stringify({
name: firstRow.Name,
description: firstRow.Description,
muscleGroup: firstRow.MuscleGroup,
imageUrl: firstRow.ImageURL,
videoUrl: firstRow.VideoURL
}));
}
})
.catch(_ => {
response
.status(500)
.send(JSON.stringify({error: 'Internal server error'}));
})
.finally(() => {
conn.end();
});
})
.catch(_ => {
response
.status(500)
.send(JSON.stringify({error: 'Internal server error'}));
});
}
// Export the function that registers the incoming request handlers
module.exports = function(app, pool) {
app.get('/', (req, res) => handleIncoming(req, res, app, pool));
};

View File

@@ -1,7 +1,9 @@
const mariadb = require('mariadb');
const express = require('express');
const app = express();
const bodyParser = require('body-parser');
app.use(bodyParser.json());
const serverPort = 3000;
const databaseCredentials = {
@@ -11,7 +13,7 @@ const databaseCredentials = {
database: 'fitbot',
connectionLimit: 5,
allowUnauthorized: true
}
};
// Create connection pool
const pool = mariadb.createPool(databaseCredentials);
@@ -20,6 +22,6 @@ const pool = mariadb.createPool(databaseCredentials);
require('incoming_request_handlers')(app, pool);
// Start server
app.listen(port, () => {
app.listen(serverPort, () => {
console.log(`Server running on port ${serverPort}`);
})
});