-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.js
92 lines (78 loc) · 1.82 KB
/
server.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
const express = require("express");
const app = express();
app.use(express.json());
let currentUser = {
name: "Sarah Waters",
age: 55,
country: "United Kingdom",
books: ["Fingersmith", "The Night Watch"],
};
let users = [
{
id: 3,
name: "Sarah Waters",
age: 55,
country: "United Kingdom",
books: ["Fingersmith", "The Night Watch"],
},
{
id: 1,
name: "Haruki Murakami",
age: 71,
country: "Japan",
books: ["Norwegian Wood", "Kafka on the Shore"],
},
{
id: 0,
name: "Chimamanda Ngozi Adichie",
age: 43,
country: "Nigeria",
books: ["Half of a Yellow Sun", "Americanah"],
},
];
let books = [
{
id: 0,
name: "To Kill a Mockingbird",
pages: 281,
title: "Harper Lee",
price: 12.99,
},
{
id: 1,
name: "The Catcher in the Rye",
pages: 224,
title: "J.D. Salinger",
price: 9.99,
},
{
id: 2,
name: "The Little Prince",
pages: 85,
title: "Antoine de Saint-Exupéry",
price: 7.99,
},
];
app.get("/current-user", (req, res) => res.json(currentUser));
app.get("/users/:id", (req, res) => {
const { id } = req.params;
console.log(id);
res.json(users.find((user) => user.id === parseInt(id)));
});
app.get("/users", (req, res) => res.json(users));
app.post("/users/:id", (req, res) => {
let { id } = req.params;
id = parseInt(id);
const { user: editedUser } = req.body;
users = users.map((user) => (user.id === id ? { ...editedUser, id } : user));
res.json(users.find((user) => user.id === id));
});
app.get("/books", (req, res) => res.json(books));
app.get("/books/:id", (req, res) => {
const { id } = req.params;
res.json(books.find((book) => book.id === parseInt(id)));
});
let SERVER_PORT = 9090;
app.listen(SERVER_PORT, () =>
console.log(`Server is listening on port: ${SERVER_PORT}`)
);