github.com/hoffie/larasync@v0.0.0-20151025221940-0384d2bddcef/repository/transaction.go (about) 1 package repository 2 3 import ( 4 "errors" 5 "fmt" 6 "strconv" 7 8 "github.com/hoffie/larasync/repository/odf" 9 ) 10 11 // Transaction represents a server side transaction for specific NIBs 12 // which is used to synchronize the different clients. 13 type Transaction struct { 14 ID int64 15 NIBIDs []string 16 PreviousID int64 17 } 18 19 // newTransactionFromPb returns a new Transaction from the 20 // protobuf Transaction. 21 func newTransactionFromPb(pbTransaction *odf.Transaction) *Transaction { 22 return &Transaction{ 23 ID: pbTransaction.GetID(), 24 PreviousID: pbTransaction.GetPreviousID(), 25 NIBIDs: pbTransaction.GetNIBIDs(), 26 } 27 } 28 29 // toPb converts this Transaction to a protobuf Transaction. 30 // This is used by the encoder. 31 func (t *Transaction) toPb() (*odf.Transaction, error) { 32 if t.ID == 0 { 33 return nil, errors.New("Transaction ID must not be empty") 34 } 35 if len(t.NIBIDs) == 0 { 36 return nil, fmt.Errorf( 37 "The transaction with ID %d has no NIB IDs", 38 t.ID, 39 ) 40 } 41 protoTransaction := &odf.Transaction{ 42 ID: &t.ID, 43 PreviousID: nil, 44 NIBIDs: t.NIBIDs} 45 if t.PreviousID != 0 { 46 protoTransaction.PreviousID = &t.PreviousID 47 } 48 return protoTransaction, nil 49 } 50 51 // IDString returns the ID of this Transaction as a string. 52 func (t *Transaction) IDString() string { 53 return strconv.FormatInt(t.ID, 10) 54 } 55 56 // PreviousIDString returns the Previous transaction id as a string 57 func (t *Transaction) PreviousIDString() string { 58 return strconv.FormatInt(t.PreviousID, 10) 59 } 60 61 // nibUUIDsFromTransactions returns all uuids from a list of transactions. 62 func nibUUIDsFromTransactions(transactions []*Transaction) <-chan string { 63 nibUUIDChannel := make(chan string, 100) 64 go func() { 65 for _, transaction := range transactions { 66 for _, nibID := range transaction.NIBIDs { 67 nibUUIDChannel <- nibID 68 } 69 } 70 close(nibUUIDChannel) 71 }() 72 return nibUUIDChannel 73 }