刘嘉昕 | 9cdeca2 | 2025-06-03 16:54:30 +0800 | [diff] [blame^] | 1 | import axios from 'axios'; |
| 2 | |
| 3 | const BASE_URL = 'http://localhost:8080/chat'; // 根据你的后端接口地址调整 |
| 4 | |
| 5 | // 发送消息 |
| 6 | export const sendMessage = async ({ senderId, receiverId, content }) => { |
| 7 | const now = new Date().toISOString(); // 发送时间 |
| 8 | |
| 9 | // 构造后端需要的格式,chatimformation1 或 chatimformation2 中只有一个有值 |
| 10 | const payload = { |
| 11 | friend1: senderId, |
| 12 | friend2: receiverId, |
| 13 | talkTime: now, |
| 14 | chatimformation1: senderId < receiverId ? content : null, // 约定较小 ID 为 friend1 发送的消息 |
| 15 | chatimformation2: senderId > receiverId ? content : null, |
| 16 | }; |
| 17 | |
| 18 | const response = await axios.post(`${BASE_URL}/create`, payload); |
| 19 | return response.data; |
| 20 | }; |
| 21 | |
| 22 | // 获取两个用户之间的聊天记录 |
| 23 | export const getMessagesByUserIds = async (senderId, receiverId) => { |
| 24 | const response = await axios.get(`${BASE_URL}/between`, { |
| 25 | params: { |
| 26 | user1: senderId, |
| 27 | user2: receiverId, |
| 28 | } |
| 29 | }); |
| 30 | return response.data; |
| 31 | }; |
| 32 | |
| 33 | // 可选:获取某用户与所有人的聊天记录(如果你后续需要聊天列表用) |
| 34 | export const getChatsByUser = async (userId) => { |
| 35 | const response = await axios.get(`${BASE_URL}/user/${userId}`); |
| 36 | return response.data; |
| 37 | }; |