On Github Raynos / jsfest2014-talk
Because of `npm`, we no longer need off the shelf web frameworks
Fed up with `express`. It's bad, but that's for another talk
Wanting a better approach, finding inspiration in `isaacs/npm-www` and `mikeal/tako`.
Lessons from `isaac/npm-www`
Lessons from `mikeal/tako`
`Raynos/routil`, the underscore of `http`
Lessons learned
publishing to `npm` is easy. Thus modules are born
var sendJson = require('send-data/json') var db = require('./db.js') // GET /users/:id module.exports = function* getUser(req, res, opts) { var user = yield db.users.get.bind(db.users, opts.id) sendJson(req, res, user) }
var jsonBody = require('body/json') var db = require('./db.js') // PUT /users/:id module.exports = function* saveUser(req, res, opts) { var body = yield jsonBody.bind(null, req, res) yield db.users.put.bind(db.users, opts.id, body) res.end('OK') }
var Router = require('routes-router') var http = require('http') var router = Router({ errorHandler: function (req, res, err) { res.statusCode = 500 res.end("500: Unknown error " + err.message) } }) router.addRoute("/oops", function (req, res, opts, cb) { cb(new Error("oops!")) }) http.createServer(router).listen(3000)
// require statements somewhere var renderUserPage = require('./views/user-page.js'); var validateUser = require('./validations/user.js'); var router = Router(); router.addRoute('/user/:id', { GET: function* renderPage(req, res, opts) { var user = yield db.users.get.bind(db.users, opts.id); sendHtml(req, res, renderUserPage({ title: 'Editing user ' + user.name, name: user.name, email: user.email })); }, POST: function* updateUser() { var body = yield formBody.bind(null, req, res); var error = validateUser(body); if (error) yield error; yield db.users.put.bind(db.users, opts.id, body); redirecter(req, res, '/users/' + opts.id + '/edit'); } }); http.createServer(router).listen(3000);
Which is right for you
The pros
The cons
A collection of examples and documentation for this approach
Contributions welcome