Hey all. I've been looking for this but I can't find an answer.
Is there a way to add statements to my query based on a conditional statement?
For example, my query:
SELECT * FROM users
If the server also receives from the front-end a query string like name="John" I want to add this to my pre-defined query:
SELECT * FROM users WHERE name = 'John'
What I am trying to accomplish here is to have a default query, that will change based on FILTERS and SEARCH made by the user on the front-end.
Thank you in advance.
Hi @lucasmrl this is just an idea, but what about something like this? Not too sure it would scale to more complex stuff though. Maybe check out a query builder?
const sql = `
select *
from users
where (
case when $1 is not null
then name = $1
else true
end
)
`
const value = [request.query.name]
Hi @lucasmrl this is just an idea, but what about something like this? Not too sure it would scale to more complex stuff though. Maybe check out a query builder?
This is eventually a job for query builders or in-query logic (including stored procedures), yep. One popular query builder is Knex.js.
Thank you, guys! I decided to do something simple so I went with @thebearingedge , but I will definitely take a look at Knex.js!
Most helpful comment
Hi @lucasmrl this is just an idea, but what about something like this? Not too sure it would scale to more complex stuff though. Maybe check out a query builder?
Hi @lucasmrl this is just an idea, but what about something like this? Not too sure it would scale to more complex stuff though. Maybe check out a query builder?
https://www.npmjs.com/search?q=postgres%20query%20builder