Skip to content

Commit 0c1183c

Browse files
committed
CRUD operation
1 parent 12a835f commit 0c1183c

File tree

1 file changed

+28
-5
lines changed

1 file changed

+28
-5
lines changed

src/controllers/contactController.js

Lines changed: 28 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -19,29 +19,52 @@ const createContact = asyncHandler(async (req,res)=>{
1919
res.status(400);
2020
throw new Error("All Fields are mandatory")
2121
}
22-
res.status(201).json({message : "Create Contact!"})
22+
const contact = await Contact.create({
23+
name,
24+
email,
25+
phone
26+
})
27+
res.status(201).json(contact)
2328
});
2429

2530
//@desc Get contact by id
2631
//@route GET/api/contacts:id
2732
//@access public
2833

29-
const getContact = asyncHandler( (req,res)=>{
30-
res.status(200).json({message : `Get contact for ${req.params.id}`})
34+
const getContact = asyncHandler(async (req,res)=>{
35+
const contact = await Contact.findById(req.params.id);
36+
if(!contact){
37+
res.status(404);
38+
throw new Error("Contact not found")
39+
}
40+
res.status(200).json(contact)
3141
});
3242

3343
//@desc update contacts
3444
//@route PUT/api/contacts/:id
3545
//@access public
3646
const updateContact = asyncHandler(async (req,res)=>{
37-
res.status(200).json({message : `update contact for ${req.params.id}`})
47+
const contact = await Contact.findById(req.params.id);
48+
if(!contact){
49+
res.status(404);
50+
throw new Error("Contact not found")
51+
}
52+
53+
const updatedContact = await Contact.findByIdAndUpdate(req.params.id, req.body,{new : true})
54+
res.status(200).json(updatedContact)
3855
});
3956

4057
//@desc delete contact
4158
//@route delete/api/contacts/:id
4259
//@access public
4360
const deleteContact = asyncHandler(async (req,res)=>{
44-
res.status(200).json({message : `Delete contact for ${req.params.id}`})
61+
const contact = await Contact.findById(req.params.id);
62+
if(!contact){
63+
res.status(404);
64+
throw new Error("Contact not found")
65+
}
66+
const deletedContect = await Contact.findOneAndDelete();
67+
res.status(200).json(deletedContect);
4568
});
4669

4770

0 commit comments

Comments
 (0)