Spaces:
No application file
No application file
| import { MongoClient, type Db, type Collection } from "mongodb" | |
| let client: MongoClient | |
| let db: Db | |
| let messagesCollection: Collection | |
| const MONGODB_URI = process.env.MONGODB_URI! | |
| const DB_NAME = "deep_rebuild" | |
| export async function connectToMongoDB() { | |
| if (!client) { | |
| client = new MongoClient(MONGODB_URI) | |
| await client.connect() | |
| db = client.db(DB_NAME) | |
| messagesCollection = db.collection("messages") | |
| } | |
| return { client, db, messagesCollection } | |
| } | |
| export async function saveMessageToMongoDB(message: any) { | |
| try { | |
| const { messagesCollection } = await connectToMongoDB() | |
| return await messagesCollection.insertOne({ | |
| ...message, | |
| timestamp: new Date(), | |
| _id: undefined, // Let MongoDB generate the ID | |
| }) | |
| } catch (error) { | |
| console.error("MongoDB save error:", error) | |
| throw error | |
| } | |
| } | |
| export async function getMessagesFromMongoDB(limit = 50) { | |
| try { | |
| const { messagesCollection } = await connectToMongoDB() | |
| return await messagesCollection.find({}).sort({ timestamp: -1 }).limit(limit).toArray() | |
| } catch (error) { | |
| console.error("MongoDB fetch error:", error) | |
| throw error | |
| } | |
| } | |