-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.js
73 lines (58 loc) · 1.52 KB
/
server.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
const express = require("express");
const bodyParser = require("body-parser");
const R = require("ramda");
// put path in the URL? 🤔
// handle OPTIONS request at the root? 🤔
// handle only POST requests? 🤔
function rpcService(exposedMethods) {
const service = express();
service.use(bodyParser.json());
service.use(async function rpcHandler(req, res, next) {
const { path, args } = req.body;
if (!ArrayOfStringsSchema.test(path)) {
console.log("failed ArrayOfStringsSchema");
next(new TypeError("path parameter must be an array of strings"));
return;
}
if (!Array.isArray(args)) {
console.log("failed Array.isArray");
next(new TypeError("args parameter must be an array"));
return;
}
const thisArg = R.path(path.slice(0, -1), exposedMethods);
const method = R.path(path, exposedMethods);
if (typeof method !== "function") {
next();
return;
}
try {
res.json(await method.apply(thisArg, args));
} catch (error) {
next(error);
}
});
service.use(function errorHandler(err, req, res, next) {
console.log(err);
res.status(400).json({
error: err,
});
});
return service;
}
module.exports = {
rpcService,
};
const ArrayOfStringsSchema = {
test(value) {
if (!Array.isArray(value)) {
return false;
}
if (!value.every(isString)) {
return false;
}
return true;
},
};
function isString(value) {
return typeof value === "string";
}