Started mvc example
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by Tj Holowaychuk · committed by Tj Holowaychuk · parent cbfed20 · Browse files · 4 files·+106 added−0 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
4 files+106 added−0 removed
- other:+106 added−0 removed
Provenance
- Commit
9231245- Tree
02a9b54- Author
Tj Holowaychuk <tj@vision-media.ca>- Committer
Tj Holowaychuk <tj@vision-media.ca>- Parent
cbfed20
4 files changed+106 added−0 removed
added:examples/mvc/controllers/app.js+9 added
123456789
module.exports = { // /users index: function(req, res){ res.render('index'); }};No newline at end of fileadded:examples/mvc/controllers/user.js+28 added
12345678910111213141516171819202122232425262728
// Fake user database for example
var users = [ { name: 'TJ', email: 'tj@vision-media.ca' }, { name: 'Simon', email: 'simon@vision-media.ca' }];
module.exports = { // /users index: function(req, res){ res.send('users: ' + JSON.stringify(users)); },
// /users/:id
show: function(req, res, next){ var id = req.params.id, user = users[id]; if (user) { res.send('user: ' + JSON.stringify(user)); } else { next(new Error('User ' + id + ' does not exist')); } }};No newline at end of fileadded:examples/mvc/app.js+13 added
12345678910111213
/** * Module dependencies. */
var express = require('../../lib/express');
var app = express.createServer();
require('./mvc').boot(app);
app.listen();console.log('Application server started on port 3000');No newline at end of fileadded:examples/mvc/mvc.js+56 added
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
/** * Module dependencies. */
var fs = require('fs');
exports.boot = function(app){ bootControllers(app);};
// Bootstrap controllers
function bootControllers(app) { fs.readdir(__dirname + '/controllers', function(err, files){ if (err) throw err; files.forEach(function(file){ bootController(app, file); }); });}
// Example (simplistic) controller support
function bootController(app, file) { var name = file.replace('.js', ''), actions = require('./controllers/' + name), plural = name + 's', // realistically we would use an inflection lib prefix = '/' + plural; Object.keys(actions).map(function(action){ var fn = actions[action]; switch(action) { case 'index': app.get(prefix, fn); break; case 'show': app.get(prefix + '/:id', fn); break; case 'add': app.get(prefix + '/:id/add', fn); break; case 'create': app.post(prefix + '/:id', fn); break; case 'edit': app.get(prefix + '/:id/edit', fn); break; case 'update': app.put(prefix + '/:id', fn); break; case 'destroy': app.del(prefix + '/:id', fn); break; } });}No newline at end of file