diff --git a/initialProject/lib/seedDatabase.js b/initialProject/lib/seedDatabase.js index 8c6ac68..c2e29f2 100644 --- a/initialProject/lib/seedDatabase.js +++ b/initialProject/lib/seedDatabase.js @@ -13,15 +13,15 @@ const query = async (statement) => { try { return (await conn.query(statement)).rows; } catch (error) { - throw new Error(`\DB error: ${error.message}`); + throw new Error(`DB error: ${error.message}`); } }; -(async () => { +const initializeDatabase = async () => { try { let exists = false; try { - exists = (await query(sql`SELECT to_regclass('public.todo') as exists`))[0].exists == 'todo'; + exists = (await query(sql`SELECT to_regclass('public.todo') as exists`))[0].exists === 'todo'; } catch (e) {} if (!exists) { console.log(new Date().toISOString(), 'Initializing database'); @@ -31,5 +31,26 @@ const query = async (statement) => { } catch (createError) { console.log(new Date().toISOString(), 'Error initializing database', createError); } - process.exit(); -})(); +}; + +const MAX_RETRIES = 5; +const RETRY_INTERVAL = 5000; // 5 seconds + +const initializeWithRetry = async (retryCount = 0) => { + try { + await conn.connect(); // Try to establish a database connection + await initializeDatabase(); // Try to initialize the database + process.exit(); // Exit after successful initialization + } catch (error) { + console.error(new Date().toISOString(), 'Error connecting to database:', error.message); + if (retryCount < MAX_RETRIES) { + console.log(`Retrying in ${RETRY_INTERVAL / 1000} seconds...`); + setTimeout(() => initializeWithRetry(retryCount + 1), RETRY_INTERVAL); + } else { + console.error('Maximum retry attempts reached. Exiting...'); + process.exit(1); // Exit with non-zero status to indicate failure + } + } +}; + +initializeWithRetry();