Skip to content

Commit

Permalink
Make seed retry if database not yet available
Browse files Browse the repository at this point in the history
  • Loading branch information
MarcusAhlfors committed Apr 17, 2024
1 parent 09ceeab commit c3d5fc1
Showing 1 changed file with 26 additions and 5 deletions.
31 changes: 26 additions & 5 deletions initialProject/lib/seedDatabase.js
Original file line number Diff line number Diff line change
Expand Up @@ -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');
Expand All @@ -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();

0 comments on commit c3d5fc1

Please sign in to comment.