const http = require("http");
const { URL } = require("url");
const mysql = require("mysql2/promise");
const pool = process.env.DATABASE_URL
? mysql.createPool(process.env.DATABASE_URL)
: mysql.createPool({
host: process.env.DB_HOST,
port: process.env.DB_PORT || "3306",
user: process.env.DB_USER,
password: process.env.DB_PASSWORD,
database: process.env.DB_NAME || "postgres",
});
async function ensureTable() {
await pool.query(
"CREATE TABLE IF NOT EXISTS nubes_test_table (id INT AUTO_INCREMENT 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 + MariaDB Demo
Node + MariaDB 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";
await pool.query("INSERT INTO nubes_test_table (test_data) VALUES (?)", [content]);
}
if (url.pathname === "/update") {
await pool.query("UPDATE nubes_test_table SET test_data=? WHERE id=?", [
form.txt_content || "",
form.id,
]);
}
if (url.pathname === "/delete") {
await pool.query("DELETE FROM nubes_test_table WHERE id=?", [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}`);
});