Last active
December 17, 2020 00:05
-
-
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)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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