Last active
March 3, 2016 13:12
-
-
Save fuunnx/d0bae44e4bfe13228511 to your computer and use it in GitHub Desktop.
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 Rx from 'rx' | |
// sources$ | |
const request$ = new Rx.Subject() | |
const http = require('http') | |
const fs = require('fs') | |
const hostname = '127.0.0.1' | |
const port = 1337 | |
http.createServer( | |
(req, res) => { | |
request$.onNext({ | |
body: req, | |
res | |
}) | |
}) | |
.listen(port, hostname, () => { | |
console.log(`Server running at http://${hostname}:${port}/`) | |
}); | |
// helpers | |
const mapRequest = (f) => (request) => ({ | |
...request, | |
body: f(request.body), | |
}) | |
const flatMapRequest = (f) => (request) => { | |
return Rx.Observable.of(request.body) | |
.flatMap(f) | |
.map( | |
body => ({ | |
...request, | |
body, | |
}) | |
) | |
} | |
function readFile(fileName) { | |
return new Promise((resolve, reject) => { | |
fs.readFile( | |
'./public/' + fileName, | |
(error, data) => error ? reject(error) : resolve(data) | |
) | |
}) | |
} | |
//main | |
const response$ = request$ | |
.map(mapRequest(x => 'index.html')) | |
.flatMap(flatMapRequest(readFile) | |
//sink$ | |
response$.subscribe( | |
({ | |
body, | |
res | |
}) => { | |
res.end(body) | |
} | |
) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment