sepc
v1.0.4
Published
Dead simple JSON-RPC server for Node.js.
Downloads
6
Maintainers
Readme
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.
- type:
function
- example: httpServer, wsServer
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>