@@ -3,37 +3,44 @@ const challengeQuery = require('../models/challenges')
3
3
const ERROR_MESSAGE = 'Something went wrong. Please try again or contact admin'
4
4
5
5
/**
6
- * Get the challenges or add the challenge
6
+ * Get the challenges
7
7
* @param {Object } req - Express request object
8
8
* @param {Object } res - Express response object
9
9
*/
10
10
11
- const sendChallengeResponse = async ( req , res ) => {
11
+ const fetchChallenges = async ( req , res ) => {
12
12
try {
13
- if ( req . method === 'GET' ) {
14
- const allChallenges = await challengeQuery . fetchChallenges ( )
15
- const promiseArray = await getParticipantsofChallenges ( allChallenges )
16
- const challengesWithParticipants = await Promise . all ( promiseArray )
13
+ const allChallenges = await challengeQuery . fetchChallenges ( )
14
+ const promiseArray = await getParticipantsofChallenges ( allChallenges )
15
+ const challengesWithParticipants = await Promise . all ( promiseArray )
16
+ return res . json ( {
17
+ message : challengesWithParticipants . length ? 'Challenges returned successfully!' : 'No Challenges found' ,
18
+ challenges : challengesWithParticipants
19
+ } )
20
+ } catch ( err ) {
21
+ logger . error ( `Error while retrieving challenges ${ err } ` )
22
+ return res . boom . serverUnavailable ( ERROR_MESSAGE )
23
+ }
24
+ }
25
+
26
+ /**
27
+ * Add a challenge
28
+ * @param {Object } req - Express request object
29
+ * @param {Object } res - Express response object
30
+ */
31
+
32
+ const createChallenge = async ( req , res ) => {
33
+ try {
34
+ const challengeAdded = await challengeQuery . postChallenge ( req . body )
35
+ if ( challengeAdded ) {
17
36
return res . json ( {
18
- message : challengesWithParticipants . length ? 'Challenges returned successfully!' : 'No Challenges found' ,
19
- challenges : challengesWithParticipants
37
+ message : 'Challenge added successfully'
20
38
} )
21
39
} else {
22
- if ( req . method === 'POST' ) {
23
- const challengeAdded = await challengeQuery . postChallenge ( req . body )
24
- if ( challengeAdded ) {
25
- return res . status ( 200 ) . json ( {
26
- message : 'Challenge added successfully' ,
27
- challenges : challengeAdded
28
- } )
29
- }
30
- } else {
31
- return res . boom . notFound ( 'Unable to add challenge' )
32
- }
40
+ return res . boom . badRequest ( 'Unable to add challenge' )
33
41
}
34
- return ''
35
42
} catch ( err ) {
36
- logger . error ( `Error while retriving challenges ${ err } ` )
43
+ logger . error ( `Error while adding challenge ${ err } ` )
37
44
return res . boom . serverUnavailable ( ERROR_MESSAGE )
38
45
}
39
46
}
@@ -77,6 +84,7 @@ const subscribeToChallenge = async (req, res) => {
77
84
}
78
85
79
86
module . exports = {
80
- sendChallengeResponse,
87
+ fetchChallenges,
88
+ createChallenge,
81
89
subscribeToChallenge
82
90
}
0 commit comments