Skip to content
This repository was archived by the owner on Nov 9, 2023. It is now read-only.

Commit 9ffe19e

Browse files
authored
Add async handle signature (#55)
* add async handle signature * add await example to readme * encapsulate callback vs promise logic in handle
1 parent b4b2b06 commit 9ffe19e

2 files changed

Lines changed: 26 additions & 19 deletions

File tree

README.md

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -24,9 +24,12 @@ Requests are handled asynchronously, stepping down the stack until complete.
2424
```js
2525
let request = { id: 1, jsonrpc: '2.0', method: 'hello' }
2626

27-
engine.handle(request, function(err, res){
28-
// do something with res.result
27+
engine.handle(request, function(err, response){
28+
// do something with response.result
2929
})
30+
31+
// there is also a Promise signature
32+
const response = await engine.handle(request)
3033
```
3134

3235
Middleware have direct access to the request and response objects.

src/index.js

Lines changed: 21 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -22,30 +22,34 @@ module.exports = class RpcEngine extends SafeEventEmitter {
2222
}
2323

2424
handle (req, cb) {
25-
// batch request support
25+
2626
if (Array.isArray(req)) {
27-
this._handleBatch(req, cb)
28-
} else {
29-
this._handle(req, cb)
27+
if (cb) {
28+
this._handleBatch(req)
29+
.catch((err) => cb(err)) // fatal error
30+
.then((res) => cb(null, res))
31+
return undefined
32+
}
33+
return this._handleBatch(req)
34+
}
35+
36+
if (!cb) {
37+
return this._promiseHandle(req)
3038
}
39+
return this._handle(req, cb)
3140
}
3241

3342
//
3443
// Private
3544
//
3645

37-
async _handleBatch (reqs, cb) {
38-
46+
async _handleBatch (reqs) {
3947
// The order here is important
40-
try {
41-
const batchRes = await Promise.all( // 2. Wait for all requests to finish
42-
// 1. Begin executing each request in the order received
43-
reqs.map(this._promiseHandle.bind(this)),
44-
)
45-
return cb(null, batchRes) // 3a. Return batch response
46-
} catch (err) {
47-
return cb(err) // 3b. Some kind of fatal error; all requests are lost
48-
}
48+
// 3a. Return batch response, or reject on some kind of fatal error
49+
return await Promise.all( // 2. Wait for all requests to finish
50+
// 1. Begin executing each request in the order received
51+
reqs.map(this._promiseHandle.bind(this)),
52+
)
4953
}
5054

5155
_promiseHandle (req) {
@@ -58,9 +62,9 @@ module.exports = class RpcEngine extends SafeEventEmitter {
5862
})
5963
}
6064

61-
_handle (_req, cb) {
65+
_handle (callerReq, cb) {
6266

63-
const req = Object.assign({}, _req)
67+
const req = Object.assign({}, callerReq)
6468
const res = {
6569
id: req.id,
6670
jsonrpc: req.jsonrpc,

0 commit comments

Comments
 (0)