fix: wait for database during API startup
All checks were successful
CI / Validate frontend and API (push) Successful in 31s
CI / Build and publish Docker images (push) Successful in 16s

This commit is contained in:
Cauê Faleiros
2026-09-01 12:05:40 -03:00
parent 006281f062
commit 8e28f0feb5

View File

@@ -4,8 +4,31 @@ import { fileURLToPath } from 'node:url';
import { pool, closePool } from './pool.js'; import { pool, closePool } from './pool.js';
const migrationsDirectory = join(dirname(fileURLToPath(import.meta.url)), '../../migrations'); const migrationsDirectory = join(dirname(fileURLToPath(import.meta.url)), '../../migrations');
const databaseRetryDelayMs = 2_000;
const databaseRetryAttempts = 30;
const delay = (milliseconds: number) => new Promise<void>((resolve) => setTimeout(resolve, milliseconds));
async function waitForDatabase() {
let lastError: unknown;
for (let attempt = 1; attempt <= databaseRetryAttempts; attempt += 1) {
try {
await pool.query('select 1');
return;
} catch (error) {
lastError = error;
if (attempt === databaseRetryAttempts) break;
console.warn(`Database is not ready (attempt ${attempt}/${databaseRetryAttempts}); retrying in 2 seconds.`);
await delay(databaseRetryDelayMs);
}
}
throw lastError;
}
async function migrate() { async function migrate() {
await waitForDatabase();
await pool.query(` await pool.query(`
create table if not exists schema_migrations ( create table if not exists schema_migrations (
name text primary key, name text primary key,