/
store.go
92 lines (85 loc) · 2.19 KB
/
store.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
package mongostore
import (
"context"
"github.com/1k-off/dev-helper-bot/internal/store"
"github.com/rs/zerolog/log"
"go.mongodb.org/mongo-driver/bson"
"go.mongodb.org/mongo-driver/mongo"
"go.mongodb.org/mongo-driver/mongo/options"
"go.mongodb.org/mongo-driver/x/mongo/driver/connstring"
)
type DataStore struct {
client *mongo.Client
db *mongo.Database
ctx context.Context
domainRepository *domainRepository
vpnEuRepository *vpnEuRepository
}
func New(uri string) *DataStore {
cs, err := connstring.ParseAndValidate(uri)
if err != nil {
log.Fatal().Err(err).Msg("")
}
// Use the SetServerAPIOptions() method to set the Stable API version to 1
serverAPI := options.ServerAPI(options.ServerAPIVersion1)
opts := options.Client().ApplyURI(uri).SetServerAPIOptions(serverAPI)
client, err := mongo.Connect(context.TODO(), opts)
if err != nil {
log.Fatal().Err(err).Msg("")
}
ctx := context.Background()
err = client.Ping(ctx, nil)
if err != nil {
log.Fatal().Err(err).Msg("")
}
return &DataStore{
client: client,
db: client.Database(cs.Database),
ctx: ctx,
}
}
func (s *DataStore) DomainRepository() store.DomainRepository {
if s.domainRepository != nil {
return s.domainRepository
}
c := s.db.Collection(store.DomainCollection)
_, err := c.Indexes().CreateOne(
context.Background(),
mongo.IndexModel{
Keys: bson.D{{Key: store.DomainUserIdKey, Value: 1}},
Options: options.Index().SetUnique(true),
},
)
if err != nil {
log.Error().Err(err).Msg("")
}
s.domainRepository = &domainRepository{
store: s,
collection: c,
}
return s.domainRepository
}
func (s *DataStore) VPNEURepository() store.VPNEURepository {
if s.vpnEuRepository != nil {
return s.vpnEuRepository
}
c := s.db.Collection(store.VpnEUCollection)
_, err := c.Indexes().CreateOne(
context.Background(),
mongo.IndexModel{
Keys: bson.D{{Key: store.VpnEuUserEmail, Value: 1}},
Options: options.Index(),
},
)
if err != nil {
log.Error().Err(err).Msg("")
}
s.vpnEuRepository = &vpnEuRepository{
store: s,
collection: c,
}
return s.vpnEuRepository
}
func (s *DataStore) Close() error {
return s.client.Disconnect(s.ctx)
}