nodester-json-rpc
v0.0.2
Published
JSON-RPC middleware for nodester.
Readme
nodester JSON-RPC
JSON-RPC middleware for nodester.
- Follows JSON-RPC 2.0 Specification
Installation
Install with NPM
npm install -S nodester-json-rpcUsage
nodester-json-rpc can only be used with a nodester router:
const Router = require('nodester/router');
const rpc = require('nodester-json-rpc/rpc');
const Path = require('path');
// For example: ../src/app/providers/Users.provider.js
const providersPath = Path.join(process.cwd(), 'src', 'app', 'providers');
const router = new Router({ providersPath });
// Define a route.
router.add.route(
v1('post /rpc/users'),
rpc({ providedBy: 'Users' })
);Then make a POST request with a body formatted like this:
{
"jsonrpc": "2.0",
"id": 1,
"method": "blockById",
"params": {
"id": 24232
}
}Running middlewares before the provider method
Pass a before option to run one or more middlewares before the resolved provider method is called — useful for authentication, authorization or request enrichment:
router.add.route(
v1('post /rpc/users'),
rpc({
before: [ authenticate, authorize ],
providedBy: 'Users'
})
);before accepts an array of middlewares, or a single middleware function. Each one receives (req, res, next) and runs in order, after the request has been validated (so req.rpc — holding id, method and params — is already populated):
function authenticate(req, res, next) {
// Short-circuit by responding here (the provider method won't run):
if (!req.headers.authorization) {
return res.status(401).json({ error: 'Unauthorized' });
}
// Or call next() to continue to the next middleware / provider method:
return next();
}A middleware may:
- call
next()to proceed to the next middleware, or — once the chain is exhausted — to the provider method; - end the response without calling
next()to short-circuit the call, so the provider method is skipped; throw, or callnext(error), to reject — the error is returned as a JSON-RPC error response.
License
Copyright
Copyright 2024-present Mark Khramko
