-
Notifications
You must be signed in to change notification settings - Fork 133
/
mongo.go
72 lines (56 loc) · 1.79 KB
/
mongo.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
package config
import (
"context"
"fmt"
"go.mongodb.org/mongo-driver/bson"
"go.mongodb.org/mongo-driver/mongo"
"go.mongodb.org/mongo-driver/mongo/options"
"github.com/kubeshop/testkube/pkg/api/v1/testkube"
"github.com/kubeshop/testkube/pkg/telemetry"
)
const CollectionName = "config"
const Id = "api"
func NewMongoRepository(db *mongo.Database, opts ...Opt) *MongoRepository {
r := &MongoRepository{
Coll: db.Collection(CollectionName),
}
for _, opt := range opts {
opt(r)
}
return r
}
type Opt func(*MongoRepository)
func WithMongoRepositoryCollection(collection *mongo.Collection) Opt {
return func(r *MongoRepository) {
r.Coll = collection
}
}
type MongoRepository struct {
Coll *mongo.Collection
}
func (r *MongoRepository) GetUniqueClusterId(ctx context.Context) (clusterId string, err error) {
config := testkube.Config{}
_ = r.Coll.FindOne(ctx, bson.M{"id": Id}).Decode(&config)
// generate new cluster id and save if there is not already
if config.ClusterId == "" {
config.ClusterId = fmt.Sprintf("cluster%s", telemetry.GetMachineID())
_, err := r.Upsert(ctx, config)
return config.ClusterId, err
}
return config.ClusterId, nil
}
func (r *MongoRepository) GetTelemetryEnabled(ctx context.Context) (ok bool, err error) {
config := testkube.Config{}
err = r.Coll.FindOne(ctx, bson.M{"id": Id}).Decode(&config)
return config.EnableTelemetry, err
}
func (r *MongoRepository) Get(ctx context.Context) (result testkube.Config, err error) {
err = r.Coll.FindOne(ctx, bson.M{"id": Id}).Decode(&result)
return
}
func (r *MongoRepository) Upsert(ctx context.Context, result testkube.Config) (updated testkube.Config, err error) {
upsert := true
result.Id = Id
_, err = r.Coll.ReplaceOne(ctx, bson.M{"id": Id}, result, &options.ReplaceOptions{Upsert: &upsert})
return result, err
}