Files
J1B4-Fitbot/code/web/incoming_request_handlers.js
Luca Warmenhoven 29944bce57 Crack butt
2024-05-28 12:07:07 +02:00

66 lines
2.2 KiB
JavaScript

/**
*
* @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)
{
let query = 'SELECT * FROM Exercise WHERE ExerciseID = ?';
let parameters = [];
if (!request.hasOwnProperty('uid') || typeof request.uid !== 'number')
{
query = 'SELECT * FROM Exercise';
} else parameters.push(request.uid);
// Acquire database connection
pool.getConnection()
.then(conn => {
conn.query(query, parameters)
.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 (Querying)'}));
})
.finally(() => {
conn.end();
});
})
.catch(_ => {
response
.status(500)
.send(JSON.stringify({error: 'Internal server error (Connection)'}));
});
}
// Export the function that registers the incoming request handlers
module.exports = function(app, pool) {
app.get('/', (req, res) => handleIncoming(req, res, app, pool));
};