145 lines
4.1 KiB
JavaScript
145 lines
4.1 KiB
JavaScript
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 ? `<p style="color:red">${error}</p>` : "";
|
|
const rowsHtml = rows
|
|
.map(
|
|
(row) => `
|
|
<tr>
|
|
<td>${row.id}</td>
|
|
<td>
|
|
<form method="POST" action="/update">
|
|
<input type="hidden" name="id" value="${row.id}">
|
|
<input type="text" name="txt_content" value="${row.test_data}">
|
|
<button type="submit">save</button>
|
|
</form>
|
|
</td>
|
|
<td>
|
|
<form method="POST" action="/delete" onsubmit="return confirm('Delete?')">
|
|
<input type="hidden" name="id" value="${row.id}">
|
|
<button type="submit">delete</button>
|
|
</form>
|
|
</td>
|
|
</tr>`
|
|
)
|
|
.join("");
|
|
|
|
return `<!doctype html>
|
|
<html lang="en">
|
|
<head>
|
|
<meta charset="utf-8">
|
|
<title>Node + Postgres Demo</title>
|
|
</head>
|
|
<body>
|
|
<h3>Node + Postgres Demo</h3>
|
|
${errorHtml}
|
|
<form method="POST" action="/add">
|
|
<input type="text" name="txt_content" placeholder="New message">
|
|
<button type="submit">Add</button>
|
|
</form>
|
|
<table border="1" cellpadding="6" cellspacing="0">
|
|
<tr><th>ID</th><th>Content</th><th>Actions</th></tr>
|
|
${rowsHtml}
|
|
</table>
|
|
</body>
|
|
</html>`;
|
|
}
|
|
|
|
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}`);
|
|
});
|