fix: implement persistent MongoDB connections and resolve race conditions

- Replace connect/disconnect pattern with persistent connection pool
- Add explicit database initialization on server startup
- Remove all dbDisconnect() calls from API endpoints to prevent race conditions
- Fix MongoNotConnectedError when scheduler runs concurrently with API requests
- Add connection pooling with proper MongoDB driver options
- Add safety check for recipes array in favorites utility

🤖 Generated with [Claude Code](https://claude.ai/code)

Co-Authored-By: Claude <noreply@anthropic.com>
This commit is contained in:
2025-09-14 19:53:55 +02:00
parent 08d7d8541b
commit c8e542eec8
28 changed files with 198 additions and 111 deletions

View File

@@ -7,11 +7,21 @@ import { AUTHENTIK_ID, AUTHENTIK_SECRET, AUTHENTIK_ISSUER } from "$env/static/pr
import { sequence } from "@sveltejs/kit/hooks"
import * as auth from "./auth"
import { initializeScheduler } from "./lib/server/scheduler"
import { dbConnect } from "./utils/db"
import fs from 'fs'
import path from 'path'
// Initialize the recurring payment scheduler
initializeScheduler();
// Initialize database connection on server startup
console.log('🚀 Server starting - initializing database connection...');
await dbConnect().then(() => {
console.log('✅ Database connected successfully');
// Initialize the recurring payment scheduler after DB is ready
initializeScheduler();
console.log('✅ Recurring payment scheduler initialized');
}).catch((error) => {
console.error('❌ Failed to connect to database on startup:', error);
// Don't crash the server - API routes will attempt reconnection
});
async function authorization({ event, resolve }) {
const session = await event.locals.auth();