I’m trying to use optional params with an express api and mariadb, where it will skip over the param if the value is undefined. I know I could easily just loop and clean the data myself, but I feel like there’s a better solution built into the mariadb connector.
This is how you do a simple statement with query params via the mariadb connector:
pool.query(
`SELECT
entry_id
FROM
ENTRY
WHERE
entry_id = ?
AND
entry_type_id IN (?)`,
[entry_id, entry_type_ids]
)
What happens if the user doesn’t want to search by entry_type_id and neglects the statement entirely? It throws an error. So I tried the following statements to get around it:
Failure 1:
pool.query(
`SELECT
entry_id
FROM
ENTRY
WHERE
entry_id = ?
${(entry_type_ids)
? `AND entry_type_id IN (?)`
: "?"
}`,
[entry_id, entry_type_ids]
)
Failure 2:
pool.query(
`SELECT
entry_id
FROM
ENTRY
WHERE
entry_id = ?
${(entry_type_ids)
? `AND entry_type_id IN (?)`
: "/*?*/"
}`,
[entry_id, entry_type_ids]
)
entry_type_ids is just an example and most of the actual query params are being provided by the user, such as tags which can contain special characters.
Is there a better way to achieve what I want, or do I need to clean the params myself?