@@ -19,29 +19,52 @@ const createContact = asyncHandler(async (req,res)=>{
19
19
res . status ( 400 ) ;
20
20
throw new Error ( "All Fields are mandatory" )
21
21
}
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 )
23
28
} ) ;
24
29
25
30
//@desc Get contact by id
26
31
//@route GET/api/contacts:id
27
32
//@access public
28
33
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 )
31
41
} ) ;
32
42
33
43
//@desc update contacts
34
44
//@route PUT/api/contacts/:id
35
45
//@access public
36
46
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 )
38
55
} ) ;
39
56
40
57
//@desc delete contact
41
58
//@route delete/api/contacts/:id
42
59
//@access public
43
60
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 ) ;
45
68
} ) ;
46
69
47
70
0 commit comments