forked from lsongdev/kelp-server
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
59 lines (56 loc) · 1.57 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
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 controller = require('kelp-controller');
const routing = require('routing2');
const { debuglog } = require('util');
const debug = debuglog('kelp-server');
const { Response, Controller } = controller;
const createServer = ({
app = kelp(),
routes = [],
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, controller(action));
}
// middleware
app.use(send);
app.use(body);
app.use(logger);
app.use(middlewares);
if (defaultErrorHandler) {
app.use(error);
}
app.use(router);
if (defaultHandler) {
app.use((_, res) => res.send(404));
}
return http.createServer(app);
};
module.exports = {
Response,
Controller,
createServer,
};