Skip to content

Instantly share code, notes, and snippets.

@protometa
Created June 9, 2017 16:54
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 protometa/3bf2b7002624e80ac4e64bc154770fac to your computer and use it in GitHub Desktop.
Save protometa/3bf2b7002624e80ac4e64bc154770fac to your computer and use it in GitHub Desktop.
Paging JSON API as a lazy Highland stream
const _ = require('highland')
const JSONstream = require('JSONstream')
require('isomorphic-fetch')
const highlandFetch = require('highland-fetch')
Response.prototype.highland = highlandFetch.highlandResponse
// pages through next links and returns json objects as one continuous stream
function pageStream (url) {
return _(fetch(url, { headers: new Headers({ Accept: 'application/json' }) }))
.flatMap(res => {
if (!res.ok) throw new Error(res.status)
const next = _(res.headers.get('link').split(','))
.filter(link => (/rel="next"/).test(link))
.map(link => link.match(/<(.*)>/)[1])
.flatMap(pageStream)
return res.highland()
.through(highlandFetch.textDecoder)
.through(JSONstream.parse('*'))
.concat(next)
})
}
// lazily stream and parse on the fly
pageStream('https://example.com/paging-api')
.stopOnError(err => console.error(err.stack))
.each(_.log)
.done(() => console.log('DONE'))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment