Skip to content

Instantly share code, notes, and snippets.

@avermeulen
Created November 9, 2018 13:15
Show Gist options
  • Save avermeulen/c8afe866619f074aa4b61c24d5465d19 to your computer and use it in GitHub Desktop.
Save avermeulen/c8afe866619f074aa4b61c24d5465d19 to your computer and use it in GitHub Desktop.
function buildQuery(sql, fields) {
// get all the fields needed in the where clause
let field_names = Object.keys(fields);
// check if a where clause is needed
if (field_names.length > 0) {
sql += ' where '
}
// get all the fields for the where clause with $ placeholder
let query_fields = field_names.map((field, index) => {
return field + ' = $' + (index + 1);
})
// join fields with an and
sql += query_fields.join( " and " );
// get all the parameter values
let params = field_names.map((field_name) => fields[field_name] );
return {
sql,
params
}
}
let queryData = buildQuery('select * from shoes', {
brand_id: 17,
size_id: 12,
// color_id: 47
});
// pool.query(queryData.sql, queryData.params);
console.log(queryData);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment