Reputation: 37
I'm currently learning how to implement filtering, sort, and pagination in a Node.js and MySQL backend.
The current solution I have is:
exports.getAll = (req, res) => {
let params = {
target_muscle: (req.query.target_muscle ? req.query.target_muscle : 'target_muscle')
}
Exercise.getAll(params, (error, result) => {
if(error)
res.status(500).send({
message: error.message
});
else
res.send(result);
})
}
on the controller which calls this method from the model:
Exercise.getAll = (params, result) => {
db.query("SELECT\
exercise_id,\
username AS author,\
title, target_muscle,\
sets, reps, duration,\
likes,\
video_id\
FROM exercises\
JOIN users ON exercises.author_id = users.user_id\
WHERE target_muscle=?", [params.target_muscle], (error, res) => {
if(error) {
result(error, null);
return;
}
result(null, res);
})
}
It works fine when I actually have a query parameter passed on the GET request but gives me an empty result when I don't pass any parameter. I expected it to be unfiltered when I didn't pass anything.
Upvotes: 1
Views: 868
Reputation: 91
You are going to need to validate if you have a param value before adding that condition to the where portion of your SQL query. The way you're doing it, your code is querying like this.
WHERE target_muscle = 'target_muscle'
Upvotes: 1