Skip to content

Instantly share code, notes, and snippets.

@mrbrianevans
Last active August 14, 2024 08:30
Show Gist options
  • Save mrbrianevans/4be1e92bd0a131477a05e03421b91cfd to your computer and use it in GitHub Desktop.
Save mrbrianevans/4be1e92bd0a131477a05e03421b91cfd to your computer and use it in GitHub Desktop.
Template string literal
const _query = async (client, text, values) => {
const queryText = text.reduce((query, phrase, index)=>`${query} ${phrase}$${index+1}`, '')
const { rows } = await client.query(queryText, values)
return rows
}
const query = (stringArray, ...args) => {
const client = new Client()
const result = await _query(client, stringArray, args)
await client.end()
return result
}
const queryc = (client) => {
return (stringArray, ...args) => _query(client, stringArray, args)
}
// using a re-usable database pool
const pool = new Pool()
const client = pool.client()
const people = await queryc(client)`SELECT * FROM people WHERE dob > ${new Date()}`
await client.end()
await pool.end()
// a single query with zero setup/teardown
const cars = await query`SELECT * FROM cars WHERE price > ${50}`
@mrbrianevans
Copy link
Author

Tagged template literal to easily query a database. One option which creates a Client, executes the query, and then tears down the client. And another option that allows you to pass it a previously created client, allowing one client to be used for multiple queries. Values are parameterized in the query (ie protected from SQL injection).

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment