feat: 对接 PostgreSQL 存储层
This commit is contained in:
@@ -12,19 +12,23 @@ import (
|
||||
apperr "github.com/hhs/camtalk/internal/errors"
|
||||
"github.com/hhs/camtalk/internal/models"
|
||||
"github.com/hhs/camtalk/internal/session"
|
||||
"github.com/hhs/camtalk/internal/store"
|
||||
)
|
||||
|
||||
// ConversationHandler 提供对话相关的 REST 端点。
|
||||
type ConversationHandler struct {
|
||||
sessionMgr session.Manager
|
||||
tokenMgr *auth.TokenManager
|
||||
msgRepo store.MessageRepository // 可选,为 nil 时 fallback 到内存查询
|
||||
}
|
||||
|
||||
// NewConversationHandler 创建 ConversationHandler。
|
||||
func NewConversationHandler(sessionMgr session.Manager, tokenMgr *auth.TokenManager) *ConversationHandler {
|
||||
// msgRepo 可选,为 nil 时消息查询走内存。
|
||||
func NewConversationHandler(sessionMgr session.Manager, tokenMgr *auth.TokenManager, msgRepo store.MessageRepository) *ConversationHandler {
|
||||
return &ConversationHandler{
|
||||
sessionMgr: sessionMgr,
|
||||
tokenMgr: tokenMgr,
|
||||
msgRepo: msgRepo,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -215,7 +219,7 @@ func (h *ConversationHandler) Delete(c *gin.Context) {
|
||||
//
|
||||
// 查询参数:
|
||||
// - limit: 返回消息数量上限,默认 50
|
||||
// - before: 消息偏移量(用于分页),返回此偏移量之前的消息
|
||||
// - before: 消息 ID 游标(用于分页),返回此 ID 之前的消息
|
||||
func (h *ConversationHandler) GetMessages(c *gin.Context) {
|
||||
sessionID := c.Param("id")
|
||||
|
||||
@@ -229,9 +233,27 @@ func (h *ConversationHandler) GetMessages(c *gin.Context) {
|
||||
limit = 50
|
||||
}
|
||||
|
||||
before, _ := strconv.Atoi(c.DefaultQuery("before", "0"))
|
||||
beforeID, _ := strconv.ParseInt(c.DefaultQuery("before", "0"), 10, 64)
|
||||
|
||||
// 获取全量历史(内存实现中 history 是全量存储的)
|
||||
// 优先从 PostgreSQL 查询(支持持久化后的全量历史)
|
||||
if h.msgRepo != nil {
|
||||
messages, err := h.msgRepo.GetMessages(c.Request.Context(), sessionID, limit, beforeID)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{
|
||||
"code": apperr.CodeInternalError,
|
||||
"message": "failed to get messages",
|
||||
})
|
||||
return
|
||||
}
|
||||
count, _ := h.msgRepo.GetMessageCount(c.Request.Context(), sessionID)
|
||||
c.JSON(http.StatusOK, gin.H{
|
||||
"messages": messages,
|
||||
"total": count,
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
// fallback:从内存查询
|
||||
allMessages, err := h.sessionMgr.GetHistory(c.Request.Context(), sessionID, 0)
|
||||
if err != nil {
|
||||
if errors.Is(err, session.ErrSessionNotFound) {
|
||||
@@ -250,9 +272,9 @@ func (h *ConversationHandler) GetMessages(c *gin.Context) {
|
||||
|
||||
total := len(allMessages)
|
||||
|
||||
// before > 0 表示取 before 之前的消息(不含 before 位置)
|
||||
if before > 0 && before <= total {
|
||||
allMessages = allMessages[:before]
|
||||
// beforeID > 0 时表示偏移量(兼容旧接口语义)
|
||||
if beforeID > 0 && int(beforeID) <= total {
|
||||
allMessages = allMessages[:beforeID]
|
||||
}
|
||||
|
||||
// 取最后 limit 条
|
||||
|
||||
Reference in New Issue
Block a user