/
db.go
139 lines (112 loc) · 3.32 KB
/
db.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
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
package db
import (
"context"
"fmt"
"os"
"time"
"github.com/joho/godotenv"
"go.mongodb.org/mongo-driver/bson"
"go.mongodb.org/mongo-driver/mongo"
"go.mongodb.org/mongo-driver/mongo/options"
)
func GetMongoClient() (*mongo.Client, error) {
err := godotenv.Load(".env")
if err != nil {
fmt.Println("[ERROR] error loading .env file")
}
serverAPI := options.ServerAPI(options.ServerAPIVersion1)
opts := options.Client().
ApplyURI(os.Getenv("MONGODB_URI")).
SetServerAPIOptions(serverAPI)
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
client, err := mongo.Connect(ctx, opts)
if err != nil {
return nil, fmt.Errorf("[ERROR] failed to connect to MongoDB: %v", err)
}
err = client.Ping(ctx, nil)
if err != nil {
return nil, fmt.Errorf("[ERROR] failed to ping MongoDB: %v", err)
}
fmt.Println("[SUCCESS] connected to MongoDB!")
return client, nil
}
func SaveDataToMongoDB(data Data) error {
client, err := GetMongoClient()
if err != nil {
return err
}
defer client.Disconnect(context.Background())
collection := client.Database(os.Getenv("DB_NAME")).Collection(os.Getenv("COLLECTION_NAME"))
_, err = collection.InsertOne(context.Background(), data)
if err != nil {
return fmt.Errorf("[ERROR] failed to insert data into MongoDB: %v", err)
}
fmt.Println("[SUCCESS] data saved to MongoDB!")
return nil
}
func GetData(username string) (Data, error) {
client, err := GetMongoClient()
if err != nil {
return Data{}, err
}
defer client.Disconnect(context.Background())
collection := client.Database(os.Getenv("DB_NAME")).Collection(os.Getenv("COLLECTION_NAME"))
filter := bson.M{
"username": username,
}
var cityData Data
err = collection.FindOne(context.Background(), filter).Decode(&cityData)
if err != nil {
return Data{}, fmt.Errorf("[ERROR] failed to fetch city data from MongoDB: %v", err)
}
return cityData, nil
}
func FetchDataFromMongoDB(username string) ([]Data, error) {
client, err := GetMongoClient()
if err != nil {
return nil, err
}
defer client.Disconnect(context.Background())
collection := client.Database(os.Getenv("DB_NAME")).Collection(os.Getenv("COLLECTION_NAME"))
filter := bson.M{
"username": username,
}
cursor, err := collection.Find(context.Background(), filter)
if err != nil {
return nil, err
}
defer cursor.Close(context.Background())
var citiesData []Data
err = cursor.All(context.Background(), &citiesData)
if err != nil {
return nil, err
}
return citiesData, nil
}
func AsyncSaveDataToMongoDB(data []Data, done chan<- bool) {
client, err := GetMongoClient()
if err != nil {
fmt.Printf("[ERROR] failed to connect to MongoDB: %v\n", err)
done <- true
return
}
defer client.Disconnect(context.Background())
collection := client.Database(os.Getenv("DB_NAME")).Collection(os.Getenv("COLLECTION_NAME"))
_, err = collection.DeleteMany(context.Background(), bson.M{})
if err != nil {
fmt.Printf("[ERROR] failed to delete existing data from MongoDB: %v\n", err)
done <- true
return
}
var documents []interface{}
for _, cityData := range data {
documents = append(documents, cityData)
}
_, err = collection.InsertMany(context.Background(), documents)
if err != nil {
fmt.Printf("[ERROR] failed to insert data into MongoDB: %v\n", err)
}
fmt.Println("[SUCCESS] data saved to MongoDB!")
done <- true
}