UNPKG

1.04 kBJavaScriptView Raw
1/*!
2 * jsonrpc.js - json-rpc middleware for bweb
3 * Copyright (c) 2017, Christopher Jeffrey (MIT License).
4 * https://github.com/bcoin-org/bweb
5 */
6
7'use strict';
8
9const assert = require('bsert');
10
11/**
12 * JSON rpc middleware.
13 * @param {Object} rpc
14 * @returns {Function}
15 */
16
17function 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 * Expose
54 */
55
56module.exports = jsonRPC;