-
Notifications
You must be signed in to change notification settings - Fork 2
/
repository.go
109 lines (87 loc) · 2.26 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
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
package news
import (
"context"
"go.mongodb.org/mongo-driver/bson"
"go.mongodb.org/mongo-driver/mongo"
"go.mongodb.org/mongo-driver/mongo/options"
"log"
"os"
"time"
)
type Repository struct {
MongoClient *mongo.Client
}
func NewRepository(uri string) Repository {
env := os.Getenv("APP_ENV")
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
client, err := mongo.Connect(ctx, options.Client().ApplyURI(uri))
defer cancel()
client.Connect(ctx)
if err != nil {
log.Fatal(err)
}
if env == "test" {
client.Database("ventures").Collection("users").Drop(ctx)
}
return Repository{client}
}
func (r *Repository) GetNews() ([]News, error) {
collection := r.MongoClient.Database("ventures").Collection("news")
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
defer cancel()
filter := bson.M{}
cur, err := collection.Find(ctx, filter)
if err != nil {
return nil, nil
}
var news []News
for cur.Next(ctx) {
userEntity := News{}
err := cur.Decode(&userEntity)
if err != nil {
return nil, nil
}
news = append(news, userEntity)
}
return news, nil
}
func (r *Repository) AddNews(news News) (*News, error) {
collection := r.MongoClient.Database("ventures").Collection("news")
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
defer cancel()
_, err := collection.InsertOne(ctx, news)
if err != nil {
return nil, err
}
return r.GetNewsByID(news.ID)
}
func (r *Repository) DeleteNews(id string) error {
collection := r.MongoClient.Database("ventures").Collection("news")
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
defer cancel()
filter := bson.M{"id": id}
_, err := collection.DeleteOne(ctx, filter)
if err != nil {
return err
}
return nil
}
func (r *Repository) GetNewsByID(id string) (*News, error) {
collection := r.MongoClient.Database("ventures").Collection("news")
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
defer cancel()
filter := bson.M{"id": id}
cur := collection.FindOne(ctx, filter)
if cur.Err() != nil {
return nil, cur.Err()
}
if cur == nil {
return nil, cur.Err()
}
newsEntitiy := News{}
err := cur.Decode(&newsEntitiy)
if err != nil {
return nil, err
}
return &newsEntitiy, nil
}