Skip to content

Instantly share code, notes, and snippets.

@staltz
Created June 28, 2015 11:55
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save staltz/c7142dec80ac077ef8ed to your computer and use it in GitHub Desktop.
Save staltz/c7142dec80ac077ef8ed to your computer and use it in GitHub Desktop.
Draft of Cycle.js HTTP Driver
const Cycle = require('@cycle/core');
const CycleWeb = require('@cycle/web');
const makeHTTPDriver = require('@cycle/http');
const h = CycleWeb.h;
function main(responses) {
const GITHUB_SEARCH_API = 'https://api.github.com/search/repositories?q=';
// This essentially models when search requests are supposed
// to happen
const searchRequest$ = responses.DOM.get('.field', 'input')
.debounce(500)
.map(ev => ev.target.value)
.filter(query => query.length > 0)
.map(q => GITHUB_SEARCH_API + encodeURI(q));
const otherRequest$ = Cycle.Rx.Observable.interval(1000).take(2)
.map(() => 'http://www.google.com');
const vtree$ = responses.HTTP
// We filter responses.HTTP because it includes response
// observables from both google.com and api.github.com,
// and we are only interested in the latter
.filter(res$ => res$.request.indexOf(GITHUB_SEARCH_API) === 0)
// responses.HTTP is an Observable of Observable, so we need to
// flatten it. The reason why it comes as an Obs of Obs is because
// the app developer should choose whether to flatMap or flatMapLatest.
.flatMapLatest(x => x)
.map(res => JSON.parse(res.response).items)
.startWith([])
.map(results =>
h('div', [
h('label.label', 'Search:'),
h('input.field', {attributes: {type: 'text'}}),
h('hr'),
h('ul.search-results', results.map(result =>
h('li.search-result', [
h('a', {href: result.html_url}, result.name)
])
))
])
);
return {
DOM: vtree$,
// Request both api.github.com and google.com
// endpoints. All HTTP requests should be sent to
// this driver.
HTTP: searchRequest$.merge(otherRequest$)
};
}
Cycle.run(main, {
DOM: CycleWeb.makeDOMDriver('.js-container'),
HTTP: makeHTTPDriver()
});
var Rx = require('rx-dom');
// makeHTTPDriver is a factory, but it has no parameters.
// It would be simpler to just export httpDriver() function,
// but maybe it would make sense to give some parameters
// to the factory. I just don't know which parameters would
// those be. A cache? Suggestions please.
function makeHTTPDriver() {
return function httpDriver(request$) {
return request$.map(function (request) {
var response$ = Rx.DOM.ajax(request);
response$.request = request;
return response$;
});
}
}
module.exports = makeHTTPDriver;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment