Skip to content

会话与未读消息 API

认证要求

所有接口需要 JWT 认证,请求头携带 Authorization: Bearer <token>

获取会话列表

获取当前用户的所有会话(每个聊天对象只显示最新一条消息)。

GET /api/conversations/:userId

路径参数

参数类型必填说明
userIdstring用户 ID(必须与认证用户一致,否则返回 403)

响应示例

json
{
  "code": 200,
  "data": [
    {
      "id": "msg_001",
      "from_id": "user_a",
      "to_id": "user_b",
      "type": "single",
      "content": "你好",
      "timestamp": 1719820800000,
      "content_type": "text",
      "chat_partner": "user_b",
      "partner_name": "小明",
      "partner_avatar": "https://example.com/avatar.png",
      "isOnline": 1,
      "unreadCount": 3
    },
    {
      "id": "msg_002",
      "from_id": "user_a",
      "to_id": "group_001",
      "type": "group",
      "content": "大家好",
      "timestamp": 1719820700000,
      "content_type": "text",
      "chat_partner": "group_001",
      "group_name": "技术交流群",
      "unreadCount": 12
    }
  ]
}

响应字段说明

字段类型说明
idstring最新消息 ID
from_idstring消息发送者 ID
to_idstring消息接收者/群 ID
typestringsingle(私聊)或 group(群聊)
contentstring最新消息内容
timestampinteger最新消息时间戳(毫秒)
content_typestring内容类型,如 text
chat_partnerstring聊天对象 ID(私聊为对方用户 ID,群聊为群 ID)
partner_namestring聊天对象昵称(仅私聊)
partner_avatarstring聊天对象头像(仅私聊)
group_namestring群名称(仅群聊)
isOnlinenumber对方是否在线,01(仅私聊)
unreadCountnumber未读消息数

错误响应

code说明
401未认证或 token 无效
403userId 与认证用户不匹配

获取未读消息总数

GET /api/unread/total

无需额外参数,服务端从 JWT 中提取用户 ID。

响应示例

json
{
  "code": 200,
  "data": {
    "total": 15
  }
}

清除未读消息计数

清除指定会话的未读消息计数。

POST /api/unread/clear

请求体

json
{
  "chatId": "user_b"
}
字段类型必填说明
chatIdstring聊天对象 ID(私聊为对方用户 ID,群聊为群 ID)

响应示例

json
{
  "code": 200,
  "message": "Unread cleared"
}

前端调用示例

javascript
// 获取会话列表
this.middle.get(
  config.imBaseURL + '/conversations/' + userId,
  {},
  { header: this.getImHeader() }
).then(res => {
  if (res.code === 200) {
    this.conversations = res.data;
  }
});

// 进入聊天时清除未读
this.middle.post(
  config.imBaseURL + '/unread/clear',
  { chatId: chatPartnerId },
  { header: this.getImHeader() }
);