Files
customer-server/dao/session_dao.go
2026-03-14 10:02:49 +08:00

100 lines
2.5 KiB
Go
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
package dao
import (
"context"
"customer-server/model/entity"
"gitea.com/red-future/common/db/mongo"
"github.com/gogf/gf/v2/os/gtime"
"go.mongodb.org/mongo-driver/v2/bson"
"go.mongodb.org/mongo-driver/v2/mongo/options"
)
var Session = new(session)
type session struct{}
// Upsert 更新或插入会话(根据 userId + sessionId
// 注意:消费者调用,无 HTTP 上下文,直接使用原生 MongoDB 操作
func (d *session) Upsert(ctx context.Context, data *entity.Session) (err error) {
filter := bson.M{
"userId": data.UserId,
"sessionId": data.SessionId,
"isDeleted": false,
}
now := gtime.Now().Time
update := bson.M{
"$set": bson.M{
"platform": data.Platform,
"status": data.Status,
"lastActiveAt": data.LastActiveAt,
"updater": "system",
"updatedAt": now,
},
"$inc": bson.M{
"messageCount": 1,
},
"$setOnInsert": bson.M{
"creator": "system",
"createdAt": now,
"isDeleted": false,
},
}
opts := options.UpdateOne().SetUpsert(true)
_, err = mongo.GetDB().Collection(entity.SessionCollection).UpdateOne(ctx, filter, update, opts)
return
}
// Archive 归档会话
// 注意:消费者调用,无 HTTP 上下文,直接使用原生 MongoDB 操作
func (d *session) Archive(ctx context.Context, userId, sessionId string) (err error) {
filter := bson.M{
"userId": userId,
"sessionId": sessionId,
"isDeleted": false,
}
now := gtime.Now().Time
update := bson.M{
"$set": bson.M{
"status": entity.SessionStatusArchived,
"archivedAt": now,
"updater": "system",
"updatedAt": now,
},
}
_, err = mongo.GetDB().Collection(entity.SessionCollection).UpdateOne(ctx, filter, update)
return
}
// FindByUserId 根据用户ID查询会话列表
func (d *session) FindByUserId(ctx context.Context, userId string, limit int64) (list []*entity.Session, err error) {
filter := bson.M{"userId": userId, "isDeleted": false}
opts := options.Find().SetSort(bson.D{{Key: "lastActiveAt", Value: -1}}).SetLimit(limit)
cursor, err := mongo.GetDB().Collection(entity.SessionCollection).Find(ctx, filter, opts)
if err != nil {
return
}
defer cursor.Close(ctx)
err = cursor.All(ctx, &list)
return
}
// FindActiveByUserId 查询用户活跃会话
func (d *session) FindActiveByUserId(ctx context.Context, userId string) (data *entity.Session, err error) {
filter := bson.M{
"userId": userId,
"status": entity.SessionStatusActive,
"isDeleted": false,
}
err = mongo.GetDB().Collection(entity.SessionCollection).FindOne(ctx, filter).Decode(&data)
return
}