Files
frontend/src/stores/message/services/MessageSendService.ts

110 lines
3.2 KiB
TypeScript
Raw Normal View History

/**
*
*
*/
import type { MessageResponse, MessageSegment, ConversationResponse } from '../../../types/dto';
2026-04-13 01:30:37 +08:00
import { messageService } from '@/services/message';
import { messageRepository } from '@/database';
import type { IMessageSendService } from '../types';
import { useMessageStore, mergeMessagesById } from '../store';
export class MessageSendService implements IMessageSendService {
private getCurrentUserId: () => string | null;
constructor(getCurrentUserId: () => string | null) {
this.getCurrentUserId = getCurrentUserId;
}
/**
*
*/
async sendMessage(
conversationId: string,
segments: MessageSegment[],
options?: { replyToId?: string }
): Promise<MessageResponse | null> {
const store = useMessageStore.getState();
try {
// 调用API发送
const response = await messageService.sendMessage(conversationId, {
segments,
reply_to_id: options?.replyToId,
});
if (response) {
const currentUserId = this.getCurrentUserId();
// 添加到本地消息列表
const existingMessages = store.getMessages(conversationId);
const newMessage: MessageResponse = {
id: response.id,
conversation_id: conversationId,
sender_id: currentUserId || '',
seq: response.seq,
segments,
created_at: new Date().toISOString(),
status: 'normal',
};
const updatedMessages = mergeMessagesById(existingMessages, [newMessage]);
store.setMessages(conversationId, updatedMessages);
// 更新会话最后消息
this.updateConversationWithNewMessage(conversationId, newMessage);
// 保存到本地数据库
const textContent = segments
?.filter((s: any) => s.type === 'text')
.map((s: any) => s.data?.text || '')
.join('') || '';
messageRepository.saveMessage({
id: response.id,
conversationId,
senderId: currentUserId || '',
content: textContent,
type: segments?.find((s: any) => s.type === 'image') ? 'image' : 'text',
isRead: true,
createdAt: newMessage.created_at,
seq: response.seq,
status: 'normal',
segments,
}).catch(console.error);
return newMessage;
}
return null;
} catch (error) {
console.error('[MessageSendService] 发送消息失败:', error);
return null;
}
}
/**
*
*/
private updateConversationWithNewMessage(
conversationId: string,
message: MessageResponse
): void {
const store = useMessageStore.getState();
const conversation = store.getConversation(conversationId);
const createdAt = message.created_at || new Date().toISOString();
if (conversation) {
// 更新现有会话
const updatedConv: ConversationResponse = {
...conversation,
last_seq: message.seq,
last_message: message,
last_message_at: createdAt,
updated_at: createdAt,
};
store.updateConversation(updatedConv);
}
}
}