Transactions with postgres

So, I have my authentication set up in a way that each user 'lives' in two separate tables, Users (email and password) and Customers (more personal data)

This is my registration controller:
authRouter.post('/register', async (req, res) => {
  console.log(req.body)
  const { email, password, password2, role } = req.body
  // [TODO] validate email
  if (password !== password2) {
    return res.status(401).send('BAD REQUEST')
  }

  console.log('inserting')
  const collection = collections[role]
  console.log('got collection', !!collection)
  const [user] = await db.insert(Users).values({ email, password }).returning()
  const [person] = await db.insert(Customers).values({ email }).returning()

  res.send(person)
})
`

How can i make this operation into a single atomic transaction that will revert if any of them fails by itself?

const [user] = await db.insert(Users).values({ email, password }).returning()
  const [person] = await db.insert(Customers).values({ email }).returning()


Thank you
Was this page helpful?