-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcontactController.js
More file actions
110 lines (105 loc) · 2.66 KB
/
contactController.js
File metadata and controls
110 lines (105 loc) · 2.66 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
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
101
102
103
104
105
106
107
108
109
110
// Import contact model
Contact = require("./contactModel");
// Handle index actions
exports.index = function (req, res) {
Contact.get(function (err, contacts) {
if (err) {
res.status(500).send(err);
return;
}
res.status(200).send({
status: "success",
message: "Contacts retrieved successfully",
data: contacts,
});
});
};
// Handle create contact actions
exports.new = function (req, res) {
var contact = new Contact();
contact.name = req.body.name;
contact.gender = req.body.gender ? req.body.gender : "";
contact.email = req.body.email;
contact.phone = req.body.phone ? req.body.phone : "";
if (!req.body.name) {
res.status(400).send("Name required!");
return;
}
if (!req.body.email) {
res.status(400).send("Email required!");
return;
}
// save the contact and check for errors
contact.save(function (err) {
if (err) {
res.status(500).send(err);
return;
}
res.status(201).send({
message: "New contact created!",
data: contact,
});
});
};
// Handle view contact info
exports.view = function (req, res) {
Contact.findById(req.params.contact_id, function (err, contact) {
if (!contact) {
res.status(404).send("Contact not found!");
return;
}
if (err) {
res.status(500).send(err);
return;
}
res.status(200).send({
message: "Contact details loading..",
data: contact,
});
});
};
// Handle update contact info
exports.update = function (req, res) {
Contact.findById(req.params.contact_id, function (err, contact) {
if (!contact) {
res.status(404).send("Contact not found!");
return;
}
if (err) {
res.status(500).send(err);
return;
}
contact.name = req.body.name ? req.body.name : contact.name;
contact.gender = req.body.gender ? req.body.gender : contact.gender;
contact.email = req.body.email ? req.body.email : contact.email;
contact.phone = req.body.phone ? req.body.phone : contact.phone;
// save the contact and check for errors
contact.save(function (err) {
if (err) {
res.status(500).send(err);
return;
}
res.status(200).send({
message: "Contact Info updated",
data: contact,
});
});
});
};
// Handle delete contact
exports.delete = function (req, res) {
Contact.findByIdAndRemove(req.params.contact_id, function (err, contact) {
if (!contact) {
res.status(404).send("Contact not found!");
return;
}
if (err) {
res.status(500).send(err);
return;
}
res.status(200).send({
status: "success",
message: "Contact deleted",
});
});
};