forked from techupth/react-custom-hook-get-posts
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapp.js
115 lines (91 loc) · 2.33 KB
/
app.js
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
113
114
115
import express from "express";
import bodyParser from "body-parser";
import cors from "cors";
let posts = [
{
id: 1,
title: "Paper Clips",
content:
"Integer aliquet, massa id lobortis convallis, tortor risus dapibus augue, vel accumsan tellus nisi eu orci. Mauris lacinia sapien quis libero. Nullam sit amet turpis elementum ligula vehicula consequat. Morbi a ipsum.",
likes: 61,
},
{
id: 2,
title: "Born to Kill",
content:
"Quisque erat eros, viverra eget, congue eget, semper rutrum, nulla.",
likes: 46,
},
];
const app = express();
const port = 4000;
app.use(cors());
app.use(bodyParser.json());
app.get("/", (req, res) => {
res.send("Hello World!");
});
app.get("/posts", (req, res) => {
return res.json({
data: posts,
});
});
app.get("/posts/:id", (req, res) => {
const postId = +req.params.id;
const hasFound = posts.find((post) => post.id === postId);
if (!hasFound) {
return res.status(404).json({
message: `Post ${postId} not found`,
});
}
const post = posts.filter((post) => post.id === postId);
return res.json({
data: post[0],
});
});
app.post("/posts", (req, res) => {
posts.push({
id: posts[posts.length - 1].id + 1,
...req.body,
});
return res.json({
message: "Post has been created.",
});
});
app.put("/posts/:id", (req, res) => {
const updatedPost = req.body;
const postId = +req.params.id;
const hasFound = posts.find((post) => post.id === postId);
if (!hasFound) {
return res.status(404).json({
message: `Post ${postId} not found`,
});
}
const postIndex = posts.findIndex((post) => {
return post.id === +postId;
});
posts[postIndex] = { id: postId, ...updatedPost };
return res.json({
message: `Post ${postId} has been updated.`,
});
});
app.delete("/posts/:id", (req, res) => {
const postId = +req.params.id;
const hasFound = posts.find((post) => post.id === postId);
if (!hasFound) {
return res.status(404).json({
message: `Post ${postId} not found`,
});
}
posts = posts.filter((post) => {
return postId !== post.id;
});
return res.json({
message: `Post ${postId} has been deleted.`,
});
});
app.get("*", (req, res) => {
res.status(404).send("Not found");
});
app.listen(port, () => {
console.log(`Example app listening on port ${port}`);
});