/
mongo_repository.go
85 lines (69 loc) · 2.33 KB
/
mongo_repository.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
package repository
import (
"context"
"time"
"github.com/openuniland/good-guy/configs"
"github.com/openuniland/good-guy/internal/cookies"
"github.com/openuniland/good-guy/internal/models"
"github.com/openuniland/good-guy/pkg/db/mongodb"
"github.com/rs/zerolog/log"
"go.mongodb.org/mongo-driver/bson"
"go.mongodb.org/mongo-driver/bson/primitive"
"go.mongodb.org/mongo-driver/mongo"
"go.mongodb.org/mongo-driver/mongo/options"
)
var collectionName = "cookies"
type cookieRepo struct {
cfg *configs.Configs
mongodb *mongodb.MongoDB
}
func NewCookieRepository(cfg *configs.Configs, mongodb *mongodb.MongoDB) cookies.Repository {
if err := mongodb.DB.CreateCollection(context.Background(), collectionName); err != nil {
log.Warn().Err(err).Msg("collection already exists: " + collectionName)
}
coll := mongodb.DB.Collection(collectionName)
indexModels := []mongo.IndexModel{
{
Keys: bson.M{
"username": 1,
},
Options: options.Index().SetUnique(true),
},
{
Keys: bson.M{
"cookies": 1,
},
Options: options.Index().SetUnique(false),
},
}
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
_, err := coll.Indexes().CreateMany(ctx, indexModels)
if err != nil {
log.Warn().Err(err).Msg("failed to create indexes: " + collectionName)
}
return &cookieRepo{cfg: cfg, mongodb: mongodb}
}
func (c *cookieRepo) Create(ctx context.Context, cookie *models.Cookie) (*mongo.InsertOneResult, error) {
dbName := c.cfg.MongoDB.MongoDBName
coll := c.mongodb.Client.Database(dbName).Collection(collectionName)
cookie.CreatedAt = primitive.NewDateTimeFromTime(time.Now())
return coll.InsertOne(ctx, cookie)
}
func (c *cookieRepo) FindOne(ctx context.Context, filter bson.M) (*models.Cookie, error) {
dbName := c.cfg.MongoDB.MongoDBName
coll := c.mongodb.Client.Database(dbName).Collection(collectionName)
var cookie *models.Cookie
res := coll.FindOne(ctx, filter)
if err := res.Decode(&cookie); err != nil {
return nil, err
}
return cookie, nil
}
func (c *cookieRepo) UpdateSertOne(ctx context.Context, filter bson.M, update bson.M) (*mongo.UpdateResult, error) {
dbName := c.cfg.MongoDB.MongoDBName
coll := c.mongodb.Client.Database(dbName).Collection(collectionName)
upsert := true
opts := options.Update().SetUpsert(upsert)
return coll.UpdateOne(ctx, filter, update, opts)
}