Created
August 22, 2020 14:03
-
-
Save imedadel/ce32a99af3173d45ce5517cd315b9235 to your computer and use it in GitHub Desktop.
Tagged templates for writing SQL queries for `pg`
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
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