Files
2025-09-28 19:18:40 +08:00

77 lines
2.1 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 getnotifications
import (
"fmt"
"github.com/gin-gonic/gin"
"net/http"
"strconv"
"time"
"toutoukan/init/databaseInit"
)
type Notification struct {
// ⭐️ 新增: 主键 id
ID uint `gorm:"primaryKey" json:"id"` // GORM 会自动识别为自增主键
SenderID string `json:"sender_id"`
ReceiverID string `json:"receiver_id"`
Status int8 `json:"status"`
Sequence string `json:"sequence"`
CreatedAt time.Time `json:"created_at"`
Content string `json:"content"`
IsRead int8 `json:"is_read"`
MsgType string `json:"msg_type"`
Target string `json:"target"`
}
// TableName 指定 GORM 使用的表名
func (Notification) TableName() string {
return "user_msg"
}
type UidRequest struct {
Uid string `json:"uid" binding:"required"` // binding:"required" 确保 uid 字段必须存在
}
// --- Gin Handler ---
// GetNotifications 使用 GORM 进行数据库查询
func GetNotifications(c *gin.Context) {
// 1. 从请求 Body 中获取 uid
var requestBody UidRequest
if err := c.ShouldBindJSON(&requestBody); err != nil {
// 如果 JSON 格式不正确或缺少 uid 字段ShouldBindJSON 会返回错误
c.JSON(http.StatusBadRequest, gin.H{"message": "请求参数错误: " + err.Error()})
return
}
userID := requestBody.Uid
// 2. 获取分页参数 (这部分逻辑不变)
page, _ := strconv.Atoi(c.DefaultQuery("page", "1"))
limit, _ := strconv.Atoi(c.DefaultQuery("limit", "20"))
offset := (page - 1) * limit
// 3. 准备用于接收结果的切片
var notifications []Notification
// 4. 使用 GORM 进行链式查询 (这部分逻辑不变)
result := databaseInit.UserDB.
Where("receiver_id = ?", userID).
Order("created_at DESC").
Limit(limit).
Offset(offset).
Find(&notifications)
// 5. GORM 的错误处理 (这部分逻辑不变)
if result.Error != nil {
c.JSON(http.StatusInternalServerError, gin.H{"message": fmt.Sprintf("查询数据库失败: %v", result.Error)})
return
}
// 6. 返回 JSON 响应 (这部分逻辑不变)
c.JSON(http.StatusOK, gin.H{
"data": notifications,
"message": "获取消息列表成功",
"success": true,
})
}