Created
March 16, 2017 21:05
-
-
Save kaosat-dev/3e6a36c8d5d44e86df298ab72acee170 to your computer and use it in GitHub Desktop.
Cycle.js 'simplified' api for chaining http request (for example)
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
import { of } from 'most' | |
import { div } from 'foo' | |
import { makeSubject } from 'bar' | |
function main (sources) { | |
const request$ = makeSubject() // subject of requests, for all requests | |
// const {request$, response$} = makeRequest1(sources, 'http://localhost:8080/hello') | |
// const response$ = makeRequest2(sources, requests$, 'http://localhost:8080/hello') | |
const req = (url, opts) => makeRequest2(sources, request$, url, opts) | |
const response$ = req('http://my-api.com/hello') | |
.flatMap(function (helloResult) { | |
const secondaryUrl = `https://my-api.com/printers/${helloResult}` | |
return req(secondaryUrl) | |
}) | |
.flatMap(function (secondaryResult) { | |
const secondaryUrl = `https://my-api.com/queueSubmit/${secondaryResult}` | |
const data = {filename: 'foo.stl'} | |
return req(secondaryUrl, {method: 'POST', data}) | |
}) | |
let vdom$ = response$ | |
.map(res => res.text) // We expect this to be "Hello World" | |
.startWith('Loading...') | |
.map(text => div('.container', [ | |
h1(text) | |
]) | |
) | |
return { | |
DOM: vdom$, | |
HTTP: request$ | |
} | |
} | |
function makeRequest1 (sources, url, options) { | |
const defaults = { | |
category: 'makeRequest' + Math.random(), | |
method: 'GET', | |
data: undefined | |
} | |
options = Object.assign({}, defaults, options) | |
const {category, method, data} = options | |
let request$ = of({ | |
url, // GET method by default | |
method, | |
category, | |
data | |
}) | |
let response$ = sources.HTTP | |
.select(category) | |
.flatten() | |
return {request$, response$} | |
} | |
// in this version, requests$ is a subject | |
function makeRequest2 (sources, request$, url, options) { | |
const defaults = { | |
category: 'makeRequest' + Math.random(), | |
method: 'GET', | |
data: undefined | |
} | |
options = Object.assign({}, defaults, options) | |
const {category, method, data} = options | |
request$.next({ | |
url, // GET method by default | |
method, | |
category, | |
data | |
}) | |
let response$ = sources.HTTP | |
.select(category) | |
.flatten() | |
return response$ | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment