npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

@koalex/koa-json-rpc

v1.0.3

Published

JSON-RPC 2.0 middleware for Koa.js which implements the https://www.jsonrpc.org/specification

Downloads

26

Readme

koa-json-rpc

JSON-RPC 2.0 middleware for Koa.js which implements the https://www.jsonrpc.org/specification

  • Batch support
  • Parallel handling

Installation

Install using npm:

npm i @koalex/koa-json-rpc --save

API Reference

Jsonrpc ⏏

Kind: Exported class

new Jsonrpc([opts])

Create a new JSON-RPC

| Param | Type | Description | | --- | --- | --- | | [opts] | Object | | | [opts.onerror] | Function | | | [opts.parallel] | Boolean | default is true | | [opts.bodyParser] | Function | koa-bodyparser or async-busboy or some another. |

Examples
Basic usage:

const Koa        = require('koa');
const Router     = require('koa-router');
const bodyParser = require('koa-bodyparser');
const Jsonrpc    = require('@koalex/koa-json-rpc');

const app     = new Koa();
const router  = new Router();

const jsonrpc = new Jsonrpc({
    bodyParser: bodyParser({
        onerror: (err, ctx) => {
            ctx.status = 200;
            ctx.body = Jsonrpc.parseError;
        }
    })
});

jsonrpc.method('someMethod', (ctx, next) => {
    // ctx.jsonrpc available
    /*
        ctx.jsonrpc.request
        ctx.jsonrpc.id
        ctx.jsonrpc.method [[Get]]
        ctx.jsonrpc.params [[Get]]
        ctx.jsonrpc.response
        ctx.jsonrpc.result
        ctx.jsonrpc.error
        ctx.jsonrpc.code
        ctx.jsonrpc.message
        ctx.jsonrpc.data
    */
    ctx.body = 'Hello world!';
});

router.post('/api', jsonrpc.middleware);

app.use(router.routes());
/*
    REQUEST -> {id: 987, jsonrpc: '2.0', method: 'someMethod'}
    RESPONSE <- {jsonrpc: '2.0', id: 987, result: 'Hello world!'}
*/

Additional usage examples:

jsonrpc.method('sum', (ctx, next) => {
    let sum = 0;
    ctx.jsonrpc.params.forEach(num => sum += num);
    ctx.body = sum;
    /*
        also you can:
        ctx.jsonrpc.result = sum;
        ctx.body = ctx.jsonrpc.response;
    */
});
jsonrpc.method('someErrMethod', (ctx, next) => {
    throw new Error('Crash...');
});
jsonrpc.method('someHttpErrMethod', (ctx, next) => {
    ctx.throw(500);
});
/*
    REQUEST -> {id: 1, jsonrpc: '2.0', method: 'sum', params: [1, 2, 3]}
    RESPONSE <- {jsonrpc: '2.0', id: 1, result: 6}
*/
/*
    REQUEST -> {id: 2, jsonrpc: '2.0', method: 'someErrMethod', params: [1, 2, 3]}
    RESPONSE <- {jsonrpc: '2.0', id: 2, error: {code: -32000: message: 'Server error', data: 'Error: Crash...'}}
*/
/*
    REQUEST -> {id: 3, jsonrpc: '2.0', method: 'someHttpErrMethod', params: [1, 2, 3]}
    RESPONSE <- {jsonrpc: '2.0', id: 3, error: {code: -32000: message: 'Server error', data: {message: 'Internal Server Error'}}}
*/

Batch:

const Koa        = require('koa');
const Router     = require('koa-router');
const bodyParser = require('koa-bodyparser');
const Jsonrpc    = require('@koalex/koa-json-rpc');

const app    = new Koa();
const router = new Router();

const jsonrpc = new Jsonrpc({
    bodyParser: bodyParser({
        onerror: (err, ctx) => {
            ctx.status = 200;
            ctx.body = Jsonrpc.parseError;
        }
    })
});

jsonrpc.method('sum', (ctx, next) => {
    let sum = 0;
    ctx.jsonrpc.params.forEach(num => sum += num);
    ctx.body = sum;
});
jsonrpc.method('subtract', (ctx, next) => {
    ctx.body = ctx.jsonrpc.params.minuend - ctx.jsonrpc.params.subtrahend;
});

router.post('/api', jsonrpc.middleware);

app.use(router.routes());

/* 
    REQUEST ->
    [
        {id: 123, jsonrpc: '2.0', method: 'sum', params: [1, 2, 3]},
        {id: 456, jsonrpc: '2.0', method: 'subtract', params: {minuend: 10, subtrahend: 3}}
    ]

    RESPONSE <-
    [
        {id: 123, jsonrpc: '2.0', result: 6},
        {id: 456, jsonrpc: '2.0', result: 7}
    ]
*/

Batch with different instances of Jsonrpc:

const Koa           = require('koa');
const Router        = require('koa-router');
const koaBodyParser = require('koa-bodyparser');
const Jsonrpc       = require('@koalex/koa-json-rpc');

const app     = new Koa();
const router  = new Router();

const bodyParser = koaBodyParser({
    onerror: (err, ctx) => {
        ctx.status = 200;
        ctx.body = Jsonrpc.parseError;
    }
});

const jsonrpc1 = new Jsonrpc();
const jsonrpc2 = new Jsonrpc();

jsonrpc1.method('sum', (ctx, next) => {
    let sum = 0;
    ctx.jsonrpc.params.forEach(num => sum += num);
    ctx.body = sum;
});
jsonrpc2.method('subtract', (ctx, next) => {
    ctx.body = ctx.jsonrpc.params.minuend - ctx.jsonrpc.params.subtrahend;
});

router.post('/api', bodyParser, jsonrpc.middleware, jsonrpc2.middleware);

app.use(router.routes());

/* 
    REQUEST ->
    [
        {id: 1234, jsonrpc: '2.0', method: 'sum', params: [1, 2, 3]},
        {id: 4567, jsonrpc: '2.0', method: 'subtract', params: {minuend: 10, subtrahend: 3}}
    ]

    RESPONSE <-
    [
        {id: 1234, jsonrpc: '2.0', result: 6},
        {id: 4567, jsonrpc: '2.0', result: 7}
    ]
*/

jsonrpc.method(methodName, middleware [,...middleware]) ⇒ Jsonrpc

| Param | Type | Description | | --- | --- | --- | | methodName | String | A String containing the name of the method to be invoked. Method names that begin with the word rpc followed by a period character (U+002E or ASCII 46) are reserved for rpc-internal methods and extensions and MUST NOT be used for anything else. | | middleware | Function | middleware |

jsonrpc.methods [[Get]]⇒ Array

Returns a list of registered methods.

jsonrpc.method('sum', (ctx, next) => {
    // Some code...
});
jsonrpc.method('subtract', (ctx, next) => {
    // Some code...
});

console.log( jsonrpc.methods ); // ['sum', 'subtract']

jsonrpc.middleware [[Get]]⇒ Function

Returns a middleware function which takes arguments ctx and next

Jsonrpc.parseError ⇒ Object

Returns error reponse object: { jsonrpc: '2.0', id: null, error: { code: -32700, message: 'Parse error', } }

Kind: static method of Jsonrpc

Example

const Koa        = require('koa');
const Router     = require('koa-router');
const bodyParser = require('koa-bodyparser');
const Jsonrpc    = require('@koalex/koa-json-rpc');

const app    = new Koa();
const router = new Router();

const jsonrpc = new Jsonrpc({
    bodyParser: bodyParser({
        onerror: (err, ctx) => {
            ctx.status = 200;
            ctx.body = Jsonrpc.parseError;
        }
    })
});

jsonrpc.method('someMethod', (ctx, next) => {
    // ctx.jsonrpc available
});

router.post('/api', jsonrpc.middleware);

app.use(router.routes());

Contributing

Please submit all issues and pull requests to the koalex/koa-json-rpc repository!

Tests

Run tests using npm test.

This project using SemVer for versioning. For the versions available, see the tags on this repository.

This project is licensed under the MIT License - see the LICENSE file for details