fix: wait for database during API startup
This commit is contained in:
@@ -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,
|
||||||
|
|||||||
Reference in New Issue
Block a user