-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathapp.js
96 lines (88 loc) · 2.22 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
const app = require("express")();
const db = require("./db.json");
const bodyParser = require("body-parser");
const ejs = require("ejs");
app.set('view engine','ejs');
app.use(bodyParser.json())
app.use(bodyParser.urlencoded({ extended : true }))
app.get("/",(req,res) => {
res.render('index')
})
//get all users
app.get("/users", (req, res) => {
console.log("Request is received...");
res.send(200, {
db
})
})
//get a user with its id
app.get("/users/:id", (req, res) => {
if(isNaN(req.params.id)){
res.send(400, {
message: "Unprocessible Entry"
})
} else {
const user = db.find(u => u.id == req.params.id)
if(user){
res.send(200, user)
} else {
res.send(404, {
message: "User Not Found"
})
}
}
})
// add a new user
app.post("/users", (req, res) => {
const newUser = {
id: new Date().getTime(),
full_name: req.body.full_name,
country: req.body.country,
email: req.body.email,
created_at: new Date()
};
db.push(newUser)
res.send(newUser)
})
// Update values of user
app.patch("/users/:id", (req, res) => {
if(isNaN(req.params.id)){
res.send(400, {
message: "Unprocessible Entry"
})
} else {
const user = db.find(u => u.id == req.params.id)
if(user){
Object.keys(req.body).forEach(key => {
user[key] = req.body[key];
})
res.send(200, user)
} else {
res.send(404, {
message: "User Not Found"
})
}
}
})
app.delete("/users/:id", (req, res) => {
if(isNaN(req.params.id)){
res.send(400, {
message: "Unprocessible Entry"
})
} else {
const userIndex = db.findIndex(u => u.id == req.params.id)
if(userIndex > -1){
db.splice(userIndex,1);
res.send(201, {
message : "User is deleted!"
})
} else {
res.send(404, {
message: "User Not Found"
})
}
}
})
app.listen(process.env.PORT || 3000, () => {
console.log("The server is running...");
})