Skip to content

Instantly share code, notes, and snippets.

@tomaskikutis
Created May 13, 2017 20:09
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tomaskikutis/100c0ecaf7373da1f57ca186ef449e8c to your computer and use it in GitHub Desktop.
Save tomaskikutis/100c0ecaf7373da1f57ca186ef449e8c to your computer and use it in GitHub Desktop.
hacker-news-top-10
const topStoriesUrl = "https://hacker-news.firebaseio.com/v0/topstories.json";
const getStoryInfoUrl = storyId => `https://hacker-news.firebaseio.com/v0/item/${storyId}.json`
const getUserInfoUrl = userId => `https://hacker-news.firebaseio.com/v0/user/${userId}.json`
function fetchJson(method, url){
return new Promise(function(resolve, reject){
var oReq = new XMLHttpRequest();
oReq.addEventListener("load", function(){
resolve(JSON.parse(this.responseText));
});
oReq.addEventListener("error", reject);
oReq.addEventListener("abort", reject);
oReq.open(method, url);
oReq.send();
});
}
function getStoryHtml(storyAndAuthorJson){
const storyInfo = storyAndAuthorJson.storyJson;
const authorInfo = storyAndAuthorJson.authorJson;
return `
<div>
⬆️${storyInfo.score}
<a href="${storyInfo.url}">${storyInfo.title}</a>
| ⏰${storyInfo.time}
| by <strong>${storyInfo.by}</strong>(${authorInfo.karma})
</div>
`;
}
function getStoryAndAuthorJson(storyJson){
return new Promise(function(resolve, reject){
fetchJson("GET", getUserInfoUrl(storyJson.by))
.then( authorJson => resolve({storyJson, authorJson}) )
.catch( reason => reject(reason) )
});
}
fetchJson("GET", topStoriesUrl)
.then( (topStoriesIds) => {
return Promise.all(
topStoriesIds
.slice(0,10)
.map( storyId => fetchJson("GET", getStoryInfoUrl(storyId) )
)
)
})
.then( (topStoriesJson) => {
return Promise.all(
topStoriesJson.map( storyJson => getStoryAndAuthorJson(storyJson) )
)
})
.then( res => {
document.body.innerHTML = res.map(getStoryHtml).join("")
})
.catch( reason => document.body.innerHTML = "Error:" + JSON.stringify(reason) )
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment