Skip to content

Commit 6a03144

Browse files
authored
feat: wait-for-postgres
1 parent 8f4e5da commit 6a03144

File tree

3 files changed

+32
-3
lines changed

3 files changed

+32
-3
lines changed

infra/compose.yaml

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
services:
22
database:
3+
container_name: "postgres-dev"
34
image: "postgres:16.0-alpine3.18"
45
env_file:
56
- ../.env.development

infra/scripts/wait-for-postgres.js

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
require("dotenv").config({ path: ".env.development" });
2+
3+
if (!process.env.POSTGRES_HOST) {
4+
throw new Error("Environment variable POSTGRES_HOST is not defined");
5+
}
6+
7+
const { exec } = require("node:child_process");
8+
9+
function checkPostgres() {
10+
exec(
11+
`docker exec postgres-dev pg_isready --host ${process.env.POSTGRES_HOST}`,
12+
handleReturn,
13+
);
14+
15+
async function handleReturn(error, stdout) {
16+
if (stdout.search("accepting connections") === -1) {
17+
process.stdout.write("🟡");
18+
await new Promise((resolve) => setTimeout(resolve, 1000));
19+
return checkPostgres();
20+
}
21+
22+
console.log("🟢 PostgreSQL is ready!");
23+
}
24+
}
25+
26+
console.log("🔴 Waiting for PostgreSQL to become available...");
27+
checkPostgres();

package.json

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@
44
"description": "Clone of tabs news project",
55
"main": "index.js",
66
"scripts": {
7-
"dev": "npm run services:up && next dev",
7+
"dev": "npm run services:up && npm run wait-for-postgres && npm run migration:up && next dev",
88
"services:up": "docker compose -f infra/compose.yaml up -d",
99
"services:down": "docker compose -f infra/compose.yaml down",
1010
"services:stop": "docker compose -f infra/compose.yaml stop",
@@ -13,7 +13,8 @@
1313
"test": "jest --runInBand",
1414
"test:watch": "jest --watchAll --runInBand",
1515
"migration:create": "node-pg-migrate --migrations-dir infra/migrations create",
16-
"migration:up": "node-pg-migrate --migrations-dir infra/migrations --envPath .env.development up"
16+
"migration:up": "node-pg-migrate --migrations-dir infra/migrations --envPath .env.development up",
17+
"wait-for-postgres": "node infra/scripts/wait-for-postgres.js"
1718
},
1819
"author": "",
1920
"license": "MIT",
@@ -29,4 +30,4 @@
2930
"jest": "^29.6.2",
3031
"prettier": "^3.3.3"
3132
}
32-
}
33+
}

0 commit comments

Comments
 (0)