-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathconfigs.go
47 lines (39 loc) · 1.19 KB
/
configs.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
package stores
import (
"context"
"go.mongodb.org/mongo-driver/bson"
"go.mongodb.org/mongo-driver/mongo"
"go.mongodb.org/mongo-driver/mongo/options"
)
type ConfigsStore struct {
*store
}
const CONFIGS Collection = "configs"
func newConfigsStore(ctx context.Context, client *mongo.Client, database string) *ConfigsStore {
_ = client.Database(database).CreateCollection(ctx, string(CONFIGS))
s := &store{
Collection: client.Database(database).Collection(string(CONFIGS)),
ctx: ctx,
}
return &ConfigsStore{s}
}
func (c *Client) GetConfigsStore() (*ConfigsStore, bool) {
storeInterface, ok := c.GetCollection(CONFIGS)
if !ok {
return nil, false
}
return storeInterface.(*ConfigsStore), ok
}
func (s *ConfigsStore) Get(name string) *mongo.SingleResult {
filter := bson.D{{Key: "name", Value: name}}
return s.FindOne(s.ctx, filter)
}
func (s *ConfigsStore) Upsert(name string, config any) error {
opts := options.FindOneAndReplace().SetUpsert(true)
if err := s.FindOneAndReplace(s.ctx, bson.D{{Key: "name", Value: name}}, bson.D{{Key: "name", Value: name}, {Key: "value", Value: config}}, opts).Err(); err != nil {
if err != mongo.ErrNoDocuments {
return err
}
}
return nil
}