-
Notifications
You must be signed in to change notification settings - Fork 0
/
repository.go
75 lines (63 loc) · 1.63 KB
/
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
package quote
import (
"context"
"go.mongodb.org/mongo-driver/bson"
"go.mongodb.org/mongo-driver/mongo"
)
type Repository interface {
Create(ctx context.Context, q *Quote) error
Update(ctx context.Context, q *Quote) error
Delete(ctx context.Context, id string) error
GetAll(ctx context.Context) ([]Quote, error)
GetById(ctx context.Context, id string) (*Quote, error)
}
type mongoRepository struct {
collection *mongo.Collection
}
func NewMongoRepository(col *mongo.Collection) Repository {
return &mongoRepository{
collection: col,
}
}
func (r *mongoRepository) Create(ctx context.Context, q *Quote) error {
_, err := r.collection.InsertOne(ctx, q)
if err != nil {
return err
}
return nil
}
func (r *mongoRepository) Update(ctx context.Context, q *Quote) error {
filter := bson.M{"_id": q.Id}
update := bson.M{"$set": q}
if _, err := r.collection.UpdateOne(ctx, filter, update); err != nil {
return err
}
return nil
}
func (r *mongoRepository) Delete(ctx context.Context, id string) error {
filter := bson.M{"_id": id}
if _, err := r.collection.DeleteOne(ctx, filter); err != nil {
return err
}
return nil
}
func (r *mongoRepository) GetAll(ctx context.Context) ([]Quote, error) {
var qq []Quote
cur, err := r.collection.Find(ctx, bson.M{})
if err != nil {
return nil, err
}
defer cur.Close(ctx)
if err := cur.All(ctx, &qq); err != nil {
return nil, err
}
return qq, nil
}
func (r *mongoRepository) GetById(ctx context.Context, id string) (*Quote, error) {
filter := bson.M{"_id": id}
var q Quote
if err := r.collection.FindOne(ctx, filter).Decode(&q); err != nil {
return nil, err
}
return &q, nil
}