Skip to content

Commit

Permalink
adjust pg_wait.ts
Browse files Browse the repository at this point in the history
  • Loading branch information
piotr-iohk committed Oct 22, 2024
1 parent 1ab2dd5 commit b4b4610
Showing 1 changed file with 12 additions and 5 deletions.
17 changes: 12 additions & 5 deletions tasks/pg_wait.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,6 @@ import { assertExists } from "@std/assert"

const connectionString = Deno.env.get("DATABASE_URL")
assertExists(connectionString)
const client = new pg.Client({ connectionString })

const MAX_RETRIES = 200
const RETRY_INTERVAL_MS = 10_000
Expand All @@ -16,21 +15,29 @@ let attempts = 0

while (!connected && attempts < MAX_RETRIES) {
try {
const client = new pg.Client({ connectionString })
await client.connect()
connected = true
await client.end()
} catch (err: unknown) {
if (err instanceof Error && err.message.startsWith("Client has already been connected.")) {
connected = true
break
}

attempts++
console.log("Waiting for database to be ready.")
console.error(err)
console.log(`Attempt ${attempts} failed. Waiting for database to be ready...`)

if (attempts >= MAX_RETRIES) {
console.error("Max retries reached. Could not connect to the database.")
}

await new Promise((resolve) => setTimeout(resolve, RETRY_INTERVAL_MS))
}
}

if (connected) {
await client.end()
console.log("Database ready at", connectionString)
} else throw 0
} else {
Deno.exit(1)
}

0 comments on commit b4b4610

Please sign in to comment.