sepc

1.0.4 • Public • Published

sepc

Dead simple JSON-RPC over HTTP/WebSockets server for Node.js. Built with jepc and express. If you need a client, try repc.

Installation

npm i sepc

Usage

sepc(methods, options)

HTTP:

import sepc from 'sepc';

const add = (a, b) => a + b;
const sub = (a, b) => a - b;

sepc({ add, sub }).listen(3000);
curl -X POST 'http://localhost:3000' \
  -d '{ "jsonrpc": "2.0", "method": "add", "params": [2, 2], "id": 1 }'

# { "jsonrpc": "2.0", "result": 4, "id": 1 }

WebSockets:

import sepc from 'sepc';

const add = (a, b) => a + b;
const sub = (a, b) => a - b;

sepc.ws({ add, sub }).listen(3000);

Producing errors:

import sepc from 'sepc';
import { JsonRpcError } from 'jepc';

function divide(a, b) {
    if (b === 0) {
        throw new JsonRpcError(-32602, 'Cannot divide by zero');
    }

    return a / b;
}

sepc({ divide }).listen(3000);

Handling errors:

import sepc from 'sepc';

const add = () => {
    throw new Error('Unsupported!');
}

const errorHandler = (error, context, defaultErrorHandler) => {
    console.error(error);

    return defaultErrorHandler(error, context);
};

sepc({ add }, { errorHandler }).listen(3000);

Options

server

Server builder function. Must implement method listen with identical parameters from api's one.

errorHandler

Error handler.

  • type: function
  • example:
const errorHandler = (error, context, defaultErrorHandler) => {
    console.log(error);

    return defaultErrorHandler(error, context);
}

api

Additional parameters for API.

  • type: object

API

listen

Start a server.

  • type: function(port, path, callback)

methods

Available methods.

  • type: Record<string, Method>

Package Sidebar

Install

npm i sepc

Weekly Downloads

0

Version

1.0.4

License

MIT

Unpacked Size

5.07 kB

Total Files

5

Last publish

Collaborators

  • kohutd