Last active
August 29, 2015 14:22
-
-
Save vslinko/9c09cce0882707a43f0f to your computer and use it in GitHub Desktop.
es6 template literals example
This file contains 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
import pgquery from 'pgquery' | |
const role = 'admin' | |
const likes = 5 | |
console.log(pgquery` | |
SELECT * FROM users WHERE role = ${role} AND likes > ${likes} | |
`) | |
/* | |
{ queryString: '\n SELECT * FROM users WHERE role = $1::varchar AND likes > $2::int\n', | |
params: [ 'admin', 5 ] } | |
*/ |
This file contains 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
export default function pgquery(parts, ...params) { | |
const queryString = parts.reduce((acc, part, index) => { | |
const param = params[index - 1] | |
let type | |
if (typeof param === 'string') { | |
type = 'varchar' | |
} else if (typeof param === 'number') { | |
type = 'int' | |
} else { | |
throw new Error('Unsupported param') | |
} | |
return acc + `\$${index}::${type}` + part | |
}) | |
return { | |
queryString, | |
params, | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment