-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
104 lines (88 loc) · 3.24 KB
/
Copy pathserver.js
File metadata and controls
104 lines (88 loc) · 3.24 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
const express = require("express");
const mysql = require("mysql2/promise");
const app = express();
app.use(express.json());
const PORT = process.env.PORT || 8080;
function getDbConfig() {
if (process.env.DATABASE_URL) {
const url = new URL(process.env.DATABASE_URL);
return {
host: url.hostname,
port: Number(url.port) || 3306,
user: url.username,
password: url.password,
database: url.pathname.replace("/", ""),
ssl: url.searchParams.get("sslmode") === "require" ? {} : undefined,
};
}
return {
host: process.env.MYSQL_HOST || "localhost",
port: Number(process.env.MYSQL_PORT) || 3306,
user: process.env.MYSQL_USER || "root",
password: process.env.MYSQL_PASSWORD || "",
database: process.env.MYSQL_DATABASE || "myapi",
};
}
let pool;
async function initDb() {
pool = mysql.createPool({ ...getDbConfig(), waitForConnections: true, connectionLimit: 10 });
await pool.execute(`
CREATE TABLE IF NOT EXISTS tasks (
id INT AUTO_INCREMENT PRIMARY KEY,
title VARCHAR(255) NOT NULL,
done BOOLEAN DEFAULT FALSE,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
)
`);
console.log("Database initialised – tasks table ready");
}
// --- Health ---
app.get("/health", async (_req, res) => {
try {
await pool.execute("SELECT 1");
res.json({ status: "ok" });
} catch (err) {
res.status(503).json({ status: "error", message: err.message });
}
});
// --- CRUD ---
app.get("/api/tasks", async (_req, res) => {
const [rows] = await pool.execute("SELECT * FROM tasks ORDER BY created_at DESC");
res.json(rows);
});
app.post("/api/tasks", async (req, res) => {
const { title } = req.body;
if (!title) return res.status(400).json({ error: "title is required" });
const [result] = await pool.execute("INSERT INTO tasks (title) VALUES (?)", [title]);
const [rows] = await pool.execute("SELECT * FROM tasks WHERE id = ?", [result.insertId]);
res.status(201).json(rows[0]);
});
app.get("/api/tasks/:id", async (req, res) => {
const [rows] = await pool.execute("SELECT * FROM tasks WHERE id = ?", [req.params.id]);
if (rows.length === 0) return res.status(404).json({ error: "not found" });
res.json(rows[0]);
});
app.put("/api/tasks/:id", async (req, res) => {
const { title, done } = req.body;
const [existing] = await pool.execute("SELECT * FROM tasks WHERE id = ?", [req.params.id]);
if (existing.length === 0) return res.status(404).json({ error: "not found" });
const newTitle = title ?? existing[0].title;
const newDone = done ?? existing[0].done;
await pool.execute("UPDATE tasks SET title = ?, done = ? WHERE id = ?", [newTitle, newDone, req.params.id]);
const [rows] = await pool.execute("SELECT * FROM tasks WHERE id = ?", [req.params.id]);
res.json(rows[0]);
});
app.delete("/api/tasks/:id", async (req, res) => {
const [result] = await pool.execute("DELETE FROM tasks WHERE id = ?", [req.params.id]);
if (result.affectedRows === 0) return res.status(404).json({ error: "not found" });
res.status(204).end();
});
// --- Start ---
initDb()
.then(() => {
app.listen(PORT, () => console.log(`API listening on :${PORT}`));
})
.catch((err) => {
console.error("Failed to initialise database:", err.message);
process.exit(1);
});