http-jsonrpc-server

Build Status Codacy BadgebitHound Code dependencies Status devDependencies Status

A simple and lightweight library for creating a JSON-RPC 2.0 compliant HTTP server.

This package complies with the JSON-RPC 2.0 and JSON-RPC 2.0 Transport: HTTP specifications.

Install

To install http-jsonrpc-server in the current directory, run:

npm install http-jsonrpc-server --save

Usage

Below is code to create a server with two exposed methods and begin listening on a given port.

const RpcServer = require('http-jsonrpc-server');

function sum(arr) {
  let total = 0;
  for (let n = 0; n < arr.length; n += 1) {
    total += arr[n];
  }
  return total;
}

async function wait(params) {
  return new Promise((resolve) => {
    setTimeout(() => {
      resolve(true);
    }, params.ms);
  });
}

const rpcServer = new RpcServer({
  methods: {
    sum,
    wait,
  }
});
rpcServer.setMethod('sum', sum);
rpcServer.setMethod('wait', wait);
rpcServer.listen(9090).then(() => {
  console.log('server is listening at http://127.0.0.1:9090/');
}

Specifying a Path

const rpcServer = new RpcServer({
  path: '/api'
});
rpcServer.listen(9090).then(() => {
  console.log('server is listening at http://127.0.0.1:9090/api');
}

Optional Callbacks

onServerError will be called if the server emits an error. onRequest, and onRequestError, and onResult will be called each time a method is called, throws an error, or returns a result respectively.

const rpcServer = new RpcServer({
  onRequest: (request) => {
    console.log(JSON.stringify(request));
    // sample output: {"jsonrpc":"2.0","id":1,"method":"sum","params":[1,2,3]}
  },
  onRequestError = (err, id) => {
    console.error('request ' + id + ' threw an error: ' + err);
  },
  onResult = (result, id) => {
    console.log(result); // sample output: 6
  },
  onServerError: (err) => {
    console.error('the server threw an error: ' + err)
  },
});

Adding/Updating Methods

You can register new methods or updates existing ones after the server has been created.

rpcServer.setMethod('sum', sum);

Closing the Server

rpcServer.close().then(() => {
  console.log('server stopped listening');
}

Native HTTP Server

You can access the underlying http.Server object with rpcServer.server.

if (rpcServer.server.listening) {
  console.log('server is listening');
}

Exposed Constants

console.log(rpcServer.PARSE_ERROR); // -32700
console.log(rpcServer.INVALID_REQUEST); // -32600
console.log(rpcServer.METHOD_NOT_FOUND); // -32601
console.log(rpcServer.INVALID_PARAMS); // -32602
console.log(rpcServer.SERVER_ERROR); // -32000
console.log(rpcServer.SERVER_ERROR_MAX); // -32099

API Documentation

RpcServer

Class representing a HTTP JSON-RPC server

Kind: global class

new RpcServer(options)

Create an RpcServer

Param Type Description
options Object Optional parameters for the server.
options.methods Object A map of method names to functions. Method functions are passed one parameter which will either be an Object or a string array.
options.path string The path for the server.
options.onRequest function Callback for when requests are received, it is passed an Object representing the request.
options.onRequestError function Callback for when requested methods throw errors, it is passed an error and request id.
options.onResult function Callback for when requests are successfully returned a result.
options.onServerError function Callback for server errors, it is passed an Error.

rpcServer.setMethod(name, method)

Set a method

Kind: instance method of RpcServer

Param Type Description
name string The name of the method
method function The function to be called for this method. Method functions are passed one parameter which will either be an Object or a string array.

rpcServer.listen(port) ⇒ Promise

Begin listening on a given port

Kind: instance method of RpcServer Returns: Promise - A promise that resolves to true once the server is listening. On error or invalid port number the promise will be rejected with an Error.

Param Type Description
port number The port number to listen on

rpcServer.close() ⇒ Promise

Stop listening on all ports

Kind: instance method of RpcServer Returns: Promise - A promise that resolves to true once the server stops listening. On error the promise will be rejected with an Error.

Sample Requests

Here are some sample requests made against the server created in the first usage example.

Sum

POST / HTTP/1.1
Host: 127.0.0.1:9090
Content-Type: application/json
Accept: application/json
Content-Length: 56

{"jsonrpc":"2.0","id":1,"method":"sum","params":[1,2,3]}
connection: close
content-type: application/json
content-length: 35

 {"jsonrpc":"2.0","id":1,"result":6}

Sum (Batched)

POST / HTTP/1.1
Host: 127.0.0.1:9090
Content-Type: application/json
Accept: application/json
Content-Length: 115

[{"jsonrpc":"2.0","id":1,"method":"sum","params":[1,2,3]},{"jsonrpc":"2.0","id":2,"method":"sum","params":[4,5,6]}]
connection: close
content-type: application/json
content-length: 74

[{"jsonrpc":"2.0","id":1,"result":6},{"jsonrpc":"2.0","id":2,"result":15}]

Wait

POST / HTTP/1.1
Host: 127.0.0.1:9090
Content-Type: application/json
Accept: application/json
Content-Length: 59

{"jsonrpc":"2.0","id":1,"method":"wait","params":{"ms":50}}
connection: close
content-type: application/json
content-length: 38

{"jsonrpc":"2.0","id":1,"result":true}

Built With

Share this project:
×

Updates