Fixed database request handling

This commit is contained in:
Luca Warmenhoven
2024-06-03 14:13:06 +02:00
parent 9f2bb805f0
commit c084443799
2 changed files with 36 additions and 33 deletions

View File

@@ -1,3 +1,6 @@
const databaseQuery = 'SELECT * FROM `Exercise` ORDER BY RAND() LIMIT 1';
/**
*
* @param {Request} request The incoming request
@@ -8,45 +11,33 @@
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 ORDER BY RAND() LIMIT 1';
} else parameters.push(request.uid);
// Acquire database connection
pool.getConnection()
.then(conn => {
conn.query(query, parameters)
conn.query(
databaseQuery)
.then(rows => {
if (rows.length === 0)
{
response
.status(404)
.send(JSON.stringify({error: 'Exercise not found'}));
.send(JSON.stringify({error: 'No exercises found in the database.'}));
}
else
{
// Send back the data in the right format
let converted = rows.map(row => {
return {
exerciseId: row.ExerciseID,
name: row.Name,
muscleGroup: row.MuscleGroup,
shortDescription: row.ShortDescription,
description: row.Description,
imageUrl: row.ImageURL,
videoUrl: row.VideoURL,
path: row.Path,
duration: row.Duration
};
})[0];
response
.status(200)
.send(JSON.stringify(converted));
let row = rows[0];
response.status(200)
.send(JSON.stringify({
exerciseId: row['ExerciseID'],
name: row['Name'],
muscleGroup: row['MuscleGroup'],
shortDescription: row['ShortDescription'],
description: row['Description'],
imageUrl: row['ImageURL'],
videoUrl: row['VideoURL'],
path: row['Path'],
duration: row['Duration']
}))
}
})
.catch(error => {