forked from swimlane/trafficlight
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbindings.ts
More file actions
81 lines (74 loc) · 1.9 KB
/
bindings.ts
File metadata and controls
81 lines (74 loc) · 1.9 KB
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
78
79
80
81
import 'reflect-metadata';
import { ROUTE_PREFIX } from './constants';
/**
* Given a list of params, execute each with the context.
*
* @param params
* @param ctx
* @param next
*/
export function getArguments(params, ctx, next): any[] {
let args = [ctx, next];
if (params) {
args = [];
// sort by index
params.sort((a, b) => {
return a.index - b.index;
});
for (const param of params) {
let result;
if (param !== undefined) result = param.fn(ctx);
args.push(result);
}
}
return args;
}
/**
* Binds the routes to the router
*
* Example:
*
* const router = new Router();
* bindRoutes(router, [ProfileController]);
*
* @export
* @param {*} routerRoutes
* @param {any[]} controllers
* @param {(ctrl) => any} [getter]
* @returns {*}
*/
export function bindRoutes(routerRoutes: any, controllers: any[], getter?: (ctrl) => any): any {
var reactRouters = [];
for (const ctrl of controllers) {
var routes = Reflect.getMetadata(ROUTE_PREFIX, ctrl);
if (routes) {
ctrl[ROUTE_PREFIX] = routes;
} else {
routes = ctrl[ROUTE_PREFIX];
}
for (const { method, url, middleware, name, params, view, response } of routes) {
const inst = getter === undefined ?
new ctrl() : getter(ctrl);
if (view) {
reactRouters.push({
component: view, path: url, func : inst[name], args : (ctx, next) => getArguments(params, ctx, next)
});
} else {
middleware.push(async function (ctx, next) {
const args = getArguments(params, ctx, next);
const result = inst[name](...args);
if (response) {
response(ctx, await result)
} else {
if (result) {
ctx.body = await result;
}
}
return result;
});
}
routerRoutes[method](url, ...middleware);
}
}
return reactRouters;
}