1 | 'use strict';
|
2 |
|
3 | module.exports = ($, util) => {
|
4 | function _drawRoutes(ctx, routes) {
|
5 | routes.forEach(route => {
|
6 |
|
7 | if (!route.pipeline) {
|
8 | const _handler = route.handler.slice();
|
9 |
|
10 | const action = _handler.length > 1 ? _handler.pop() : 'index';
|
11 | const controller = _handler.join('.');
|
12 |
|
13 |
|
14 | if (route.use && !Array.isArray(route.use)) {
|
15 | route.use = [route.use];
|
16 | }
|
17 |
|
18 |
|
19 | route.controller = controller;
|
20 | route.action = action;
|
21 |
|
22 | if (!this._controllers[controller]) {
|
23 | try {
|
24 | const _controller = this.controller_lookup
|
25 | ? this.controller_lookup.replace('%s', controller)
|
26 | : `${controller}Controller`;
|
27 |
|
28 | const Ctrl = util.getProp($, _controller,
|
29 | new Error(`${_controller} is not defined`));
|
30 |
|
31 | this._controllers[controller] = {
|
32 | instance: new Ctrl(),
|
33 | definition: Ctrl,
|
34 | };
|
35 |
|
36 |
|
37 | if (!(this._controllers[controller].instance[action])) {
|
38 | throw new Error(`No callback found for ${route.verb} ${route.path}`);
|
39 | }
|
40 |
|
41 | route.pipeline = route.pipeline || [];
|
42 |
|
43 |
|
44 | if (typeof this._controllers[controller].definition.pipe === 'function') {
|
45 | route.pipeline.unshift({
|
46 | call: [this._controllers[controller].definition, 'pipe'],
|
47 | name: `${controller}#pipe`,
|
48 | type: 'method',
|
49 | });
|
50 | }
|
51 |
|
52 | route.pipeline.push({
|
53 | call: [this._controllers[controller].instance, action],
|
54 | name: `${controller}#${action}`,
|
55 | type: 'method',
|
56 | });
|
57 | } catch (e) {
|
58 | throw new Error(`${controller} controller failed\n${e.stack}`);
|
59 | }
|
60 | }
|
61 |
|
62 | delete route.handler;
|
63 | }
|
64 | })
|
65 | }
|
66 |
|
67 | return $.module('Router.Controllers', {
|
68 | _drawRoutes,
|
69 | _controllers: {},
|
70 |
|
71 | before_routes: _drawRoutes,
|
72 | });
|
73 | };
|