fix(api): add validation for listing and seller in bid route feat(telemetry): add userId to MarketTelemetry style(globe): add null check for canvas element chore: add lint:fix script to package.json
82 lines
1.7 KiB
TypeScript
82 lines
1.7 KiB
TypeScript
/**
|
|
* Conexão MongoDB usando Mongoose
|
|
* Singleton pattern para reutilizar conexão
|
|
*/
|
|
|
|
import mongoose from "mongoose";
|
|
|
|
function getMongoUrl(): string {
|
|
const url = process.env.MONGO_URL;
|
|
if (!url) {
|
|
throw new Error("MONGO_URL não está definida nas variáveis de ambiente");
|
|
}
|
|
return url;
|
|
}
|
|
|
|
interface MongooseCache {
|
|
conn: typeof mongoose | null;
|
|
promise: Promise<typeof mongoose> | null;
|
|
}
|
|
|
|
// Cache global para Next.js (evita múltiplas conexões em hot reload)
|
|
declare global {
|
|
// eslint-disable-next-line no-var
|
|
var mongoose: MongooseCache | undefined;
|
|
}
|
|
|
|
const cached: MongooseCache = global.mongoose || { conn: null, promise: null };
|
|
|
|
if (!global.mongoose) {
|
|
global.mongoose = cached;
|
|
}
|
|
|
|
/**
|
|
* Conecta ao MongoDB ou retorna conexão existente
|
|
*/
|
|
export async function connectMongoDB(): Promise<typeof mongoose> {
|
|
if (cached.conn) {
|
|
return cached.conn;
|
|
}
|
|
|
|
if (!cached.promise) {
|
|
const opts = {
|
|
bufferCommands: false,
|
|
maxPoolSize: 10,
|
|
serverSelectionTimeoutMS: 5000,
|
|
socketTimeoutMS: 45000,
|
|
};
|
|
|
|
cached.promise = mongoose
|
|
.connect(getMongoUrl(), opts)
|
|
.then((mongoose) => {
|
|
// Conexão MongoDB estabelecida (log desabilitado)
|
|
return mongoose;
|
|
})
|
|
.catch((error) => {
|
|
console.error("❌ Erro ao conectar MongoDB:", error);
|
|
cached.promise = null;
|
|
throw error;
|
|
});
|
|
}
|
|
|
|
try {
|
|
cached.conn = await cached.promise;
|
|
} catch (e) {
|
|
cached.promise = null;
|
|
throw e;
|
|
}
|
|
|
|
return cached.conn;
|
|
}
|
|
|
|
/**
|
|
* Desconecta do MongoDB (útil para testes)
|
|
*/
|
|
export async function disconnectMongoDB(): Promise<void> {
|
|
if (cached.conn) {
|
|
await mongoose.disconnect();
|
|
cached.conn = null;
|
|
cached.promise = null;
|
|
}
|
|
}
|