31 lines
714 B
TypeScript
31 lines
714 B
TypeScript
import { MongoClient, type Db } from "mongodb";
|
|
|
|
let client: MongoClient | null = null;
|
|
let db: Db | null = null;
|
|
|
|
export async function getDb(): Promise<Db> {
|
|
if (db) return db;
|
|
|
|
const uri = useRuntimeConfig().db;
|
|
if (!uri) throw new Error("NUXT_DB is not configured");
|
|
|
|
client = new MongoClient(uri);
|
|
await client.connect();
|
|
db = client.db("vat-api");
|
|
|
|
// Create indexes for the requests collection
|
|
const requests = db.collection("requests");
|
|
await requests.createIndex({ timestamp: -1 });
|
|
await requests.createIndex({ ip: 1, timestamp: -1 });
|
|
|
|
return db;
|
|
}
|
|
|
|
export async function closeDb(): Promise<void> {
|
|
if (client) {
|
|
await client.close();
|
|
client = null;
|
|
db = null;
|
|
}
|
|
}
|