65 lines
2.3 KiB
JavaScript
65 lines
2.3 KiB
JavaScript
|
|
const databaseQuery = 'SELECT * FROM `Exercise` ORDER BY RAND() LIMIT 1';
|
|
|
|
/**
|
|
*
|
|
* @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)
|
|
{
|
|
|
|
// Acquire database connection
|
|
pool.getConnection()
|
|
.then(conn => {
|
|
conn.query(
|
|
databaseQuery)
|
|
.then(rows => {
|
|
if (rows.length === 0)
|
|
{
|
|
response
|
|
.status(404)
|
|
.send(JSON.stringify({error: 'No exercises found in the database.'}));
|
|
}
|
|
else
|
|
{
|
|
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 => {
|
|
console.log(error);
|
|
response
|
|
.status(500)
|
|
.send(JSON.stringify({error: 'Internal server error (Querying)'}));
|
|
})
|
|
.finally(() => {
|
|
conn.end();
|
|
});
|
|
})
|
|
.catch(error => {
|
|
console.log(error);
|
|
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.post('/', (req, res) => handleIncoming(req, res, app, pool));
|
|
}; |