const http = require("http");
const { URL } = require("url");
const { Pool } = require("pg");
function buildPgConfig() {
if (process.env.DATABASE_URL) {
return {
connectionString: process.env.DATABASE_URL,
ssl: process.env.PGSSLMODE === "require" ? { rejectUnauthorized: false } : undefined,
};
}
return {
host: process.env.PGHOST,
port: Number(process.env.PGPORT || "5432"),
user: process.env.PGUSER,
password: process.env.PGPASSWORD,
database: process.env.PGDATABASE || "postgres",
ssl: process.env.PGSSLMODE === "require" ? { rejectUnauthorized: false } : undefined,
};
}
const pool = new Pool(buildPgConfig());
async function ensureTable() {
await pool.query(
"CREATE TABLE IF NOT EXISTS nubes_test_table (id SERIAL PRIMARY KEY, test_data TEXT, created_at TIMESTAMP DEFAULT NOW())"
);
}
function parseForm(body) {
return body
.split("&")
.map((pair) => pair.split("="))
.reduce((acc, [key, value]) => {
acc[decodeURIComponent(key)] = decodeURIComponent((value || "").replace(/\+/g, " "));
return acc;
}, {});
}
function renderPage(rows, error) {
const errorHtml = error ? `
${error}
` : "";
const rowsHtml = rows
.map(
(row) => `
| ${row.id} |
|
|
`
)
.join("");
return `
NodeJS + Postgres Demo
${errorHtml}
| ID | Content | Actions |
${rowsHtml}
`;
}
async function handleRequest(req, res) {
const url = new URL(req.url, `http://${req.headers.host}`);
if (req.method === "GET" && url.pathname === "/healthz") {
res.writeHead(200, { "Content-Type": "text/plain" });
res.end("ok");
return;
}
if (req.method === "GET" && url.pathname === "/") {
try {
await ensureTable();
const { rows } = await pool.query(
"SELECT id, test_data FROM nubes_test_table ORDER BY id DESC LIMIT 20"
);
res.writeHead(200, { "Content-Type": "text/html; charset=utf-8" });
res.end(renderPage(rows));
} catch (err) {
res.writeHead(500, { "Content-Type": "text/html; charset=utf-8" });
res.end(renderPage([], err.message));
}
return;
}
if (req.method === "POST" && ["/add", "/update", "/delete"].includes(url.pathname)) {
let body = "";
req.on("data", (chunk) => {
body += chunk;
});
req.on("end", async () => {
const form = parseForm(body);
try {
await ensureTable();
if (url.pathname === "/add") {
const content = form.txt_content || "Node did it";
const { rows: lastRows } = await pool.query(
"SELECT test_data, created_at FROM nubes_test_table ORDER BY id DESC LIMIT 1"
);
const last = lastRows[0];
const isDuplicate =
last &&
last.test_data === content &&
Date.now() - new Date(last.created_at).getTime() < 3000;
if (!isDuplicate) {
await pool.query("INSERT INTO nubes_test_table (test_data) VALUES ($1)", [content]);
}
}
if (url.pathname === "/update") {
await pool.query("UPDATE nubes_test_table SET test_data=$1 WHERE id=$2", [
form.txt_content || "",
form.id,
]);
}
if (url.pathname === "/delete") {
await pool.query("DELETE FROM nubes_test_table WHERE id=$1", [form.id]);
}
res.writeHead(303, { Location: "/" });
res.end();
} catch (err) {
res.writeHead(500, { "Content-Type": "text/html; charset=utf-8" });
res.end(renderPage([], err.message));
}
});
return;
}
res.writeHead(404, { "Content-Type": "text/plain" });
res.end("Not found");
}
const port = process.env.PORT || 3000;
const server = http.createServer(handleRequest);
server.listen(port, () => {
console.log(`Server running on port ${port}`);
});