json-rpc-engine
A tool for processing JSON-RPC requests and responses.
Usage
const JsonRpcEngine = let engine =
Build a stack of JSON-RPC processors by pushing middleware to the engine.
engine
Requests are handled asynchronously, stepping down the stack until complete.
let request = id: 1 jsonrpc: '2.0' method: 'hello' engine // There is also a Promise signatureconst response = await engine
Middleware have direct access to the request and response objects.
They can let processing continue down the stack with next()
, or complete the request with end()
.
engine
By passing a return handler to the next
function, you can get a peek at the result before it returns.
engine
Engines can be nested by converting them to middleware using JsonRpcEngine.asMiddleware()
:
const engine = const subengine = engine
async
Middleware
If you require your middleware function to be async
, use createAsyncMiddleware
:
const createAsyncMiddleware = let engine = engine
async
middleware do not take an end
callback.
Instead, the request ends if the middleware returns without calling next()
:
engine
The next
callback of async
middleware also don't take return handlers.
Instead, you can await next()
.
When the execution of the middleware resumes, you can work with the response again.
engine
You can freely mix callback-based and async
middleware:
engine engine
Gotchas
Handle errors via end(err)
, NOT next(err)
.
/* INCORRECT */engine /* CORRECT */engine
However, next()
will detect errors on the response object, and cause
end(res.error)
to be called.
engine