Skip to content

Instantly share code, notes, and snippets.

@hassantauqeer
Created January 27, 2020 09:42
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save hassantauqeer/11f11afd2bed8f8fda31d6d9caa9f924 to your computer and use it in GitHub Desktop.
Save hassantauqeer/11f11afd2bed8f8fda31d6d9caa9f924 to your computer and use it in GitHub Desktop.
const API_URL = 'https://jsonmock.hackerrank.com/api/articles?author=';
async function fetchData(query) {
return new Promise(function (resolve, reject) {
https.get(`${API_URL}${query}`, (resp) => {
let data = '';
// A chunk of data has been recieved.
resp.on('data', (chunk) => {
data += chunk;
});
// The whole response has been received. Print out the result.
resp.on('end', () => {
resolve(JSON.parse(data));
}).on("error", (err) => {
reject('Err: ');
});
})
})
}
async function getArticleTitles(author) {
let arrayOfTitles = [], totalPages = 1, currentPage = 1, promises = [];
let response = await fetchData(author);
console.log(response)
totalPages = response.total_pages;
currentPage = response.page;
arrayOfTitles = getTitles(response.data);
for (let i = currentPage + 1; i <= totalPages; i++) {
promises.push(fetchData(`${author}&page=${i}`));
}
let resp = await Promise.all(promises);
arrayOfTitles.push(...getArticlesFromPromise(resp));
return arrayOfTitles;
}
function getArticlesFromPromise(promisesResp) {
let arrayOfTitles = [];
promisesResp.map(article => {
arrayOfTitles.push(...getTitles(article.data));
});
return arrayOfTitles;
}
function getTitles(articles) {
let arrayOfTitles = [];
articles.map(article => {
if (article.title) {
arrayOfTitles.push(article.title)
} else if (article.story_title) {
arrayOfTitles.push(article.story_title)
}
});
return arrayOfTitles;
}
getArticleTitles('patricktomas').then(r => console.log(r));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment