Git Product home page Git Product logo

json-rpc-protocol's Introduction

json-rpc-protocol Build Status

JSON-RPC 2 protocol messages parsing and formatting

Install

Installation of the npm package:

> npm install --save json-rpc-protocol

Usage

Errors

// ES5
var protocol = require('json-rpc-protocol')

var JsonRpcError = protocol.JsonRpcError
var InvalidJson = protocol.InvalidJson
var InvalidRequest = protocol.InvalidRequest
var MethodNotFound = protocol.MethodNotFound
var InvalidParameters = protocol.InvalidParameters

// ES6
import {
  JsonRpcError,
  InvalidJson,
  InvalidRequest,
  MethodNotFound,
  InvalidParameters
} from 'json-rpc-protocol'

This is the base error for all JSON-RPC errors:

throw new JsonRpcError(message, code)

The JSON-RPC 2 specification defined also the following specialized errors:

// Parse error: invalid JSON was received by the peer.
throw new InvalidJson()

// Invalid request: the JSON sent is not a valid JSON-RPC 2 message.
throw new InvalidRequest()

// Method not found: the method does not exist or is not available.
throw new MethodNotFound(methodName)

// Invalid parameters.
throw new InvalidParameters(data)

Custom errors can of course be created, they just have to inherit JsonRpcError:

// ES5
function MyError () {
  JsonRpcError.call(this, 'my error', 1)
}
MyError.prototype = Object.create(JsonRpcError.prototype, {
  constructor: {
    value: MyError
  }
})

// ES6
class MyError extends JsonRpcError {
  constructor () {
    super('my error', 1)
  }
}

Parsing

// ES5
var parse = require('json-rpc-protocol').parse

// ES6
import {parse} from 'json-rpc-protocol'

The parse() function parses, normalizes and validates JSON-RPC 1 or JSON-RPC 2 messages.

These message can be either JS objects or JSON strings (they will be parsed automatically).

This function may throws:

  • InvalidJson: if the string cannot be parsed as a JSON;
  • InvalidRequest: if the message is not a valid JSON-RPC message.
parse('{"jsonrpc":"2.0", "method": "foo", "params": ["bar"]}')
// → {
//   [type: 'notification']
//   jsonrpc: '2.0',
//   method: 'foo',
//   params: ['bar']
// }

parse('{"jsonrpc":"2.0", "id": 0, "method": "add", "params": [1, 2]}')
// → {
//   [type: 'request']
//   jsonrpc: '2.0',
//   id: 0,
//   method: 'add',
//   params: [1, 2]
// }

parse('{"jsonrpc":"2.0", "id": 0, "result": 3}')
// → {
//   [type: 'response']
//   jsonrpc: '2.0',
//   id: 0,
//   result: 3
// }

A parsed message has a non enumerable property type set to easily differentiate between types of JSON-RPC messages.

Formatting

// ES5
var format = require('json-rpc-protocol').format

// ES6
import {format} from 'json-rpc-protocol'

The format.*() functions can be used to create valid JSON-RPC messages (as JavaScript strings).

Notification

format.notification('foo', ['bars'])
// → {
//   "jsonrpc": "2.0",
//   "method": "foo",
//   "params": ["bar"]
// }

The last argument, the parameters of the notification, is optional and defaults to undefined.

Request

The last argument, the parameters of the request, is optional and defaults to undefined.

format.request(0, 'add', [1, 2])
// → {
//   "jsonrpc": "2.0",
//   "id": 0,
//   "method": "add",
//   "params": [1, 2]
// }

Response

A successful response:

format.response(0, 3)
// → {
//   "jsonrpc": "2.0",
//   "id": 0,
//   "result": 3
// }

A failed response:

var MethodNotFound = require('json-rpc-protocol').MethodNotFound

format.error(0, new MethodNotFound('add'))
// → {
//   "jsonrpc": "2.0",
//   "id": 0,
//   "error": {
//     "code": -3601,
//     "message": "method not found: add",
//     "data": "add"
//   }
// }

Note: the error to format must be an instance of JsonRpcError or it will be automatically replaced by an unknown error for security reasons.

Development

Installing dependencies

> npm install

Compilation

The sources files are watched and automatically recompiled on changes.

> npm run dev

Tests

> npm run test-dev

Related

Contributions

Contributions are very welcomed, either on the documentation or on the code.

You may:

  • report any issue you've encountered;
  • fork and create a pull request.

License

ISC © Julien Fontanet

json-rpc-protocol's People

Contributors

julien-f avatar

Watchers

Joshua Thomas avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.