DEV Community

Discussion on: Idiomatic Go and the hardship of running two methods in the same DB transaction

Collapse
 
qm3ster profile image
Mihail Malo

This solutions makes quite a bit of sense.
Reminds me of Firestore's js library:

const transaction = db.runTransaction(async t => {
  const doc = await t.get(cityRef)
  var newPopulation = doc.data().population + 1
  await t.update(cityRef, { population: newPopulation })
})

It's the same substitution of global db inside a callback to the transaction method on our specific db struct.

const whatAmI = async db => {
  const doc = await db.get(cityRef)
  var newPopulation = doc.data().population + 1
  await db.update(cityRef, { population: newPopulation })
}

const notATransaction = whatAmI(db)

const aTransaction = db.runTransaction(whatAmI)