generated from Ubivius/microservice-template
/
mongoDB.go
294 lines (235 loc) · 8.33 KB
/
mongoDB.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
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
package database
import (
"context"
"fmt"
"net/http"
"os"
"time"
"github.com/Ubivius/microservice-text-chat/pkg/data"
"github.com/google/uuid"
"go.mongodb.org/mongo-driver/bson"
"go.mongodb.org/mongo-driver/mongo"
"go.mongodb.org/mongo-driver/mongo/options"
"go.opentelemetry.io/contrib/instrumentation/go.mongodb.org/mongo-driver/mongo/otelmongo"
"go.opentelemetry.io/otel"
)
// ErrorEnvVar : Environment variable error
var ErrorEnvVar = fmt.Errorf("missing environment variable")
type MongoTextChat struct {
client *mongo.Client
messagesCollection *mongo.Collection
conversationsCollection *mongo.Collection
}
func NewMongoTextChat() TextChatDB {
mp := &MongoTextChat{}
err := mp.Connect()
// If connect fails, kill the program
if err != nil {
log.Error(err, "MongoDB setup failed")
os.Exit(1)
}
return mp
}
func (mp *MongoTextChat) Connect() error {
uri := mongodbURI()
// Setting client options
opts := options.Client()
clientOptions := opts.ApplyURI(uri)
opts.Monitor = otelmongo.NewMonitor()
// Connect to MongoDB
client, err := mongo.Connect(context.Background(), clientOptions)
if err != nil || client == nil {
log.Error(err, "Failed to connect to database. Shutting down service")
os.Exit(1)
}
// Ping DB
err = client.Ping(context.Background(), nil)
if err != nil {
log.Error(err, "Failed to ping database. Shutting down service")
os.Exit(1)
}
log.Info("Connection to MongoDB established")
messagesCollection := client.Database("ubivius").Collection("messages")
conversationsCollection := client.Database("ubivius").Collection("conversations")
// Assign client and collection to the MongoTextChat struct
mp.messagesCollection = messagesCollection
mp.conversationsCollection = conversationsCollection
mp.client = client
return nil
}
func (mp *MongoTextChat) PingDB() error {
return mp.client.Ping(context.Background(), nil)
}
func (mp *MongoTextChat) CloseDB() {
err := mp.client.Disconnect(context.Background())
if err != nil {
log.Error(err, "Error while disconnecting from database")
}
}
func (mp *MongoTextChat) GetMessageByID(ctx context.Context, id string) (*data.Message, error) {
// MongoDB search filter
filter := bson.D{{Key: "_id", Value: id}}
// Holds search result
var result data.Message
// Find a single matching item from the database
err := mp.messagesCollection.FindOne(ctx, filter).Decode(&result)
// Parse result into the returned message
return &result, err
}
func (mp *MongoTextChat) GetConversationByID(ctx context.Context, id string) (*data.Conversation, error) {
// MongoDB search filter
filter := bson.D{{Key: "_id", Value: id}}
// Holds search result
var result data.Conversation
// Find a single matching item from the database
err := mp.conversationsCollection.FindOne(ctx, filter).Decode(&result)
// Parse result into the returned conversation
return &result, err
}
func (mp *MongoTextChat) GetMessagesByConversationID(ctx context.Context, id string) (data.Messages, error) {
// MongoDB search filter
filter := bson.D{{Key: "conversation_id", Value: id}}
// messages will hold the array of Messages
var messages data.Messages
// Find returns a cursor that must be iterated through
cursor, err := mp.messagesCollection.Find(ctx, filter)
if err != nil {
log.Error(err, "Error getting messages by conversationID from database")
}
// Iterating through cursor
for cursor.Next(ctx) {
var result data.Message
err := cursor.Decode(&result)
if err != nil {
log.Error(err, "Error decoding messages from database")
}
messages = append(messages, &result)
}
if err := cursor.Err(); err != nil {
log.Error(err, "Error in cursor after iteration")
}
// Close the cursor once finished
cursor.Close(ctx)
return messages, err
}
func (mp *MongoTextChat) AddMessage(ctx context.Context, message *data.Message) error {
_, err := mp.GetConversationByID(ctx, message.ConversationID)
if err != nil {
return err
}
if !mp.validateUserExist(message.UserID) {
return data.ErrorUserNotFound
}
message.ID = uuid.NewString()
// Adding time information to new message
message.CreatedOn = time.Now().UTC().String()
message.UpdatedOn = time.Now().UTC().String()
// Inserting the new message into the database
insertResult, err := mp.messagesCollection.InsertOne(ctx, message)
if err != nil {
return err
}
log.Info("Inserting message", "Inserted ID", insertResult.InsertedID)
return nil
}
func (mp *MongoTextChat) AddConversation(ctx context.Context, conversation *data.Conversation) (*data.Conversation, error) {
for _, userID := range conversation.UserID {
if !mp.validateUserExist(userID) {
return nil, data.ErrorUserNotFound
}
}
if !mp.validateGameExist(conversation.GameID) {
return nil, data.ErrorGameNotFound
}
conversation.ID = uuid.NewString()
// Adding time information to new conversation
conversation.CreatedOn = time.Now().UTC().String()
conversation.UpdatedOn = time.Now().UTC().String()
// Inserting the new conversation into the database
insertResult, err := mp.conversationsCollection.InsertOne(ctx, conversation)
if err != nil {
return nil, err
}
log.Info("Inserting conversation", "Inserted ID", insertResult.InsertedID)
return conversation, nil
}
func (mp *MongoTextChat) DeleteMessage(ctx context.Context, id string) error {
// MongoDB search filter
filter := bson.D{{Key: "_id", Value: id}}
// Delete a single item matching the filter
result, err := mp.messagesCollection.DeleteOne(ctx, filter)
if err != nil {
log.Error(err, "Error deleting message")
}
log.Info("Deleted documents in messages collection", "delete_count", result.DeletedCount)
return nil
}
func (mp *MongoTextChat) DeleteConversation(ctx context.Context, id string) error {
// MongoDB search filter
filter := bson.D{{Key: "_id", Value: id}}
// Delete a single item matching the filter
result, err := mp.conversationsCollection.DeleteOne(ctx, filter)
if err != nil {
log.Error(err, "Error deleting conversation")
}
log.Info("Deleted documents in conversations collection", "delete_count", result.DeletedCount)
return nil
}
func (mp *MongoTextChat) AddUserToConversation(ctx context.Context, conversation *data.Conversation) error {
_, span := otel.Tracer("text-chat").Start(ctx, "addUserToConversationTextChat")
defer span.End()
for _, userID := range conversation.UserID {
if !mp.validateUserExist(userID) {
return data.ErrorUserNotFound
}
}
if !mp.validateGameExist(conversation.GameID) {
return data.ErrorGameNotFound
}
conversation.UpdatedOn = time.Now().UTC().String()
// MongoDB search filter
filter := bson.D{{Key: "_id", Value: conversation.ID}}
update := bson.M{"$set": conversation}
// Update a single item in the database with the values in update that match the filter
_, err := mp.conversationsCollection.UpdateOne(ctx, filter, update)
if err != nil {
log.Error(err, "Error updating conversation.")
}
return nil
}
func (mp *MongoTextChat) validateUserExist(userID string) bool {
getUserByIDPath := data.MicroserviceUserPath + "/users/" + userID
resp, err := http.Get(getUserByIDPath)
return err == nil && resp.StatusCode == 200
}
func (mp *MongoTextChat) validateGameExist(gameID string) bool {
//Verify if game exist
return true
}
func deleteAllConversationsAndMessagesFromMongoDB() (error, error) {
uri := mongodbURI()
// Setting client options
opts := options.Client()
clientOptions := opts.ApplyURI(uri)
client, err := mongo.Connect(context.Background(), clientOptions)
if err != nil || client == nil {
log.Error(err, "Failed to connect to database. Failing test")
return err, nil
}
messagesCollection := client.Database("ubivius").Collection("messages")
conversationsCollection := client.Database("ubivius").Collection("conversations")
_, err1 := messagesCollection.DeleteMany(context.Background(), bson.D{{}})
_, err2 := conversationsCollection.DeleteMany(context.Background(), bson.D{{}})
return err1, err2
}
func mongodbURI() string {
hostname := os.Getenv("DB_HOSTNAME")
port := os.Getenv("DB_PORT")
username := os.Getenv("DB_USERNAME")
password := os.Getenv("DB_PASSWORD")
if hostname == "" || port == "" || username == "" || password == "" {
log.Error(ErrorEnvVar, "Some environment variables are not available for the DB connection. DB_HOSTNAME, DB_PORT, DB_USERNAME, DB_PASSWORD")
os.Exit(1)
}
return "mongodb://" + username + ":" + password + "@" + hostname + ":" + port + "/?authSource=admin"
}