const http = require("http"); const { URL } = require("url"); const { Pool } = require("pg"); const pool = new Pool( process.env.DATABASE_URL ? { connectionString: process.env.DATABASE_URL } : { host: process.env.PGHOST, port: process.env.PGPORT || "5432", user: process.env.PGUSER, password: process.env.PGPASSWORD, database: process.env.PGDATABASE || "postgres", ssl: process.env.PGSSLMODE === "disable" ? false : { rejectUnauthorized: false }, } ); 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 CURRENT_TIMESTAMP)" ); } 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 ` Node + Postgres Demo

Node + Postgres Demo

${errorHtml}
${rowsHtml}
IDContentActions
`; } 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 result = 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(result.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"; 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}`); });