1 |
|
2 |
|
3 |
|
4 |
|
5 |
|
6 |
|
7 | 'use strict';
|
8 |
|
9 | const assert = require('bsert');
|
10 |
|
11 |
|
12 |
|
13 |
|
14 |
|
15 |
|
16 |
|
17 | function jsonRPC(rpc) {
|
18 | assert(rpc && typeof rpc === 'object');
|
19 | assert(typeof rpc.call === 'function');
|
20 |
|
21 | return async (req, res) => {
|
22 | if (req.method !== 'POST')
|
23 | return;
|
24 |
|
25 | if (req.pathname !== '/')
|
26 | return;
|
27 |
|
28 | if (req.body instanceof Array) {
|
29 | for (const request of req.body) {
|
30 | if (typeof request.method !== 'string')
|
31 | return;
|
32 | }
|
33 | } else {
|
34 | if (typeof req.body.method !== 'string')
|
35 | return;
|
36 | }
|
37 |
|
38 | let json = await rpc.call(req.body, req.query);
|
39 |
|
40 | if (json == null)
|
41 | json = null;
|
42 |
|
43 | json = JSON.stringify(json);
|
44 | json += '\n';
|
45 |
|
46 | res.setHeader('X-Long-Polling', '/?longpoll=1');
|
47 |
|
48 | res.send(200, json, 'application/json');
|
49 | };
|
50 | }
|
51 |
|
52 |
|
53 |
|
54 |
|
55 |
|
56 | module.exports = jsonRPC;
|