-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.js
100 lines (89 loc) · 2.43 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
93
94
95
96
97
98
99
100
const express = require("express");
const cors = require("cors");
const { connectToDb, getDb } = require("./db");
const { ObjectId } = require("mongodb");
const PORT = 3000;
const app = express();
app.use(cors());
app.use(express.json());
let db;
connectToDb((err) => {
if (!err) {
app.listen(PORT, (err) => {
err
? console.log(err)
: console.log(`Server is listening on port ${PORT}`);
});
db = getDb();
} else {
console.log(`Error connection to db: ${err}`);
}
});
const handleSuccess = (res, statusCode, data) => {
res.status(statusCode).json(data);
};
const handleError = (res, statusCode, errMsg) => {
res.status(statusCode).json(errMsg);
};
app.get("/profiles", (req, res) => {
db.collection("profiles")
.find() //returns a cursor
.toArray()
.then((profiles) => {
handleSuccess(res, 200, profiles);
})
.catch(() => {
handleError(res, 500, "Error fetching profiles");
});
});
app.get("/profiles/:id", (req, res) => {
if (ObjectId.isValid(req.params.id)) {
const id = new ObjectId(req.params.id);
db.collection("profiles")
.findOne({ _id: id })
.then((doc) => handleSuccess(res, 200, doc))
.catch(() =>
handleError(res, 500, "Error fetching profiles with this id")
);
} else {
handleError(res, 500, "Wrong id");
}
});
app.post("/profiles", (req, res) => {
db.collection("profiles")
.insertOne(req.body)
.then((result) => handleSuccess(res, 201, result))
.catch(() => handleError(res, "Error creating a new profile"));
});
app.patch("/profiles/:id", (req, res) => {
// console.log("Request body:", req.body);
// console.log("Request id:", req.params.id);
if (ObjectId.isValid(req.params.id)) {
const id = new ObjectId(req.params.id);
db.collection("profiles")
.updateOne({ _id: id }, { $set: req.body })
.then((result) => {
res.status(200).json(result);
})
.catch(() =>
handleError(res, 500, "Error updating profile with this id")
);
} else {
handleError(res, 500, "Wrong id");
}
});
app.delete("/profiles/:id", (req, res) => {
if (ObjectId.isValid(req.params.id)) {
const id = new ObjectId(req.params.id);
db.collection("profiles")
.deleteOne({ _id: id })
.then((result) => {
res.status(200).json(result);
})
.catch(() =>
handleError(res, 500, "Error updating profile with this id")
);
} else {
handleError(res, 500, "Wrong id");
}
});