-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
112 lines (87 loc) · 2.52 KB
/
server.js
File metadata and controls
112 lines (87 loc) · 2.52 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
105
106
107
108
109
110
111
112
const express = require("express");
const fs = require("fs");
const path = require("path");
const app = express();
const PORT = 3000;
const DATA_FILE = path.join(__dirname, "data", "posts.json");
const PUBLIC_DIR = path.join(__dirname, "public");
app.use(express.json());
app.use(express.static(PUBLIC_DIR));
function readPostsFromFile() {
try {
const fileContent = fs.readFileSync(DATA_FILE, "utf-8");
return JSON.parse(fileContent);
} catch (error) {
return [];
}
}
function savePostsToFile(posts) {
fs.writeFileSync(DATA_FILE, JSON.stringify(posts, null, 2));
}
app.get("/api", (req, res) => {
res.send("Simple Blog API is running");
});
app.get("/api/posts", (req, res) => {
const posts = readPostsFromFile();
res.json(posts);
});
app.get("/api/posts/:id", (req, res) => {
const posts = readPostsFromFile();
const id = Number(req.params.id);
const post = posts.find((item) => item.id === id);
if (!post) {
return res.status(404).json({ message: "Post not found" });
}
res.json(post);
});
app.post("/api/posts", (req, res) => {
const posts = readPostsFromFile();
const { title, content } = req.body;
if (!title || !content) {
return res.status(400).json({ message: "Title and content are required" });
}
const highestId = posts.reduce((maxId, item) => {
return item.id > maxId ? item.id : maxId;
}, 0);
const newPost = {
id: highestId + 1,
title,
content,
};
posts.push(newPost);
savePostsToFile(posts);
res.status(201).json(newPost);
});
app.put("/api/posts/:id", (req, res) => {
const posts = readPostsFromFile();
const id = Number(req.params.id);
const { title, content } = req.body;
const postIndex = posts.findIndex((item) => item.id === id);
if (postIndex === -1) {
return res.status(404).json({ message: "Post not found" });
}
if (!title || !content) {
return res.status(400).json({ message: "Title and content are required" });
}
posts[postIndex] = {
id,
title,
content,
};
savePostsToFile(posts);
res.json(posts[postIndex]);
});
app.delete("/api/posts/:id", (req, res) => {
const posts = readPostsFromFile();
const id = Number(req.params.id);
const postIndex = posts.findIndex((item) => item.id === id);
if (postIndex === -1) {
return res.status(404).json({ message: "Post not found" });
}
posts.splice(postIndex, 1);
savePostsToFile(posts);
res.json({ message: "Post deleted successfully" });
});
app.listen(PORT, () => {
console.log(`Server is running on http://localhost:${PORT}`);
});