-
Notifications
You must be signed in to change notification settings - Fork 0
/
wait-for.js
39 lines (29 loc) · 856 Bytes
/
wait-for.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
const { Client } = require("pg");
const DEFAULT_MAX_ATTEMPTS = 100;
const DEFAULT_DELAY = 1000; // in ms
const timeout = ms => new Promise(resolve => setTimeout(resolve, ms));
async function waitForPostgreSql({
databaseUrl = process.env.DATABASE_URL || "postgres://postgres@localhost",
maxAttempts = DEFAULT_MAX_ATTEMPTS,
delay = DEFAULT_DELAY
} = {}) {
let didConnect = false;
let retries = 0;
while (!didConnect) {
try {
const client = new Client(databaseUrl);
await client.connect();
console.log("Postgres is up");
client.end();
didConnect = true;
} catch (error) {
retries++;
if (retries > maxAttempts) {
throw error;
}
console.log(`Postgres is unavailable - try again in ${delay}`);
await timeout(delay);
}
}
}
module.exports = waitForPostgreSql;