KnowledgeBase_frontend/src/store/chat/chat.messages.thunks.js

46 lines
1.3 KiB
JavaScript

import { createAsyncThunk } from '@reduxjs/toolkit';
import { get, post } from '../../services/api';
/**
* 获取聊天消息
* @param {string} chatId - 聊天ID
*/
export const fetchMessages = createAsyncThunk('chat/fetchMessages', async (chatId, { rejectWithValue }) => {
try {
const response = await get(`/chat-history/${chatId}/messages/`);
// 处理返回格式
if (response && response.code === 200) {
return response.data.messages;
}
return response.data?.messages || [];
} catch (error) {
return rejectWithValue(error.response?.data || 'Failed to fetch messages');
}
});
/**
* 发送聊天消息
* @param {Object} params - 消息参数
* @param {string} params.chatId - 聊天ID
* @param {string} params.content - 消息内容
*/
export const sendMessage = createAsyncThunk('chat/sendMessage', async ({ chatId, content }, { rejectWithValue }) => {
try {
const response = await post(`/chat-history/${chatId}/messages/`, {
content,
type: 'text',
});
// 处理返回格式
if (response && response.code === 200) {
return response.data;
}
return response.data || {};
} catch (error) {
return rejectWithValue(error.response?.data || 'Failed to send message');
}
});