-
Notifications
You must be signed in to change notification settings - Fork 0
/
mongo_repository.go
124 lines (104 loc) · 2.48 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
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
119
120
121
122
123
124
package mongodata
import (
"context"
"errors"
"github.com/cardboardrobots/mongodata/utils"
"github.com/cardboardrobots/repository"
"go.mongodb.org/mongo-driver/bson"
"go.mongodb.org/mongo-driver/bson/primitive"
"go.mongodb.org/mongo-driver/mongo"
)
type MongoRepository[T utils.Valid] struct {
Collection *mongo.Collection
}
func NewMongoRepository[T utils.Valid](da *DataAccess, collectionName string) *MongoRepository[T] {
collection := da.Collection(collectionName)
return &MongoRepository[T]{
collection,
}
}
var _ repository.Repository[utils.Valid] = &MongoRepository[utils.Valid]{}
func (c *MongoRepository[T]) GetList(
ctx context.Context,
query repository.Query,
) (repository.ListResult[T], error) {
cursor, err := c.Collection.Find(ctx, query)
if err != nil {
return nil, err
}
var results []T
if err = cursor.All(ctx, &results); err != nil {
return nil, err
}
result := repository.NewListResult(len(results), results)
return result, nil
}
func (c *MongoRepository[T]) GetById(
ctx context.Context,
id string,
) (T, error) {
_id, err := primitive.ObjectIDFromHex(id)
if err != nil {
var zero T
return zero, err
}
var result T
err = c.Collection.FindOne(ctx, bson.M{
"_id": _id,
}).Decode(&result)
if err != nil {
// ErrNoDocuments means that the filter did not match any documents in
// the collection.
var zero T
if err == mongo.ErrNoDocuments {
return zero, errors.New("not found")
}
return zero, err
}
return result, err
}
func (c *MongoRepository[T]) Create(
ctx context.Context,
data T,
) (string, error) {
error := data.Valid()
if error != nil {
return "", error
}
result, error := c.Collection.InsertOne(ctx, data)
return result.InsertedID.(primitive.ObjectID).Hex(), error
}
func (c *MongoRepository[T]) Update(
ctx context.Context,
id string,
data T,
) (bool, error) {
err := data.Valid()
if err != nil {
return false, err
}
_id, err := primitive.ObjectIDFromHex(id)
if err != nil {
return false, err
}
updateDate := make(map[string]interface{})
updateDate["$set"] = data
result, err := c.Collection.UpdateByID(ctx, _id, updateDate)
if err != nil {
return false, err
}
return (result.ModifiedCount + result.UpsertedCount) > 0, err
}
func (c *MongoRepository[T]) Delete(
ctx context.Context,
id string,
) (bool, error) {
_id, err := primitive.ObjectIDFromHex(id)
if err != nil {
return false, err
}
result, err := c.Collection.DeleteOne(ctx, bson.M{
"_id": _id,
})
return result.DeletedCount > 0, err
}