zkt26/Z2/app/server.js
2026-04-29 11:57:06 +02:00

112 lines
2.3 KiB
JavaScript

const express = require("express");
const { Pool } = require("pg");
const os = require("os");
const path = require("path");
const app = express();
// middleware
app.use(express.json());
app.use(express.static(path.join(__dirname)));
let counter = 0;
// DB connection
const pool = new Pool({
host: "postgres-service",
user: "postgres",
password: "postgres",
database: "testdb",
port: 5432,
});
// 🔥 Wait for DB
async function waitForDB() {
let connected = false;
while (!connected) {
try {
await pool.query("SELECT 1");
connected = true;
console.log("✅ Database connected");
} catch (err) {
console.log("⏳ Waiting for database...");
await new Promise(res => setTimeout(res, 2000));
}
}
}
async function initDB() {
try {
await pool.query(`
CREATE TABLE IF NOT EXISTS messages (
id SERIAL PRIMARY KEY,
text VARCHAR(255)
)
`);
console.log("✅ Table ready");
} catch (err) {
console.log("TABLE ERROR:", err.message);
}
}
// 🔹 Status API
app.get("/api/status", async (req, res) => {
counter++;
try {
const result = await pool.query("SELECT NOW()");
res.json({
time: result.rows[0].now,
hostname: os.hostname(),
requests: counter,
status: "Connected"
});
} catch (err) {
res.json({
time: "N/A",
hostname: os.hostname(),
requests: counter,
status: "Database not ready"
});
}
});
// 🔹 Insert data
app.post("/api/add", async (req, res) => {
const { text } = req.body;
try {
await pool.query(
"INSERT INTO messages (text) VALUES ($1)",
[text]
);
res.send("Inserted");
} catch (err) {
console.log("INSERT ERROR:", err);
res.status(500).send("Error inserting data");
}
});
// 🔹 Get data
app.get("/api/messages", async (req, res) => {
try {
const result = await pool.query(
"SELECT * FROM messages ORDER BY id DESC"
);
res.json(result.rows);
} catch (err) {
console.log("FETCH ERROR:", err);
res.status(500).send("Error fetching data");
}
});
async function startServer() {
await waitForDB();
await initDB();
app.listen(3000, () => {
console.log("🚀 Server running on port 3000");
});
}
startServer();