import { MongoClient } from "mongodb"; // BidaAngMamamayan — local Mongo on the site's own box, db "bama". // No auth: the site is public and the data is a public news cache + an // open community board. bindIp 127.0.0.1 keeps it off the wire. const uri = process.env.MONGODB_URI || "mongodb://127.0.0.1:27017/bama"; const client = new MongoClient(uri, { serverSelectionTimeoutMS: 8000, }); let cached = global.__bama_mongo; if (!cached) { cached = global.__bama_mongo = { client, promise: null }; } export const DB_NAME = process.env.BAMA_DB_NAME || "bama"; export async function getDb() { if (!cached.promise) { cached.promise = cached.client.connect(); } const c = await cached.promise; return c.db(DB_NAME); } // One-shot scripts (db-reset, the digest trigger) need the client to close so // the process actually exits. export async function closeDb() { if (!cached.client) return; try { await cached.client.close(); } finally { cached.client = null; cached.promise = null; if (global.__bama_mongo === cached) delete global.__bama_mongo; } } export async function getCollections() { const db = await getDb(); return { // Crawled news (the shared pool — one site, one public edition). stories: db.collection("stories"), // Community board ("Thank you Senator BAM"). board: db.collection("board"), // Rate-limit counters (board spam control). rate: db.collection("rate"), }; }