/
mongo.go
115 lines (88 loc) · 2.45 KB
/
mongo.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
package mongo
import (
"context"
"log"
"os"
"time"
"github.com/berabulut/kapsule/models"
"github.com/joho/godotenv"
"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 collection *mongo.Collection
var ctx = context.TODO()
func init() {
// the .env path is from cmd/api or cmd/redirect
if err := godotenv.Load("../../.env"); err != nil {
log.Fatal(err)
}
client, err := mongo.NewClient(options.Client().ApplyURI(os.Getenv("ATLAS_URI")))
if err != nil {
log.Fatal(err)
}
ctx, _ := context.WithTimeout(context.Background(), 10*time.Second)
err = client.Connect(ctx)
if err != nil {
log.Fatal(err)
}
err = client.Ping(ctx, nil)
if err != nil {
log.Fatal(err)
}
collection = client.Database("kapsule").Collection("urls")
}
func NewRecord(url *models.ShortURL) error {
_, err := collection.InsertOne(ctx, url)
return err
}
func GetRecords() (map[string]*models.ShortURL, error) {
filter := bson.D{{}}
return filterRecords(filter)
}
func GetRecord(key string) (models.ShortURL, error) {
record := &models.ShortURL{}
if err := collection.FindOne(ctx, bson.M{"key": key}).Decode(record); err != nil {
return models.ShortURL{}, err
}
return *record, nil
}
func HandleClick(key string, clicks int, lastTimeVisited time.Time, visits []models.Visit) error {
filter := bson.D{primitive.E{Key: "key", Value: key}}
update := bson.D{primitive.E{Key: "$set", Value: bson.D{
primitive.E{Key: "clicks", Value: clicks},
primitive.E{Key: "last_time_visited", Value: lastTimeVisited},
primitive.E{Key: "visits", Value: visits},
}}}
r := &models.ShortURL{}
return collection.FindOneAndUpdate(ctx, filter, update).Decode(r)
}
// t := &Task{}
// return collection.FindOneAndUpdate(ctx, filter, update).Decode(t)
// }
func filterRecords(filter interface{}) (map[string]*models.ShortURL, error) {
records := make(map[string]*models.ShortURL)
cur, err := collection.Find(ctx, filter)
if err != nil {
return records, err
}
// Iterate through the cursor and decode each document one at a time
for cur.Next(ctx) {
var r models.ShortURL
err := cur.Decode(&r)
if err != nil {
return records, err
}
records[r.Key] = &r
}
if err := cur.Err(); err != nil {
return records, err
}
// once exhausted, close the cursor
cur.Close(ctx)
if len(records) == 0 {
return records, mongo.ErrNoDocuments
}
return records, nil
}