Requests are handled asynchronously, stepping down the stack until complete.
letrequest={id: 1,jsonrpc: '2.0',method: 'hello'};engine.handle(request,function(err,response){// Do something with response.result, or handle response.error});// There is also a Promise signatureconstresponse=awaitengine.handle(request);
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().
async middleware do not take an end callback.
Instead, the request ends if the middleware returns without calling next():
engine.push(createAsyncMiddleware(async(req,res,next)=>{res.result=42;/* The request will end when this returns */}),);
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.push(createAsyncMiddleware(async(req,res,next)=>{res.result=42;awaitnext();/* Your return handler logic goes here */addToMetrics(res);}),);
You can freely mix callback-based and async middleware:
If your middleware has teardown to perform, you can assign a method destroy() to your middleware function(s),
and calling JsonRpcEngine.destroy() will call this method on each middleware that has it.
A destroyed engine can no longer be used.
constmiddleware=(req,res,next,end)=>{/* do something */};middleware.destroy=()=>{/* perform teardown */};constengine=newJsonRpcEngine();engine.push(middleware);/* perform work */// This will call middleware.destroy() and destroy the engine itself.engine.destroy();// Calling any public method on the middleware other than `destroy()` itself// will throw an error.engine.handle(req);
请发表评论