搜索好友接口优化

This commit is contained in:
2025-12-10 15:19:26 +08:00
parent 041d22c382
commit b189251a6f
2 changed files with 94 additions and 21 deletions

View File

@@ -43,7 +43,7 @@ func ContactListHandler(c *gin.Context) {
/**
* SearchUsersHandler
* 功能:搜索用户
* 功能:搜索用户(返回带有 is_friend 标识的结果)
* 路径GET /api/contacts/search
*/
func SearchUsersHandler(c *gin.Context) {
@@ -58,18 +58,25 @@ func SearchUsersHandler(c *gin.Context) {
limit = 20
}
users, err := service.ContactSvc.SearchUsers(keyword, limit)
// 获取当前用户ID用于判断好友关系
var currentUserID string
if userID, exists := c.Get("user_id"); exists {
currentUserID = userID.(string)
}
// 调用服务层搜索用户
result, err := service.ContactSvc.SearchUsersWithFriendStatus(currentUserID, keyword, limit)
if err != nil {
utils.InternalError(c, "搜索失败")
return
}
// 确保返回空数组而不是null
if users == nil {
users = []model.User{}
if result == nil {
result = []map[string]interface{}{}
}
utils.SuccessWithData(c, users, "搜索成功")
utils.SuccessWithData(c, result, "搜索成功")
}
/**
@@ -79,7 +86,7 @@ func SearchUsersHandler(c *gin.Context) {
*/
func AddFriendHandler(c *gin.Context) {
userID, _ := c.Get("user_id")
var req struct {
ToUserID string `json:"to_user_id" binding:"required"`
Message string `json:"message"`
@@ -272,31 +279,20 @@ func DeleteGroupHandler(c *gin.Context) {
/**
* GetContactDetailHandler
* 功能:获取好友详情
* 功能:获取用户详情(包含好友关系)
* 路径GET /api/contacts/:id
*/
func GetContactDetailHandler(c *gin.Context) {
userID, _ := c.Get("user_id")
contactID := c.Param("id")
contact, err := service.ContactSvc.GetContactDetail(userID.(string), contactID)
if err != nil {
utils.NotFound(c, "好友不存在")
return
}
// 获取联系人用户信息
user, err := service.UserSvc.GetUserByID(contactID)
// 调用服务层获取用户详情(包含好友关系)
result, err := service.ContactSvc.GetUserDetailWithFriendStatus(userID.(string), contactID)
if err != nil {
utils.NotFound(c, "用户不存在")
return
}
result := map[string]interface{}{
"contact": contact,
"user": user,
}
utils.SuccessWithData(c, result, "获取成功")
}
@@ -359,4 +355,3 @@ func DeleteContactHandler(c *gin.Context) {
utils.Success(c, "已删除好友")
}