Skip to content

Instantly share code, notes, and snippets.

@ishiduca
Last active September 19, 2016 23:17
Show Gist options
  • Save ishiduca/5da358c5da8c774b92fb375efeba27b5 to your computer and use it in GitHub Desktop.
Save ishiduca/5da358c5da8c774b92fb375efeba27b5 to your computer and use it in GitHub Desktop.
blue-frog-b - create a JSON-RPC 2.0 server/client that corresponds to the batch processing
var hyperquest = require('hyperquest')
var through = require('through2')
var frog = require('blue-frog-b')
var rpc = require('blue-frog-stream')
window.onload = function () {
var hyp = hyperquest.post('http://0.0.0.0:9999/rpc')
var stream = frog()
hyp.on('error', onError)
stream.on('error', onError)
stream
.pipe(new rpc.request.BatchStream(true)).on('error', onError)
.pipe(through.obj(function (json, _, done) {
hyp.setHeader('content-type', 'applicatin/json')
hyp.setHeader('content-length', Buffer.byteLength(json))
done(null, json)
}))
.pipe(hyp)
.pipe(stream)
var sum = stream.request('sum', [1, 2, 3])
var mul = stream.request('multi', [4, 5])
sum.on('error', onError)
mul.on('error', onError)
sum.once('data', function (result) {
console.log('sum(1,2,3) -> %d', result)
// sum(1,2,3) -> 6
})
mul.once('data', function (result) {
console.log('multi(4, 5) -> %d', result)
// multi(4, 5) -> 20
})
stream.batch([sum, mul])
}
function onError (err) {
console.log(String(err))
;('data' in err) && console.log(err.data)
}
const http = require('http')
const ecstatic = require('ecstatic')(__dirname + '/static')
const rpc = require('blue-frog-b')({prefix: '/rpc'})
const app = http.createServer(ecstatic)
function add (a, b) {return Number(a) + Number(b)}
function multi (a, b) {return Number(a) * Number(b)}
rpc.on('sum', (params, done) => {
setTimeout(() => {
try { done(null, params.reduce(add, 0)) }
catch (err) { done(err) }
}, 800)
})
rpc.on('multi', (params, done) => {
setTimeout(() => {
try { done(null, multi.apply(null, params)) }
catch (err) { done(err) }
}, 800)
})
rpc.install(app)
if (! module.parent) {
app.listen(9999, () => {
console.log('server listen on port %s', app.address().port)
})
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment