Skip to content

Commit 13df217

Browse files
challenges API refactored (#271)
* [WIP] challenges API refactored * refactored challenges get and post * validators for createChallenge * using timestamps for date * seperating get and post routes * boom response changes Co-authored-by: akshay shinde <[email protected]>
1 parent 605fcec commit 13df217

File tree

5 files changed

+68
-33
lines changed

5 files changed

+68
-33
lines changed

controllers/challenge.js

Lines changed: 30 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -3,37 +3,44 @@ const challengeQuery = require('../models/challenges')
33
const ERROR_MESSAGE = 'Something went wrong. Please try again or contact admin'
44

55
/**
6-
* Get the challenges or add the challenge
6+
* Get the challenges
77
* @param {Object} req - Express request object
88
* @param {Object} res - Express response object
99
*/
1010

11-
const sendChallengeResponse = async (req, res) => {
11+
const fetchChallenges = async (req, res) => {
1212
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) {
1736
return res.json({
18-
message: challengesWithParticipants.length ? 'Challenges returned successfully!' : 'No Challenges found',
19-
challenges: challengesWithParticipants
37+
message: 'Challenge added successfully'
2038
})
2139
} 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')
3341
}
34-
return ''
3542
} catch (err) {
36-
logger.error(`Error while retriving challenges ${err}`)
43+
logger.error(`Error while adding challenge ${err}`)
3744
return res.boom.serverUnavailable(ERROR_MESSAGE)
3845
}
3946
}
@@ -77,6 +84,7 @@ const subscribeToChallenge = async (req, res) => {
7784
}
7885

7986
module.exports = {
80-
sendChallengeResponse,
87+
fetchChallenges,
88+
createChallenge,
8189
subscribeToChallenge
8290
}
Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
const joi = require('joi')
2+
3+
const createChallenge = async (req, res, next) => {
4+
const schema = joi.object().strict().keys({
5+
title: joi.string().required(),
6+
level: joi.string().required(),
7+
start_date: joi.number().required(),
8+
end_date: joi.number().required()
9+
})
10+
11+
try {
12+
await schema.validateAsync(req.body)
13+
next()
14+
} catch (error) {
15+
logger.error(`Error validating createChallenge payload : ${error}`)
16+
res.boom.badRequest(error.details[0].message)
17+
}
18+
}
19+
20+
module.exports = {
21+
createChallenge
22+
}

models/challenges.js

Lines changed: 7 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -66,15 +66,17 @@ const fetchParticipantsData = async (participants) => {
6666

6767
const postChallenge = async (challengeData) => {
6868
try {
69-
const response = await challengesModel.add({
69+
const { start_date: startDate, end_date: endDate } = challengeData
70+
const startdate = new Firestore.Timestamp(startDate, 0)
71+
const enddate = new Firestore.Timestamp(endDate, 0)
72+
const challengeRef = await challengesModel.add({
7073
...challengeData,
74+
start_date: startdate,
75+
end_date: enddate,
7176
participants: [],
7277
is_active: true
7378
})
74-
const allChallenges = await fetchChallenges()
75-
if (response.id && allChallenges.length > 0) {
76-
return allChallenges
77-
} else return ''
79+
return challengeRef.id
7880
} catch (err) {
7981
logger.error(ERROR_MESSAGE, err)
8082
throw err

public/apiSchema.json

Lines changed: 1 addition & 1 deletion
Large diffs are not rendered by default.

routes/challenges.js

Lines changed: 8 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@ const express = require('express')
22
const router = express.Router()
33
const authenticate = require('../middlewares/authenticate')
44
const challenges = require('../controllers/challenge')
5+
const { createChallenge } = require('../middlewares/validators/challenges')
56

67
/**
78
* @swagger
@@ -29,6 +30,12 @@ const challenges = require('../controllers/challenge')
2930
* application/json:
3031
* schema:
3132
* $ref: '#/components/schemas/errors/serverUnavailable'
33+
*/
34+
router.get('/', authenticate, challenges.fetchChallenges)
35+
36+
/**
37+
* @swagger
38+
* /challenges:
3239
* post:
3340
* summary: Post new challenge
3441
* tags:
@@ -53,10 +60,7 @@ const challenges = require('../controllers/challenge')
5360
* schema:
5461
* $ref: '#/components/schemas/errors/serverUnavailable'
5562
*/
56-
router
57-
.route('/')
58-
.get(authenticate, challenges.sendChallengeResponse)
59-
.post(authenticate, challenges.sendChallengeResponse)
63+
router.post('/', authenticate, createChallenge, challenges.createChallenge)
6064

6165
/**
6266
* @swagger
@@ -88,7 +92,6 @@ router
8892
* application/json:
8993
* schema:
9094
* $ref: '#/components/schemas/errors/serverUnavailable'
91-
*
9295
*/
9396
router.post('/subscribe', authenticate, challenges.subscribeToChallenge)
9497

0 commit comments

Comments
 (0)