-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdatabase.go
More file actions
118 lines (103 loc) · 2.38 KB
/
database.go
File metadata and controls
118 lines (103 loc) · 2.38 KB
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
package main
import (
"context"
"os"
"github.com/joho/godotenv"
"go.mongodb.org/mongo-driver/bson"
"go.mongodb.org/mongo-driver/mongo"
"go.mongodb.org/mongo-driver/mongo/options"
"go.mongodb.org/mongo-driver/mongo/readpref"
)
type Store interface {
Insert(context.Context,*Event)error
UpdateStatus(context.Context,*Event)error
IncrementCount(context.Context,*Event)error
GetCount(context.Context,*Event)(int,error)
GetStatus(context.Context,*Event)(*Status,error)
}
type MongoStore struct {
collection *mongo.Database
}
func GetStore(ctx context.Context)(*MongoStore,error){
godotenv.Load()
url:=os.Getenv("MONGO_URL_EVENT_DOCUMENT")
client,err:=mongo.Connect(ctx,options.Client().ApplyURI(url))
if err!=nil{
return nil,err
}
if err:=client.Ping(ctx,readpref.Primary());err!=nil{
return nil,err
}
database:=client.Database("Event-Document")
return &MongoStore{
collection: database,
},nil
}
func(store *MongoStore)Insert(ctx context.Context,event *Event)error{
coll:=store.collection.Collection("Event-Document")
_,err:=coll.InsertOne(ctx,event)
if err!=nil{
return err
}
return nil
}
func(store *MongoStore)UpdateStatus(ctx context.Context,event *Event)error{
coll:=store.collection.Collection("Event-Document")
filter:=bson.M{
"_id":event.Id,
}
update:=bson.M{
"$set":bson.M{
"status":"processed",
},
}
_,err:=coll.UpdateOne(ctx,filter,update)
if err!=nil{
return err
}
return nil
}
func(store *MongoStore)GetCount(ctx context.Context,event *Event)(int,error){
var document Event
coll:=store.collection.Collection("Event-Document")
result:=coll.FindOne(ctx,bson.M{
"_id":event.Id,
})
err:=result.Decode(&document)
if err!=nil{
return 0,err
}
return document.RetryCount,nil
}
func(store *MongoStore)IncrementCount(ctx context.Context,event *Event)error{
count,err:=store.GetCount(ctx,event)
if err!=nil{
return err
}
if count<5{
coll:=store.collection.Collection("Event-Document")
_,err=coll.UpdateOne(ctx,bson.M{
"_id":event.Id,
},
bson.M{
"$set":bson.M{
"retry_count":count+1,
},
})
if err!=nil{
return err
}
}
return nil
}
func(store *MongoStore)GetStatus(ctx context.Context,event *Event)(*Status,error){
var status Status
coll:=store.collection.Collection("Event-Document")
result:=coll.FindOne(ctx,bson.M{
"_id":event.Id,
})
if err:=result.Decode(&status);err!=nil{
return nil,err
}
return &status,nil
}