这是根治方案 B: 1. 添加 GET /api/messages 端点从数据库获取消息 2. 在 onFinish 后延迟 500ms,然后从数据库重新加载消息 3. 更新 setMessages 和清空 appendedMessages 这确保了 data-appendMessage 保存到数据库的消息能正确显示 Co-authored-by: Cursor <cursoragent@cursor.com>
104 lines
2.7 KiB
TypeScript
104 lines
2.7 KiB
TypeScript
import { NextRequest, NextResponse } from "next/server";
|
|
import { auth } from "@/app/(auth)/auth";
|
|
import { saveMessages, getMessagesByChatId } from "@/lib/db/queries";
|
|
import type { DBMessage } from "@/lib/db/schema";
|
|
|
|
/**
|
|
* 获取聊天消息
|
|
* 用于从数据库重新加载消息
|
|
*/
|
|
export async function GET(request: NextRequest) {
|
|
try {
|
|
const session = await auth();
|
|
|
|
if (!session?.user?.id) {
|
|
return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
|
|
}
|
|
|
|
const chatId = request.nextUrl.searchParams.get("chatId");
|
|
|
|
if (!chatId) {
|
|
return NextResponse.json(
|
|
{ error: "Missing required parameter: chatId" },
|
|
{ status: 400 }
|
|
);
|
|
}
|
|
|
|
// 从数据库获取消息
|
|
const messages = await getMessagesByChatId({ id: chatId });
|
|
|
|
// 转换为前端格式
|
|
const formattedMessages = messages.map((msg: DBMessage) => {
|
|
const parts = msg.parts as any[] || [];
|
|
const firstPart = parts[0] as any;
|
|
return {
|
|
id: msg.id,
|
|
role: msg.role,
|
|
content: firstPart?.text || "",
|
|
createdAt: msg.createdAt,
|
|
parts: parts,
|
|
attachments: msg.attachments || [],
|
|
};
|
|
});
|
|
|
|
return NextResponse.json({ messages: formattedMessages });
|
|
} catch (error) {
|
|
console.error("[Messages API] GET Error:", error);
|
|
return NextResponse.json(
|
|
{ error: "Failed to get messages" },
|
|
{ status: 500 }
|
|
);
|
|
}
|
|
}
|
|
|
|
/**
|
|
* 保存消息到数据库的API
|
|
* 用于图片处理等场景中保存助手回复消息
|
|
*/
|
|
export async function POST(request: NextRequest) {
|
|
try {
|
|
const session = await auth();
|
|
|
|
if (!session?.user?.id) {
|
|
return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
|
|
}
|
|
|
|
const body = await request.json();
|
|
const { chatId, message } = body;
|
|
|
|
if (!chatId || !message) {
|
|
return NextResponse.json(
|
|
{ error: "Missing required fields: chatId and message" },
|
|
{ status: 400 }
|
|
);
|
|
}
|
|
|
|
// 构造DBMessage对象
|
|
const dbMessage: DBMessage = {
|
|
id: message.id,
|
|
chatId,
|
|
role: message.role || "assistant",
|
|
parts: message.parts || [],
|
|
attachments: message.attachments || [],
|
|
createdAt: message.createdAt ? new Date(message.createdAt) : new Date(),
|
|
videoStorageStatus: null,
|
|
temporaryVideoUrl: null,
|
|
permanentVideoUrl: null,
|
|
archivedAt: null,
|
|
videoMetadata: null,
|
|
};
|
|
|
|
// 保存消息到数据库
|
|
await saveMessages({ messages: [dbMessage] });
|
|
|
|
return NextResponse.json({ success: true });
|
|
} catch (error) {
|
|
console.error("[Messages API] Error:", error);
|
|
return NextResponse.json(
|
|
{ error: "Failed to save message" },
|
|
{ status: 500 }
|
|
);
|
|
}
|
|
}
|
|
|