Skip to content

Instantly share code, notes, and snippets.

@jeremybradbury
Last active December 17, 2020 00:05
Show Gist options
  • Save jeremybradbury/4fe707c2449429978b7dba3416d44261 to your computer and use it in GitHub Desktop.
Save jeremybradbury/4fe707c2449429978b7dba3416d44261 to your computer and use it in GitHub Desktop.
A simple helper function for building where phrases for npmjs.com/package/pg (aka node-postgres)
const getWherePhraseFromObj = (where={}) => {
// input {userid: 11, type: 'admin'}
// output {wherePhrase: 'WHERE userid = $1 AND type = $2', values:[11,'admin']}
const keys = Object.keys(where);
const values = Object.values(where);
console.info({keys, values});
let wherePhrase='';
for (let i=0; i < keys.length; i++) {
if (! wherePhrase) {
wherePhrase = 'WHERE '; // first time: i === 0
} else {
wherePhrase += ' AND ' // everything after: i > 0
}
const operator = Array.isArray(values[i]) && 'in' || '=';
wherePhrase += `${keys[i]} ${operator} $${i+1}`;
}
console.info({wherePhrase, values});
return {wherePhrase, values};
};
const _where = getWherePhraseFromObj;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment