-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbank.go
125 lines (97 loc) · 2.5 KB
/
bank.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
package main
import (
"errors"
"fmt"
"math"
"github.com/aerospike/aerospike-client-go"
)
type Bank struct {
Id string
Balance float64
Seq int
}
var (
ErrBalanceNotFound = errors.New("Balance not found")
WPolicy *aerospike.WritePolicy
)
func init() {
WPolicy := aerospike.NewWritePolicy(0, 0)
WPolicy.SendKey = true
}
func BankSaveStats(amount float64, clnt *aerospike.Client) error {
key, err := aerospike.NewKey(DBNs, DBTblStat, "stat")
if err != nil {
return err
}
intAmount := int(math.Floor((amount * MonetaryShift) + 0.5))
_, err = clnt.Operate(WPolicy,
key,
aerospike.AddOp(aerospike.NewBin("funds", intAmount)),
aerospike.AddOp(aerospike.NewBin("counter", 1)))
return err
}
func BankGetStats(clnt *aerospike.Client) (float64, int, error) {
key, err := aerospike.NewKey(DBNs, DBTblStat, "stat")
if err != nil {
return 0, 0, err
}
rec, err := Clnt.Get(nil, key)
if err != nil {
return 0, 0, err
}
if rec == nil {
return 0, 0, errors.New("No stats found")
}
var counter int
var funds float64
if _, ok := rec.Bins["funds"]; ok && rec.Bins["funds"] != nil {
funds = float64(rec.Bins["funds"].(int)) / MonetaryShift
}
if _, ok := rec.Bins["counter"]; ok && rec.Bins["counter"] != nil {
counter = rec.Bins["counter"].(int)
}
return funds, counter, err
}
func NewBank(id string, clnt *aerospike.Client) (*Bank, error) {
key, err := aerospike.NewKey(DBNs, DBTblAccounts, fmt.Sprintf("%s", id))
if err != nil {
return nil, err
}
rec, err := Clnt.Get(nil, key)
if err != nil {
return nil, err
}
var balance float64
var seq int
if rec != nil {
if _, ok := rec.Bins["balance"]; ok && rec.Bins["balance"] != nil {
balance = float64(rec.Bins["balance"].(int)) / MonetaryShift
}
if _, ok := rec.Bins["seq"]; ok && rec.Bins["seq"] != nil {
seq = rec.Bins["seq"].(int)
}
}
bankModel := Bank{
Id: id,
Balance: balance,
Seq: seq,
}
return &bankModel, nil
}
func (self *Bank) addFunds(amount float64, Clnt *aerospike.Client) (int32, error) {
intAmount := int(math.Floor((amount * MonetaryShift) + 0.5))
key, err := aerospike.NewKey(DBNs, DBTblAccounts, self.Id)
if err != nil {
return 0, err
}
Clnt.PutBins(WPolicy, key, aerospike.NewBin("id", self.Id))
_, err = Clnt.Operate(WPolicy, key,
aerospike.AddOp(aerospike.NewBin("balance", intAmount)),
aerospike.AddOp(aerospike.NewBin("seq", 1)))
if err != nil {
return 0, err
}
res, _ := Clnt.Get(nil, key)
seq := res.Bins["seq"].(int)
return int32(seq), err
}