Middleware support
norman784 opened this issue · comments
Norman Paniagua commented
I just found an issue with the way that always worked with express, and its to add a middleware (for authentication) that verify is there is an active session, the issue its that only certain routes need to be verified. i.e.
app.use(route.get('/dashboard', 'backend/user#authenticated', 'backend/dashboard#index'));
Or there is a koa way to do this?
Edited: I just made a hack to routes, and seems like:
var route = require('koa-route')
self = function() {
var method = arguments[2] || 'GET'
, url = arguments[0]
, controller = require('./controllers/' + arguments[1].split('#')[0])
, action = arguments[1].split('#')[1];
action = !action ? 'index' : (action.length == 0 ? 'index' : action)
console.log('\t[' + method + ']', url, ' => ', arguments[1]);
switch(method.toUpperCase()) {
case 'POST': return route.post(url, controller[action]);
case 'PUT': return route.put(url, controller[action]);
case 'DELETE': return route.delete(url, controller[action]);
case 'all': return route.all(url, controller[action]);
default: return route.get(url, controller[action]);
}
};
module.exports = {
get: function(url, controller) {
return self(url, controller, 'GET');
},
post: function(url, controller) {
return self(url, controller, 'POST');
},
put: function(url, controller) {
return self(url, controller, 'PUT');
},
delete: function(url, controller) {
return self(url, controller, 'DELETE');
},
del: function(url, controller) {
return self(url, controller, 'DELETE');
},
all : function(url, controller) {
return self(url, controller, 'ALL');
}
};
Thats because I'm lazy to load all my controllers manually, but also looking at the source code of route it only accepts two params, route and method.
TJ Holowaychuk commented
if you want something resource-oriented check out koa-router, it's a port of express-resource
Norman Paniagua commented
thanks, ill check that