1

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.

1 Answer 1

1

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'
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.