-
Notifications
You must be signed in to change notification settings - Fork 4
/
index.js
57 lines (56 loc) · 1.44 KB
/
index.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
const {
send,
json,
createError,
} = require('micro');
module.exports = {
rpc: (...methods) => async (req, res) => {
const data = await json(req);
req.body = data;
const { name, args } = data;
const matchingMethod = methods.find((method) => method.name === name);
if (matchingMethod) {
const parsedArgs = args ? JSON.parse(args) : [];
try {
const result = Array.isArray(parsedArgs) ?
await matchingMethod.fn(...parsedArgs, req, res) :
await matchingMethod.fn(parsedArgs, req, res);
send(res, 200, { result });
} catch (err) {
// error was handled
if (err.handled) {
send(res, err.statusCode, {
error: err.message
});
} else {
// unhandled exception
throw err;
}
}
} else if (name === 'methods') {
send(res, 200, {
result: methods.map((method) => ({
name: method.name,
docs: method.docs,
})).concat({
name: 'methods',
docs: 'list all available methods',
}),
});
} else {
send(res, 404, {
error: 'unknown method'
});
}
},
method: (name, ...args) => ({
name,
fn: args[1] ? args[1] : args[0],
docs: args[1] ? args[0] : undefined,
}),
createError: ({ message, statusCode = 400 }) => {
const err = createError(statusCode, message);
err.handled = true;
return err;
},
};