Spaces:
Build error
Build error
| import type { NextApiRequest, NextApiResponse } from "next" | |
| import fs from "fs" | |
| import path from "path" | |
| const CHAT_HISTORY_FILE = path.join(process.cwd(), "chat-history.json") | |
| interface ChatMessage { | |
| id: string | |
| role: "user" | "assistant" | |
| content: string | |
| timestamp: number | |
| model?: string | |
| } | |
| interface ChatHistory { | |
| messages: ChatMessage[] | |
| } | |
| // Read chat history from file | |
| function readChatHistory(): ChatHistory { | |
| try { | |
| if (fs.existsSync(CHAT_HISTORY_FILE)) { | |
| const data = fs.readFileSync(CHAT_HISTORY_FILE, "utf-8") | |
| return JSON.parse(data) | |
| } | |
| } catch (error) { | |
| console.error("Error reading chat history:", error) | |
| } | |
| return { messages: [] } | |
| } | |
| // Write chat history to file | |
| function writeChatHistory(history: ChatHistory): void { | |
| try { | |
| fs.writeFileSync(CHAT_HISTORY_FILE, JSON.stringify(history, null, 2)) | |
| } catch (error) { | |
| console.error("Error writing chat history:", error) | |
| } | |
| } | |
| export default async function handler( | |
| req: NextApiRequest, | |
| res: NextApiResponse | |
| ) { | |
| if (req.method === "GET") { | |
| // Get chat history | |
| const history = readChatHistory() | |
| return res.status(200).json(history) | |
| } else if (req.method === "POST") { | |
| // Add message to chat history | |
| const { message } = req.body as { message: ChatMessage } | |
| if (!message || !message.role || !message.content) { | |
| return res.status(400).json({ error: "Invalid message format" }) | |
| } | |
| const history = readChatHistory() | |
| history.messages.push(message) | |
| writeChatHistory(history) | |
| return res.status(200).json({ success: true }) | |
| } else if (req.method === "DELETE") { | |
| // Clear chat history | |
| writeChatHistory({ messages: [] }) | |
| return res.status(200).json({ success: true }) | |
| } else { | |
| return res.status(405).json({ error: "Method not allowed" }) | |
| } | |
| } |