async rpc over http
JavaScript
Fetching latest commit…
Cannot retrieve the latest commit at this time.
Permalink
Failed to load latest commit information.
test
.gitignore
.jshintrc
.travis.yml
LICENSE
README.md
index.js
package.json

README.md

http rpc

rpc over http using streams

Build Status NPM version

Build both the client and server from a common interface.

Install

npm install --save lib-http-rpc

Usage

Common

Specify a common API between the client and server.

var iface = {
  getUser: {
    method : 'GET',
    route  : '/user/:name',
  },
  setUser: {
    method : 'POST',
    route  : '/user/:name',
  },
  listUsers: {
    method : 'GET',
    route  : '/users',
    options: {
      limit: 10,
      order: 'desc'
    }
  }
};

Create an rpc from your interface.

var RPC = require('lib-http-rpc')();
var rpc = RPC.NewFromInterface(iface);

Server

Define your server application without any http dependencies.

var solidify = require('lib-stream-solidify');
var liquify  = require('lib-stream-liquify');

function App() {
  this.users = {};
}

App.prototype.getUser = function (stream, params) {
  var name = params.name;
  var user = this.users[name];

  // this causes an HTTP 404 error
  if (!user) throw new RPC.Error(404, 'user not found');

  stream.write(JSON.stringify(user));
};

App.prototype.setUser = function (stream, params) {
  var name  = params.name;
  var users = this.users;

  // parse incoming stream as json
  solidify(stream).json(function (err, obj) {
    if (err) throw err;

    users[name] = obj;

    // send response
    stream.end();
  });
};

App.prototype.listUsers = function (stream, params) {
  var limit = params.limit;
  var order = params.order;
  var users = Object.keys(this.users);

  // sort and limit users
  users = limitBy(limit, sortBy(order, users));

  // turn user object into a stream
  liquify(users).pipe(stream);
};

Generate a router from your application.

var router = rpc.getRouter(new App());
require('http').createServer(router).listen(8080);

Client

Generate a client based on the shared interface.

var client = rpc.getClient(8080, 'localhost');
var stream = client.getUser({name: 'bob'});

stream.end().pipe(process.stdout);