Created
June 25, 2017 01:42
-
-
Save vikikamath/723d68c1f0dc6d80c40824ed08e562b0 to your computer and use it in GitHub Desktop.
Fetch hackernews API using es6 generator functions and fetch API on Node@6
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
const fetch = require( 'node-fetch' ) // skip if in Chrome Latest version | |
const hnItemUrlBase = 'https://hacker-news.firebaseio.com/v0/item/' // HN Url Base | |
const hnItemId = 14561637 // real itemId | |
// hacker news required format | |
const makeItemUrl = ( prefix, itemId ) => `${prefix}${itemId}.json` | |
// fetch Wrapper | |
const fetchWrapper = ( prefix, itemId ) => { | |
const itemUrl = makeItemUrl( prefix, itemId ) | |
return fetch( itemUrl ) | |
// get json from body | |
.then( res => res.json()) | |
.then( jsonRes => { | |
// pass the value to yield back in the generator function | |
it.next( jsonRes ) | |
}) | |
} | |
// do a levelOrder on Async Tree of Items. Story Item is at the root passed | |
function *levelOrder( prefix, itemId ) { | |
const queue = [] | |
// wait until json is received | |
let current = yield fetchWrapper( prefix, itemId ) | |
queue.push( current ) | |
while ( queue.length ) { | |
current = queue.shift(); | |
console.log( current.id ); | |
if ( current.kids ) { | |
for ( let kid of current.kids ) { | |
current = yield fetchWrapper( prefix, kid ) | |
queue.push( current ) | |
} | |
} | |
} | |
} | |
// construct | |
const it = levelOrder( hnItemUrlBase, hnItemId ) | |
it.next( ) // start |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment