-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtokens.go
104 lines (90 loc) · 2.17 KB
/
tokens.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
package stores
import (
"context"
"github.com/sol-armada/sol-bot/utils"
"go.mongodb.org/mongo-driver/bson"
"go.mongodb.org/mongo-driver/mongo"
"go.mongodb.org/mongo-driver/mongo/options"
)
type TokenStore struct {
*store
}
const TOKENS Collection = "tokens"
func newTokensStore(ctx context.Context, client *mongo.Client, database string) *TokenStore {
_ = client.Database(database).CreateCollection(ctx, string(TOKENS), &options.CreateCollectionOptions{
TimeSeriesOptions: &options.TimeSeriesOptions{
TimeField: "created_at",
MetaField: utils.StringPointer("member_id"),
},
})
s := &store{
Collection: client.Database(database).Collection(string(TOKENS)),
ctx: ctx,
}
return &TokenStore{s}
}
func (c *Client) GetTokensStore() (*TokenStore, bool) {
storeInterface, ok := c.GetCollection(TOKENS)
if !ok {
return nil, false
}
return storeInterface.(*TokenStore), ok
}
func (s *TokenStore) Insert(tokenRecord any) error {
_, err := s.InsertOne(s.ctx, tokenRecord)
return err
}
// Get all token records grouping by member id
func (s *TokenStore) GetAllGrouped() (*mongo.Cursor, error) {
aggregate := []bson.M{
{
"$group": bson.M{
"_id": "$member_id",
"token_records": bson.M{
"$push": "$$ROOT",
},
},
},
}
cursor, err := s.Aggregate(s.ctx, aggregate)
if err != nil {
return nil, err
}
return cursor, nil
}
func (s *TokenStore) GetAll() (*mongo.Cursor, error) {
cursor, err := s.Find(s.ctx, bson.D{})
if err != nil {
return nil, err
}
return cursor, nil
}
func (s *TokenStore) Get(id string) (*mongo.SingleResult, error) {
res := s.FindOne(s.ctx, bson.D{{Key: "_id", Value: id}})
err := res.Err()
return res, err
}
func (s *TokenStore) GetAllBalances() (*mongo.Cursor, error) {
aggregate := bson.A{
bson.D{
{Key: "$group", Value: bson.D{
{Key: "_id", Value: "$member_id"},
{Key: "balance", Value: bson.D{
{Key: "$sum", Value: "$amount"},
}},
}},
},
bson.D{
{Key: "$addFields", Value: bson.D{
{Key: "balance", Value: bson.D{
{Key: "$sum", Value: "$balance"},
}},
}},
},
}
cursor, err := s.Aggregate(s.ctx, aggregate)
if err != nil {
return nil, err
}
return cursor, nil
}