Skip to content

Instantly share code, notes, and snippets.

@hiranya911
Last active March 11, 2018 19:55
Show Gist options
  • Save hiranya911/77e92f9f86c18dbd00c7386a8b046a62 to your computer and use it in GitHub Desktop.
Save hiranya911/77e92f9f86c18dbd00c7386a8b046a62 to your computer and use it in GitHub Desktop.
// Transaction update handler: This may get invoked multiple times due to retries.
withdraw100 := func(tn db.TransactionNode) (interface{}, error) {
// Read the current state of the node.
var acc Account
if err := tn.Unmarshal(&acc); err != nil {
return nil, err
}
// Mutate the state in memory.
if acc.Balance < 100.0 {
// Abort the transaction at anytime by returning an error.
return nil, fmt.Errorf("insufficient funds: %.2f", acc.Balance)
}
acc.Balance -= 100.0
// Return the new value which will be written back to the database.
return acc, nil
}
ref := client.NewRef("accounts/alice")
if err := ref.Transaction(ctx, withdraw100); err != nil {
log.Fatal(err)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment