Spaces:
Sleeping
Sleeping
| const app = require('./app'); | |
| const env = require('./config/env'); | |
| const { query } = require('./config/db'); | |
| const { startReminderPushWorker } = require('./workers/reminderPushWorker'); | |
| function wait(ms) { | |
| return new Promise((resolve) => { | |
| setTimeout(resolve, ms); | |
| }); | |
| } | |
| async function startServer() { | |
| let isDatabaseConnected = false; | |
| const attempts = env.dbRequiredOnStartup ? env.dbConnectRetries + 1 : 1; | |
| let lastDbError = null; | |
| for (let attempt = 1; attempt <= attempts; attempt += 1) { | |
| try { | |
| await query('SELECT 1 AS db_ok'); | |
| isDatabaseConnected = true; | |
| console.log('Database connection established.'); | |
| break; | |
| } catch (error) { | |
| lastDbError = error; | |
| if (attempt >= attempts) { | |
| break; | |
| } | |
| console.warn( | |
| `Database not ready (attempt ${attempt}/${attempts}). Retrying in ${env.dbConnectRetryDelayMs}ms...`, | |
| ); | |
| await wait(env.dbConnectRetryDelayMs); | |
| } | |
| } | |
| if (!isDatabaseConnected) { | |
| if (env.dbRequiredOnStartup) { | |
| throw lastDbError; | |
| } | |
| console.error('Database unavailable at startup; continuing in degraded mode.'); | |
| console.error(lastDbError?.message || lastDbError || 'Unknown DB error'); | |
| } | |
| app.listen(env.port, () => { | |
| console.log( | |
| `Care People backend listening on http://localhost:${env.port}`, | |
| ); | |
| if (isDatabaseConnected) { | |
| startReminderPushWorker(); | |
| } else { | |
| console.log('[push-worker] Skipped startup because database is unavailable.'); | |
| } | |
| }); | |
| } | |
| startServer().catch((error) => { | |
| console.error('Failed to start the backend server.'); | |
| console.error(error); | |
| process.exit(1); | |
| }); | |