-
Notifications
You must be signed in to change notification settings - Fork 2
Routing
camposer edited this page Jul 26, 2012
·
4 revisions
When you install express it adds routes inside app.js, I'm not really comfortable with that because this file for me must be only for app configuration, and things like routes, which changes a lot, should be configured in other place. My changes were:
- Remove all routes mappings from app.js and add one call for global routes:
routes.route(app); - Leave calls for mappings inside routes/index.js separated in files. For example:
var views = require('./views');
var rest = require('./rest');
exports.route = function(app) {
views.route(app);
rest.route(app);
};
- Add route method for each group of routes (this can be splitted in more files for larger apps). For example (routes/rest.js):
var userRest = require('../lib/rest/user');
var BASE_URL = '/rest';
this.route = function(app) {
this.users(app);
};
this.users = function(app) {
app.get(BASE_URL + '/users', userRest.getUsers);
app.get(BASE_URL + '/users/:id', userRest.getUserById);
app.put(BASE_URL + '/users', userRest.addUser);
app.delete(BASE_URL + '/users', userRest.removeUser);
app.post(BASE_URL + '/users', userRest.updateUser);
};
Note: I propose this files remain without any "business" logic, just used for routing purposes.
In this case I didn't use MVC, because my approach is for heavier clients, doing Ajax requests to RESTful applications. Something code-behind oriented. But... What if you don't want that? Well, here is a proposal (based on my actual code) for MVC:
- Change routes/views.js like this:
var userController = require('../lib/controller/user');
this.route = function(app) {
app.get('/', userController.index);
};
Note: You can divide route function like in routes/rest.js
- Add /lib/controller/user.js like this:
var userService = require('../service/user');
this.index = function(req, res){
var users = userService.getUsers();
res.render('index', { title: 'List of users', session: req.session, users: users });
}
- Inside index.ejs render users:
...
<% for (var i=0; users.length; i++) { %>
<tr>
<td><%= users[i].id %></td>
<td><%= users[i].name %></td>
</tr>
<% } %>
...
Personal note: for escaping HTML I used: http://www.htmlescape.net/htmlescape_tool.html