Skip to content

Instantly share code, notes, and snippets.

@imedadel
Created August 22, 2020 14:03
Show Gist options
  • Save imedadel/ce32a99af3173d45ce5517cd315b9235 to your computer and use it in GitHub Desktop.
Save imedadel/ce32a99af3173d45ce5517cd315b9235 to your computer and use it in GitHub Desktop.
Tagged templates for writing SQL queries for `pg`
export const sql = (query: TemplateStringsArray, ...params: any[]) => ({
text: query.reduce((acc, curr, idx) => acc + '$' + idx + curr),
values: params,
})
// Example
const name = 'joe'
const email = 'joe[at]gmail.com'
// Before
const data = await pg.query('INSERT INTO users(name, email) VALUES($1, $2);', [
name,
email,
])
// After
const data = await pg.query(
sql`INSERT INTO users(name, email) VALUES(${name}, ${email});`
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment