-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathbackend_with_db.js
87 lines (76 loc) · 2.36 KB
/
backend_with_db.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
const express = require("express");
const mongoose = require("mongoose");
// Add mongdb user services
const userServices = require("./models/user-services");
const app = express();
const port = 5000;
app.use(express.json());
app.get("/", (req, res) => {
res.send("Hello World!");
});
app.get("/users", async (req, res) => {
//res.send(users); //HTTP code 200 is set by default. See an alternative below
//res.status(200).send(users);
const name = req.query["name"];
const job = req.query["job"];
try {
const result = await userServices.getUsers(name, job);
res.send({ users_list: result });
} catch (error) {
console.log(error);
res.status(500).send("An error ocurred in the server.");
}
});
app.get("/users/:id", async (req, res) => {
const id = req.params["id"];
let result = await userServices.findUserById(id);
if (result === undefined || result === null)
res.status(404).send("Resource not found.");
else {
result = { users_list: result };
res.send(result);
}
});
app.delete("/users/:id", async (req, res) => {
const id = req.params["id"];
if (deleteUserById(id)) res.status(204).end();
else res.status(404).send("Resource not found.");
});
async function deleteUserById(id) {
try {
if (await userServices.findByIdAndDelete(id)) return true;
} catch (error) {
console.log(error);
return false;
}
}
app.post("/users", async (req, res) => {
const user = req.body;
const savedUser = await userServices.addUser(user);
if (savedUser) res.status(201).send(savedUser);
else res.status(500).end();
});
app.patch("/users/:id", async (req, res) => {
const id = req.params["id"];
const updatedUser = req.body;
const result = await updateUser(id, updatedUser);
if (result === 204) res.status(204).end();
else if (result === 404) res.status(404).send("Resource not found.");
else if (result === 500)
res.status(500).send("An error ocurred in the server.");
});
async function updateUser(id, updatedUser) {
try {
const result = await userServices.findByIdAndUpdate(id, updatedUser);
if (result) return 204;
else return 404;
} catch (error) {
console.log(error);
return 500;
}
}
app.listen(process.env.PORT || port, () => {
if (process.env.PORT)
console.log(`REST API is listening on port: ${process.env.PORT}.`);
else console.log(`REST API is listening on port: ${port}.`);
});