I am using querystring to get a set of search parameters for the enpoint in a RESTful manner:
www.api.com/products?name=apple&colour=red
or
www.api.com/products?name=apple&colour=red&size=large
As you can see, not all parameters are mandatory.
To prevent SQL injection I must use placeholders when placing variables into the query:
connection.query("SELECT * FROM products WHERE name= ? AND colour= ?",
[
req.body.name,
req.body.colour
]
However, if occasionally the size parameter is supplied as well, how do I dynamically create a different query? Writing conditionals for all combinations of search columns seems like a bad solution, and there must be a better way to do this. How do I dynamically create the SQL query based on the supplied search parameters (of course, I would individually check them for validity with express-validator and only allow the correct column names)?
if ( size === 'large') { connection.query... } else { ... }