Your Name 1fd0db078a
Some checks failed
Lint / build (20) (push) Has been cancelled
Playwright Tests / test (push) Has been cancelled
修复生图结果消息被覆盖不显示
2026-02-07 20:57:57 +08:00

113 lines
2.9 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 const dynamic = "force-dynamic";
export const revalidate = 0;
/**
* 获取聊天消息
* 用于从数据库重新加载消息
*/
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 },
{
headers: {
"Cache-Control": "no-store, max-age=0",
},
}
);
} 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 }
);
}
}