Created
October 15, 2017 19:48
-
-
Save hamidzr/d884141cefb72ab2282f9856491154f3 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* @author Hamid Zare | |
* @email hamid.zare@vanderbilt.edu | |
*/ | |
// the program would have been much faster and easier to write if the | |
// pagination was predictabe, meaning that I could grab the nth page directly | |
// in that case it would have been possible to fire all the request concurrently | |
// (after gettig the first response) | |
// assuming ES6 and Node v6 | |
const axios = require('axios'), | |
BASE_URI = 'https://api.clever.com', | |
TOKEN = 'DEMO_TOKEN' || process.env.CLEVER_TOKEN; | |
// grabs all the sections one by one | |
let grabSections = () => { | |
let sections = []; // accumulate :( | |
let grabPage = (relativePath) => { | |
let url = BASE_URI + (relativePath || ''); | |
return axios({ | |
url, | |
headers: { | |
'Authorization': `Bearer ${TOKEN}` | |
} | |
}) | |
.then(response => { | |
let {data, links} = response.data; | |
// TODO push only the sections. | |
sections = sections.concat(data); | |
// grab the rest of the data if exists; | |
let nextLink = links.find(link => link.rel === 'next'); | |
if (nextLink){ | |
// do this whole process again | |
return grabPage(nextLink.uri); | |
} | |
// console.log(response.data); | |
// console.log(Object.keys(response.data)); | |
}) | |
}; | |
return grabPage('/v1.2/sections?').then( () => { | |
// done grabbing all the pages | |
return sections; | |
}).catch(err => { | |
console.error(err); | |
throw err; | |
}); | |
}; | |
grabSections() | |
.then( sections => { | |
let numberOfSections = sections.length; | |
// calculate the number of students | |
let numberOfStudents = sections | |
.map(section => section.data.students.length) | |
.reduce( (acc, numStudents) => { | |
return acc + numStudents; | |
}, 0 ); | |
let average = numberOfStudents / numberOfSections; | |
console.log('#', numberOfStudents, 'students'); | |
console.log('#', numberOfSections, 'sections'); | |
console.log('Average per section is:', average, 'or', Math.floor(average)); | |
return average; | |
}) | |
.catch(console.error); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment