Created
October 28, 2012 10:33
-
-
Save sofish/3968274 to your computer and use it in GitHub Desktop.
auto route
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var router, middlewares, before, after, app | |
app = express() | |
router = require('./router') | |
app.configure(function(){ | |
app.set('controllers', require('YOUR_CONTROLLERS')) | |
}) | |
middlewares = { | |
users: { | |
get: [], post: [], update: [], delete: [] | |
}, | |
projects: { | |
get: [], post: [], update: [], delete: [] | |
}, | |
tasks: { | |
get: [], post: [], update: [], delete: [] | |
} | |
} | |
// return features, 因为 arguments 是不可以更改的,所以在函数中改也没办法给后面的用 | |
before = function (app, middlewares) { | |
// customize routes | |
return features; | |
} | |
// 不需要 return | |
after = function (app, middlewares, features) {} | |
router.call(this, app, middlewares, before, after); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var map = function(app, controllers, name, method, middlewares) { | |
var list = '/' + name | |
, path = list + '/:id' | |
, short_id = name + '_id' | |
, middleware = middlewares[name][method] | |
// we can get/put/delete a list | |
method !== 'post' && app[method](list, middleware, controllers[name]) | |
// post to an url means CREATE | |
if(method === 'post'){ | |
path = list, short_id = name; | |
} | |
app[method](path, middleware, controllers[short_id]); | |
} | |
/* the module produces routes like blew: | |
* app.get('/users', [...], controller.users) | |
* app.get('/users/:id', [...], controller.user_id) | |
* app.post('/users', [...], controller.users) | |
* app.put('/users/:id', [...], controller.users) | |
* app.put('/users/:id', [...], controller.user_id) | |
* app.delete('/users/:id', [...], controller.users) | |
* app.delete('/users/:id', [...], controller.user_id) | |
*/ | |
module.exports = exports = function(app, middlewares, before, after){ | |
var controllers = app.get('controllers') | |
, methods = ['get', 'post', 'put', 'delete'] | |
features = before(app, middlewares); | |
// remeber to remove controllers with '_id' subbfix | |
// they should renderred by the ExpressJS `next` router | |
features = features.filter(function(item){ | |
return item.slice(-3) !== '_id' | |
}) | |
features.forEach(function(name) { | |
methods.forEach(function(method) { | |
map(app, controllers, name, method, middlewares); | |
}) | |
}) | |
after(app, middlewares, features); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment