Skip to content

Instantly share code, notes, and snippets.

@vslinko
Last active August 29, 2015 14:22
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save vslinko/9c09cce0882707a43f0f to your computer and use it in GitHub Desktop.
Save vslinko/9c09cce0882707a43f0f to your computer and use it in GitHub Desktop.
es6 template literals example
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 ] }
*/
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