In June 2023, I found myself in an awkward situation. We used a custom database on a project, and I needed a simple query builder to create complex queries dynamically and ensure security against user input. I discovered that there were no solutions to that problem on the JavaScript platform at all. I built a solution and now open-sourced it.
When you use query builder, you write a raw SQL code.
The benifit is you can insert user input right in string, and your query remain secure against injections. Additionally, a Nano Queries let you compose queries, and extend it, so you may build complex queries simply.
Let’s say you develop a site to search something by its features, for example a movies. Your SQL query may easy takes 100-500 lines. Some part of this query will be a basic, some will be optional depends on provided filters.
With a query builder you may conditionally extend your query like that
if (userInput.rating > 0) { filter.and(sql`rating >= ${userInput.rating}`); }That’s all Query Builder does. It let you avoid to write code like that
const values = []; const getPlaceholder = (value) => { values.push(value); return `$${values.length}`; }; const where = []; if (year) { where.push(`release_year = ${getPlaceholder(year)}`); } if (rating) { where.push(`rating >= ${getPlaceholder(rating)}`); } db.query( `SELECT title FROM movies ${where.length ? 'WHERE ' + where.join(' AND ') : ''} LIMIT 100`, values, );