I have a javascript function that needs to return a list of products. It's using postgres to retrieve the list of products. The function is passed a categoryId and an optional typeId. So I need to build a SQL query based on these.
Of course I could do something like this:
async function getProducts(categoryId, typeId = false) {
let products;
if (typeId) {
products = await sql`select * from products where categoryId=${categoryId} and typeId=${typeId}`
}
else {
products = await sql`select * from products where categoryId=${categoryId}`
}
return products;
}
But how could I somehow dynamically "build" the SQL query with the template literals syntax?
Something like this:
async function getProducts(categoryId, typeId = false) {
let query = `select * from products where categoryId=${categoryId}`;
if (typeId) {
query += ` AND typeId=${typeId}`;
}
products = await sql`${query}` // doesn't work, so how could I generate a dynamic query like this?
return products;
}
(Note: this is using @vercel/postgres)
products = await sql`${query}, it returns syntax error at or near "$1"query, do you even need the template literals? I'm not familiar with postgresql or vercel, but what aboutproducts = await sql query;await sql`${query};`. Second, you might try inspecting your query before running it usingsqlTemplateas shown in their tests: github.com/vercel/storage/blob/main/packages/postgres/src/…