forked from lsongdev/koa-routeify
-
Notifications
You must be signed in to change notification settings - Fork 0
/
router.js
46 lines (40 loc) · 1.33 KB
/
router.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
var debug = require('debug');
function matches(ctx, method) {
if (!method)
return true;
if (ctx.method === method)
return true;
if (method === 'GET' && ctx.method === 'HEAD')
return true;
return false;
};
exports.matches = matches;
module.exports = function router(app){
return function*(next){
var ctx = this;
var params = {};
var routes = app.routes.filter(function(route){
if(!matches(ctx, route.method)) return false;
if(route.regexp.test(ctx.path)) return true;
});
debug('koa-routeify')(routes);
if(!routes.length) return yield* next;// not found.
var route = routes[ 0 ];
var args = route.regexp.exec(this.path).slice(1).map(decodeURIComponent);
route.regexp.keys.forEach(function(key, i){
params[ key.name ] = args[ i ];
});
var Controller = app.controllers[ route.controller ];
if(!Controller) throw new Error(`[Router] missing controller "${route.controller}"`);
var controller = new Controller(app);
var action = controller[ route.action ];
if(!action){
throw new Error(`[Router] can not found action "${route.action}" in "${Controller.name}"`);
}
controller.params = params;
controller.ctx = this;
controller.query = this.query;
controller.body = this.request.body;
yield action.apply(controller, args);
};
}