/
notifications.go
84 lines (78 loc) · 2.74 KB
/
notifications.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
package mongo
import (
"context"
"math/rand"
"time"
"go.mongodb.org/mongo-driver/bson"
)
func (ms *MongoStorage) AddNotifications(nType NotificationType, electionID string,
userID, authorID, communityID uint64, username, authorUsername, communityName,
frameURL, customText string, deadline time.Time,
) (int64, error) {
// create random id for the notification
src := rand.NewSource(time.Now().UnixNano())
rnd := rand.New(src)
randomID := rnd.Int63()
// create notification
notification := Notification{
ID: randomID,
Type: nType,
ElectionID: electionID,
UserID: userID,
Username: username,
AuthorID: authorID,
AuthorUsername: authorUsername,
CommunityID: communityID,
CommunityName: communityName,
FrameUrl: frameURL,
CustomText: customText,
Deadline: deadline,
}
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
res, err := ms.notifications.InsertOne(ctx, notification)
if err != nil {
return 0, err
}
return res.InsertedID.(int64), nil
}
// SetNotificationDeadline sets the deadline for the notification with the
// specified ID. If an error occurs, it returns the error.
func (ms *MongoStorage) SetNotificationDeadline(notificationID int64, deadline time.Time) error {
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
_, err := ms.notifications.UpdateOne(ctx, bson.M{"_id": notificationID},
bson.M{"$set": bson.M{"deadline": deadline}})
return err
}
// LastNotifications returns the registered notifications in the database ordered
// by the _id field in descending order and limited to the specified number of
// results. If an error occurs, it returns the error.
func (ms *MongoStorage) LastNotifications(maxResults int) ([]Notification, error) {
// Creating a context with timeout
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
// Executing the find operation with the specified filter and options
cursor, err := ms.notifications.Find(ctx, bson.D{})
if err != nil {
return nil, err
}
defer cursor.Close(ctx)
// Iterating through the cursor to decode the results
notifications := []Notification{}
if err := cursor.All(ctx, ¬ifications); err != nil {
return nil, err
}
if err := cursor.Err(); err != nil {
return nil, err
}
return notifications, nil
}
// RemoveNotification removes the notification with the specified ID from the
// database. If an error occurs, it returns the error.
func (ms *MongoStorage) RemoveNotification(notificationID int64) error {
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
_, err := ms.notifications.DeleteOne(ctx, bson.M{"_id": notificationID})
return err
}