Files
fabrikanabytok/apps/fabrikanabytok/lib/db/mongodb.ts
2025-11-28 20:47:00 +01:00

58 lines
1.4 KiB
TypeScript

/**
* MongoDB Connection Manager
*
* SERVER-ONLY MODULE
* This file should ONLY be imported in:
* - Server Components (without 'use client')
* - Server Actions (with 'use server')
* - API Routes
*
* NEVER import in client components
*
* All client components access data through Server Actions
*/
import { MongoClient, type Db } from "mongodb"
const uri = process.env.MONGODB_URI || "mongodb://localhost:27017/fabrika_nabytok"
const options = {}
let client: MongoClient
let clientPromise: Promise<MongoClient>
declare global {
var _mongoClientPromise: Promise<MongoClient> | undefined
}
if (process.env.NODE_ENV === "development") {
if (!global._mongoClientPromise) {
client = new MongoClient(uri, options)
global._mongoClientPromise = client.connect()
}
clientPromise = global._mongoClientPromise
} else {
client = new MongoClient(uri, options)
clientPromise = client.connect()
}
export default clientPromise
export async function getDb(): Promise<Db> {
const client = await clientPromise
return client.db(process.env.MONGODB_DB || "fabrika_nabytok")
}
export async function checkDatabaseConnection(): Promise<boolean> {
try {
const client = await clientPromise
await client.db().admin().ping()
return true
} catch (error) {
console.error("[MongoDB] Connection failed:", error)
return false
}
}
export async function getClient(): Promise<MongoClient> {
return await clientPromise
}