-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
42 lines (34 loc) · 1.04 KB
/
server.js
File metadata and controls
42 lines (34 loc) · 1.04 KB
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
// CONTACTS API ROUTES BELOW
//Generates error handler used by all endpoints.
function handleError(res, reason, message, code) {
console.log("ERROR: " + reason);
res.status(code || 500).json({"error": message});
}
app.get("/api/contacts", function(req, res) {
db.collection(CONTACTS_COLLECTION).find({}).toArray(function(err, docs) {
if (err) {
handleError(res, err.message, "Failed to get contacts.");
} else {
res.status(200).json(docs);
}
});
});
app.post("/api/contacts", function(req, res) {
var newContact = req.body;
if (!req.body.name) {
handleError(res, "Invalid user input.", "Must provide a name.", 400);
}
db.collection(CONTACTS_COLLECTION).insertOne(newContact, function(err, doc) {
if (err) {
handleError(res, err.message, "Failed to create a new contact.");
} else {
res.status(201).json(doc.ops[0]);
}
});
});
app.get("/api/contacts/:id", function(req, res) {
});
app.put("/api/contacts/:id", function(req, res) {
});
app.delete("/api/contacts/:id", function(req, res) {
});