Skip to content

Writing Tag Helpers

Christoph Herrmann edited this page Oct 17, 2019 · 3 revisions

Be very careful if extending sql-pg with own Tag Helpers and focus on security to avoid SQL Injections. Tag Helpers have to care about them by escaping keys and use parameterized query for values.

It's possible to define own Tag Helpers by adding them to the sql tag:

const bcrypt = require('bcrypt')

sql.hash = (value, saltRounds = 10) => valuePosition => ({
  text: `$${++valuePosition}`,
  values: [bcrypt.nameSync(value, saltRounds)]
})

const user = { email: 'email' }
const password = 'password'

const result = await sql.query(sql`
  INSERT INTO users (email, password) 
    VALUES (${sql.values(user)}, ${sql.hash(password)})
`)

// text: INSERT INTO users (email, password) VALUES ($1, $2)
// values: 
//   ['email', '$2b$10$ODInlkbnvW90q.EGZ.1Ale3YpOqqdn0QtAotg8q/JzM5HGky6Q2j6']

If possible it's recommended to reuse existing Tag Helpers to define own ones:

const bcrypt = require('bcrypt')

sql.hash = (value, saltRounds = 10) => 
  sql.value(bcrypt.nameSync(value, saltRounds))

const user = { email: 'email' }
const password = 'password'

const result = await sql.query(sql`
  INSERT INTO users (email, password) 
    VALUES (${sql.values(user)}, ${sql.hash(password)})
`)

// text: INSERT INTO users (email, password) VALUES ($1, $2)
// values: 
//   ['email', '$2b$10$ODInlkbnvW90q.EGZ.1Ale3YpOqqdn0QtAotg8q/JzM5HGky6Q2j6']

Clone this wiki locally