-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
92 lines (71 loc) · 2.07 KB
/
Copy pathserver.js
File metadata and controls
92 lines (71 loc) · 2.07 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
import express from "express";
import "dotenv/config";
import morgan from "morgan";
import swaggerUi from "swagger-ui-express";
import swaggerDocument from "./openapi.json" with { type: "json" };
const app = express();
app.use(express.json());
app.use(morgan("dev"));
app.use("/api-docs", swaggerUi.serve, swaggerUi.setup(swaggerDocument));
const tasks = [
{ id: 1, title: "Buy groceries", done: false },
{ id: 2, title: "Clean the kitchen", done: true },
{ id: 3, title: "Fix the broken chair", done: false },
];
app.get("/", (req, res) => {
res.json({ name: "Task API", version: "1.0", endpoints: ["/tasks"] });
});
app.get("/health", (req, res) => {
res.json({ status: "ok" });
});
app.get("/tasks", (req, res) => {
res.json(tasks);
});
app.get("/tasks/:id", (req, res) => {
const id = parseInt(req.params.id);
const task = tasks.find((task) => task.id === id);
if (!task) {
return res.status(404).json({ error: `Task ${id} not found` });
}
res.json(task);
});
app.post("/tasks", (req, res) => {
const { title, done } = req.body;
if (!title) {
return res.status(400).json("title is required");
}
const newTask = {
id: tasks.length + 1,
title: title,
done: done ?? false,
};
tasks.push(newTask);
res.status(201).json({
message: "Created",
newTask,
});
});
app.put("/tasks/:id", (req, res) => {
const id = parseInt(req.params.id);
const { title, done } = req.body;
const task = tasks.find((task) => task.id === id);
if (!task) {
return res.status(404).json({ error: `Task ${id} not found` });
}
task.title = title;
task.done = done;
res.json({ message: "Updated", task });
});
app.delete("/tasks/:id", (req, res) => {
const id = parseInt(req.params.id);
const taskIndex = tasks.findIndex((task) => task.id === id);
if (taskIndex === -1) {
return res.status(404).json({ error: `Task ${id} not found` });
}
tasks.splice(taskIndex, 1);
res.status(204).json({ message: "Deleted" });
});
const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
console.log(`Server running on port ${PORT}`);
});