Skip to content

Commit 2cc68f5

Browse files
authored
Allow clients to provide timestamp (#29)
1 parent 863dfa5 commit 2cc68f5

File tree

2 files changed

+19
-1
lines changed

2 files changed

+19
-1
lines changed

controllers/transactions.go

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@ import (
77
"log"
88
"net/http"
99
"regexp"
10+
"time"
1011

1112
ledgerContext "github.com/RealImage/QLedger/context"
1213
"github.com/RealImage/QLedger/models"
@@ -28,6 +29,14 @@ func unmarshalToTransaction(r *http.Request, txn *models.Transaction) error {
2829
return fmt.Errorf("Invalid key in data json: %v", key)
2930
}
3031
}
32+
// Validate timestamp format if present
33+
if txn.Timestamp != "" {
34+
_, err := time.Parse(models.LedgerTimestampLayout, txn.Timestamp)
35+
if err != nil {
36+
return err
37+
}
38+
}
39+
3140
return nil
3241
}
3342

models/transactions.go

Lines changed: 10 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,11 @@ import (
1111
"github.com/pkg/errors"
1212
)
1313

14+
const (
15+
// LedgerTimestampLayout is the timestamp layout followed in Ledger
16+
LedgerTimestampLayout = "2006-01-02 15:04:05.000"
17+
)
18+
1419
// Transaction represents a transaction in a ledger
1520
type Transaction struct {
1621
ID string `json:"id"`
@@ -122,7 +127,11 @@ func (t *TransactionDB) Transact(txn *Transaction) bool {
122127
transactionData = string(data)
123128
}
124129

125-
_, err = tx.Exec("INSERT INTO transactions (id, timestamp, data) VALUES ($1, $2, $3)", txn.ID, time.Now().UTC(), transactionData)
130+
if txn.Timestamp == "" {
131+
txn.Timestamp = time.Now().UTC().Format(LedgerTimestampLayout)
132+
}
133+
134+
_, err = tx.Exec("INSERT INTO transactions (id, timestamp, data) VALUES ($1, $2, $3)", txn.ID, txn.Timestamp, transactionData)
126135
if err != nil {
127136
return handleTransactionError(tx, errors.Wrap(err, "insert transaction failed"))
128137
}

0 commit comments

Comments
 (0)