Last active
June 9, 2019 21:15
-
-
Save IvanProdaiko94/561be1a310b9cc7e83e5a5272ca5479f to your computer and use it in GitHub Desktop.
Convenient way to avoid `read-after-write` errors in datastore transactions. Having delta one can store every change inside it and in the end of transaction call `td.Apply()`.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package firestore | |
import ( | |
"cloud.google.com/go/firestore" | |
) | |
type TransactionDelta struct { | |
tx *firestore.Transaction | |
delta []func() error | |
} | |
func (writes *TransactionDelta) Create(doc *firestore.DocumentRef, d interface{}) { | |
writes.delta = append(writes.delta, func() error { | |
return writes.tx.Create(doc, d) | |
}) | |
} | |
func (writes *TransactionDelta) Set(doc *firestore.DocumentRef, d interface{}, opts... firestore.SetOption) { | |
writes.delta = append(writes.delta, func() error { | |
return writes.tx.Set(doc, d, opts...) | |
}) | |
} | |
func (writes *TransactionDelta) Update(doc *firestore.DocumentRef, u []firestore.Update, precondition... firestore.Precondition) { | |
writes.delta = append(writes.delta, func() error { | |
return writes.tx.Update(doc, u, precondition...) | |
}) | |
} | |
func (writes *TransactionDelta) Delete(doc *firestore.DocumentRef, precondition... firestore.Precondition) { | |
writes.delta = append(writes.delta, func() error { | |
return writes.tx.Delete(doc, precondition...) | |
}) | |
} | |
func (writes *TransactionDelta) Apply() error { | |
for _, fn := range writes.delta { | |
err := fn() | |
if err != nil { | |
return err | |
} | |
} | |
return nil | |
} | |
func NewTransactionDelta(tx *firestore.Transaction) *TransactionDelta { | |
return &TransactionDelta{ | |
tx: tx, | |
delta: []func() error{}, | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment