Skip to content

statistics endpoint #443

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Dec 10, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions config/default.js
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,9 @@ module.exports = {
// in bytes
FILE_UPLOAD_SIZE_LIMIT: process.env.FILE_UPLOAD_SIZE_LIMIT
? Number(process.env.FILE_UPLOAD_SIZE_LIMIT) : 50 * 1024 * 1024, // 50M
// TODO: change this to localhost
SUBMISSIONS_API_URL: process.env.SUBMISSIONS_API_URL || 'https://api.topcoder-dev.com/v5/submissions',
MEMBERS_API_URL: process.env.MEMBERS_API_URL || 'https://api.topcoder-dev.com/v5/members',
RESOURCES_API_URL: process.env.RESOURCES_API_URL || 'http://localhost:4000/v5/resources',
// TODO: change this to localhost
RESOURCE_ROLES_API_URL: process.env.RESOURCE_ROLES_API_URL || 'http://api.topcoder-dev.com/v5/resource-roles',
Expand Down
49 changes: 48 additions & 1 deletion src/common/helper.js
Original file line number Diff line number Diff line change
Expand Up @@ -959,6 +959,51 @@ async function getGroupById (groupId) {
}
}

/**
* Get challenge submissions
* @param {String} challengeId the challenge id
* @returns {Array} the submission
*/
async function getChallengeSubmissions (challengeId) {
const token = await getM2MToken()
let allSubmissions = []
// get search is paginated, we need to get all pages' data
let page = 1
while (true) {
const result = await axios.get(`${config.SUBMISSIONS_API_URL}?challengeId=${challengeId}`, {
headers: { Authorization: `Bearer ${token}` },
params: {
page,
perPage: 100
}
})
const ids = result.data || []
if (ids.length === 0) {
break
}
allSubmissions = allSubmissions.concat(ids)
page += 1
if (result.headers['x-total-pages'] && page > Number(result.headers['x-total-pages'])) {
break
}
}
return allSubmissions
}

/**
* Get member by ID
* @param {String} userId the user ID
* @returns {Object}
*/
async function getMemberById (userId) {
const token = await getM2MToken()
const res = await axios.get(`${config.MEMBERS_API_URL}?userId=${userId}`, {
headers: { Authorization: `Bearer ${token}` }
})
if (res.data.length > 0) return res.data[0]
return {}
}

module.exports = {
wrapExpress,
autoWrapExpress,
Expand Down Expand Up @@ -1000,5 +1045,7 @@ module.exports = {
ensureUserCanModifyChallenge,
userHasFullAccess,
sumOfPrizes,
getGroupById
getGroupById,
getChallengeSubmissions,
getMemberById
}
13 changes: 12 additions & 1 deletion src/controllers/ChallengeController.js
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,16 @@ async function getChallenge (req, res) {
res.send(result)
}

/**
* Get challenge statistics
* @param {Object} req the request
* @param {Object} res the response
*/
async function getChallengeStatistics (req, res) {
const result = await service.getChallengeStatistics(req.authUser, req.params.challengeId)
res.send(result)
}

/**
* Fully update challenge
* @param {Object} req the request
Expand Down Expand Up @@ -77,5 +87,6 @@ module.exports = {
getChallenge,
fullyUpdateChallenge,
partiallyUpdateChallenge,
deleteChallenge
deleteChallenge,
getChallengeStatistics
}
6 changes: 6 additions & 0 deletions src/routes.js
Original file line number Diff line number Diff line change
Expand Up @@ -61,6 +61,12 @@ module.exports = {
scopes: [DELETE, ALL]
}
},
'/challenges/:challengeId/statistics': {
get: {
controller: 'ChallengeController',
method: 'getChallengeStatistics',
}
},
'/challenge-types': {
get: {
controller: 'ChallengeTypeController',
Expand Down
46 changes: 45 additions & 1 deletion src/services/ChallengeService.js
Original file line number Diff line number Diff line change
Expand Up @@ -1270,6 +1270,49 @@ async function validateWinners (winners, challengeId) {
}
}

/**
* Get challenge statistics
* @param {Object} currentUser the user who perform operation
* @param {String} id the challenge id
* @returns {Object} the challenge with given id
*/
async function getChallengeStatistics (currentUser, id) {
const challenge = await getChallenge(currentUser, id)
// for now, only Data Science challenges are supported
if (challenge.type !== 'Challenge' && challenge.track !== 'Data Science') {
throw new errors.BadRequestError(`Challenge of type ${challenge.type} and track ${challenge.track} does not support statistics`)
}
// get submissions
const submissions = await helper.getChallengeSubmissions(challenge.id)
// for each submission, load member profile
const map = {}
for (const submission of submissions) {
if (!map[submission.memberId]) {
// Load member profile and cache
const member = await helper.getMemberById(submission.memberId)
map[submission.memberId] = {
photoUrl: member.photoURL,
rating: _.get(member, 'maxRating.rating', 0),
ratingColor: _.get(member, 'maxRating.ratingColor', '#9D9FA0'),
homeCountryCode: member.homeCountryCode,
handle: member.handle,
submissions: []
}
}
// add submission
map[submission.memberId].submissions.push({
created: submission.created,
score: _.get(_.find(submission.review || [], r => r.metadata), 'score', 0)
})
}
return _.map(_.keys(map), (userId) => map[userId])
}

getChallengeStatistics.schema = {
currentUser: Joi.any(),
id: Joi.id()
}

/**
* Update challenge.
* @param {Object} currentUser the user who perform operation
Expand Down Expand Up @@ -2058,7 +2101,8 @@ module.exports = {
getChallenge,
fullyUpdateChallenge,
partiallyUpdateChallenge,
deleteChallenge
deleteChallenge,
getChallengeStatistics
}

logger.buildService(module.exports)