1
+ const to = require ( 'await-to-js' ) . default ;
2
+ const { ErrorHandler } = require ( '../../../helpers/error' ) ;
3
+ const constants = require ( '../../../constants' ) ;
4
+ const Contact = require ( "../../models/contactUs" ) ;
5
+ const Admin = require ( "../../models/Admin" ) ;
6
+
7
+ // Controller to delete a contact by adminid and contactdocumentid
8
+ module . exports = async ( req , res , next ) => {
9
+ const { contactId, adminId } = req . body ;
10
+
11
+ // Check if contactId is provided
12
+ if ( ! contactId || ! adminId ) {
13
+ const error = new ErrorHandler ( constants . ERRORS . VALIDATION , {
14
+ statusCode : 400 ,
15
+ message : 'Validation Error' ,
16
+ errStack : 'Both IDs are required to delete a contact' ,
17
+ } ) ;
18
+ return next ( error ) ;
19
+ }
20
+ //Find if the user is admin or not
21
+ const admin = await to ( Admin . findOne ( { _id : adminId } ) ) ;
22
+ if ( ! admin ) {
23
+ const error = new ErrorHandler ( constants . ERRORS . USER , {
24
+ statusCode : 400 ,
25
+ message : "Admin Validation Error" ,
26
+ errStack : "Admin user provided not found in database"
27
+ } )
28
+ return next ( error ) ;
29
+ }
30
+ // Delete the contact
31
+ const [ err , result ] = await to ( Contact . findByIdAndDelete ( contactId ) ) ;
32
+
33
+ if ( err ) {
34
+ const error = new ErrorHandler ( constants . ERRORS . DATABASE , {
35
+ statusCode : 500 ,
36
+ message : 'Database Error' ,
37
+ errStack : err ,
38
+ } ) ;
39
+ return next ( error ) ;
40
+ }
41
+
42
+ if ( ! result ) {
43
+ const error = new ErrorHandler ( constants . ERRORS . NOT_FOUND , {
44
+ statusCode : 404 ,
45
+ message : 'Contact Not Found' ,
46
+ } ) ;
47
+ return next ( error ) ;
48
+ }
49
+
50
+ res . status ( 200 ) . send ( {
51
+ message : 'Contact deleted successfully' ,
52
+ } ) ;
53
+
54
+ return next ( ) ;
55
+ } ;
0 commit comments