76 lines
2.5 KiB
JavaScript
76 lines
2.5 KiB
JavaScript
|
|
|
|
|
|
|
|
|
|
|
|
// Om iets met de database te doen, is het handig om een functie te maken
|
|
// 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) { ... }
|
|
|
|
/**
|
|
*
|
|
* @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));
|
|
}; |