File size: 1,155 Bytes
12b432a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
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
  }
}