-
Notifications
You must be signed in to change notification settings - Fork 1
/
message.go
61 lines (55 loc) · 1.6 KB
/
message.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
package mdb
import (
"context"
"fmt"
"github.com/cloudwego/kitex/pkg/klog"
"github.com/hcdoit/tiktok/pkg/consts"
"go.mongodb.org/mongo-driver/bson"
"time"
)
type Message struct {
CreateTime time.Time
IsRead bool
ToUserID int64
FromUserID int64
Content string
}
func GetMessages(ctx context.Context, fromUserID int64, toUserID int64) ([]*Message, error) {
collection := fmt.Sprintf("chat:%d-%d", fromUserID, toUserID)
if toUserID < fromUserID {
collection = fmt.Sprintf("chat:%d-%d", toUserID, fromUserID)
}
klog.Info(collection)
coll := MDB.Database(consts.MongoDataBase).Collection(collection)
cursor, err := coll.Find(ctx, bson.M{"$and": []bson.M{{"isread": false}, {"touserid": fromUserID}}})
if err != nil {
return nil, err
}
messages := make([]*Message, 0)
err = cursor.All(ctx, &messages)
klog.Info(len(messages))
if err != nil {
return nil, err
}
many, err := coll.UpdateMany(ctx, bson.M{"$and": []bson.M{{"isread": false}, {"touserid": fromUserID}}}, bson.M{"$set": bson.M{"isread": true}})
klog.Info(many.UpsertedCount)
if err != nil {
return nil, err
}
return messages, nil
}
func InsertMessage(ctx context.Context, fromUserID int64, toUserID int64, content string) error {
collection := fmt.Sprintf("chat:%d-%d", fromUserID, toUserID)
if toUserID < fromUserID {
collection = fmt.Sprintf("chat:%d-%d", toUserID, fromUserID)
}
coll := MDB.Database(consts.MongoDataBase).Collection(collection)
_, err := coll.InsertOne(ctx, &Message{
CreateTime: time.Now(),
IsRead: false,
ToUserID: toUserID,
FromUserID: fromUserID,
Content: content,
})
return err
}