-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.js
88 lines (76 loc) · 2.59 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
const express = require("express");
const app = express();
require("dotenv").config();
const { v4: uuidv4 } = require("uuid");
const { validation, putValidation } = require("./validations");
let users = {};
app.use(express.json());
app.use(express.urlencoded({ extended: true }));
// API route for get users
app.get("/api/users", (req, res) => {
res.send(users);
});
// API route for get user with specific ID
app.get("/api/users/:userId", (req, res) => {
if (!users[req.params.userId])
res.status(404).send({ message: "user not found" });
res.send(users[req.params.userId]);
});
// API route for creating a user
app.post("/api/users", async (req, res) => {
try {
const { flag, status, comments } = await validation(req.body);
if (!flag && status === 200) {
let id = uuidv4();
users[id] = { id, ...req.body };
res.status(201).send({ id, ...req.body });
} else if (flag && status === 400) {
res.status(400).send({ message: { ...comments } });
}
} catch (error) {
res.status(error.status).send({ error: error.comments });
}
});
// API route for handling update user request
app.put("/api/users/:userId", async (req, res) => {
try {
const { flag, status, comments } = await putValidation(req.body);
if (!flag && status === 200) {
if (!users[req.params.userId]) {
res.status(404).send("The user not found");
} else {
users[req.params.userId] = { ...users[req.params.userId], ...req.body };
res.status(200).send(users[req.params.userId]);
}
} else if (flag && status === 400) {
res.status(400).send({ message: { ...comments } });
}
} catch (error) {
res.status(error.status).send({ error: error.comments });
}
});
// API route for handling delete user request
app.delete("/api/users/:userId", (req, res) => {
try {
if (!users[req.params.userId])
res.status(404).send({ message: "user not found" });
else {
delete users[req.params.userId];
}
res.status(200).send({ success: "User deleted sucessfully" });
} catch (error) {
res.status(500).send({ error: "Internal Server Error" });
}
});
// If non of the API routes matches then we will handle the requst here
app.use((req, res) => {
res.status(404).send({ message: "The requested URI does not exists" });
});
// Listening for any incoming request on a particular server
app.listen(process.env.PORT, (req, res) => {
console.log("application is running on port 4000");
});
// Middleware for handling any unexpected errors
app.use((err, req, res, next) => {
res.status(500).send({ error: "Internal Server Error" });
});