-
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathindex.js
64 lines (61 loc) · 1.64 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
58
59
60
61
62
63
64
const http = require('http');
const kelp = require('kelp');
const body = require('kelp-body');
const send = require('kelp-send');
const error = require('kelp-error');
const logger = require('kelp-logger');
const Router = require('kelp-router');
const routing = require('routing2');
const { debuglog } = require('util');
const debug = debuglog('kelp-server');
const createServer = ({
app = kelp(),
port = 3000,
routes = [],
plugins = [],
middlewares = [],
controllers = [],
defaultHandler = true,
defaultErrorHandler = true,
}) => {
// router
const router = new Router();
const rules = routes.map(routing.create);
const ctrls = controllers.reduce((obj, Ctrl) => {
obj[Ctrl.name] = new Ctrl(app);
debug('initialized controller:', Ctrl.name);
return obj;
}, {});
for (const rule of rules) {
const { method, path, controller: c, action: a } = rule;
const ctrl = ctrls[c];
if (!ctrl) throw new Error(`[kelp-server] Can not find controller: "${c}"`);
const action = ctrl[a];
if (!action) throw new Error(`[kelp-server] Can not find action: "${a}"`);
debug('mapping controller to rule:', c, a);
router.route(method, path, action);
}
// middleware
app.use(send);
app.use(body);
app.use(logger);
app.use(
middlewares,
plugins
.map(plugin => plugin(app))
.filter(p => typeof p === 'function')
);
if (defaultErrorHandler) {
app.use(error);
}
app.use(router);
if (defaultHandler) {
app.use((_, res) => res.send(404));
}
const server = http.createServer(app);
server.start = (p = port) => server.listen(p);
return server;
};
module.exports = {
createServer,
};