-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapplication.js
77 lines (60 loc) · 2.06 KB
/
application.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
74
75
76
77
const assert = require('assert');
const createRpcServer = require('./server');
const runMiddleware = require('./middleware');
const { pick, defaultTo } = require('lodash');
const debug = require('debug')('jars:application');
async function createApplication(conn, identifier, options = {}) {
assert(conn, 'conn is required');
assert.equal(typeof identifier, 'string', 'identifier must be a string');
const revealErrorMessages = defaultTo(options.revealErrorMessages, process.env.NODE_ENV !== 'production') === true;
const app = {};
const middleware = [];
const errorHandlers = [];
const use = method => {
// const isErrorHandler = !!method.toString().match(/\(err/);
const isErrorHandler = method.length === 4; // err, req, res, next
if (isErrorHandler) {
errorHandlers.push(method);
} else {
middleware.push(method);
}
};
const handler = ({ method, params, reply, meta, replyWithResult, replyWithError }) => {
const req = {
app,
method,
params,
stop: false,
meta,
};
const res = {
send: result => {
res.stop = true;
return replyWithResult(result);
},
error: (...args) => {
res.stop = true;
return replyWithError(...args);
},
};
const unhandled = (req, res) => {
debug(`Unhandled: ${req.method}`);
res.error('Unhandled request');
};
const unhandledError = (err, req, res) => {
const errorData = pick(err, 'message', 'stack', 'code', 'name');
if (revealErrorMessages) {
res.error(err.message, 'InternalServerError', errorData);
} else {
debug('Will not reveal error message:\n%O', errorData);
res.error('Internal server error', 'InternalServerError');
}
};
return runMiddleware([...middleware, unhandled], [...errorHandlers, unhandledError], req, res);
};
const server = await createRpcServer(conn, identifier, handler);
const close = server.close;
Object.assign(app, { server, middleware, use, close });
return app;
}
module.exports = createApplication;