Appearance
会话与未读消息 API
认证要求
所有接口需要 JWT 认证,请求头携带 Authorization: Bearer <token>
获取会话列表
获取当前用户的所有会话(每个聊天对象只显示最新一条消息)。
GET /api/conversations/:userId路径参数
| 参数 | 类型 | 必填 | 说明 |
|---|---|---|---|
| userId | string | 是 | 用户 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
}
]
}响应字段说明
| 字段 | 类型 | 说明 |
|---|---|---|
| id | string | 最新消息 ID |
| from_id | string | 消息发送者 ID |
| to_id | string | 消息接收者/群 ID |
| type | string | single(私聊)或 group(群聊) |
| content | string | 最新消息内容 |
| timestamp | integer | 最新消息时间戳(毫秒) |
| content_type | string | 内容类型,如 text |
| chat_partner | string | 聊天对象 ID(私聊为对方用户 ID,群聊为群 ID) |
| partner_name | string | 聊天对象昵称(仅私聊) |
| partner_avatar | string | 聊天对象头像(仅私聊) |
| group_name | string | 群名称(仅群聊) |
| isOnline | number | 对方是否在线,0 或 1(仅私聊) |
| unreadCount | number | 未读消息数 |
错误响应
| code | 说明 |
|---|---|
| 401 | 未认证或 token 无效 |
| 403 | userId 与认证用户不匹配 |
获取未读消息总数
GET /api/unread/total无需额外参数,服务端从 JWT 中提取用户 ID。
响应示例
json
{
"code": 200,
"data": {
"total": 15
}
}清除未读消息计数
清除指定会话的未读消息计数。
POST /api/unread/clear请求体
json
{
"chatId": "user_b"
}| 字段 | 类型 | 必填 | 说明 |
|---|---|---|---|
| chatId | string | 是 | 聊天对象 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() }
);