Created
March 28, 2012 20:36
-
-
Save al6x/2230304 to your computer and use it in GitHub Desktop.
Adding context for Express.js req/res cycle
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
# Adding context for req/res cycle for Express.js. | |
# With context it would be possible to write more terse code: | |
# | |
# app.use -> | |
# @user = {name: 'Anonymous'} | |
# @next() | |
# | |
# app.get '/', -> | |
# @res.end "Hello, #{@user.name}" | |
# | |
# Instead of: | |
# | |
# app.use (req, res, next) -> | |
# req.user = {name: 'Anonymous'} | |
# next() | |
# | |
# app.get '/', (req, res) -> | |
# res.end "Hello, #{req.user.name}" | |
# | |
# It's also backward compatible, You still can use original API if You wish. | |
express = require 'express' | |
Router = require 'express/lib/router' | |
# Context for req/res cycle. | |
express.Context = (@req, @res) -> | |
# Wrapping every callback to be executed within context. | |
wrap = (callback) -> | |
(req, res, next) -> | |
context = (req.context ?= new express.Context(req, res)) | |
context.next = next | |
callback.apply context, [req, res, next] | |
oldUse = express.HTTPServer.prototype.use | |
express.HTTPServer.prototype.use = (args...) -> | |
callback = args.pop() | |
args.push wrap(callback) | |
oldUse.apply @, args | |
oldRoute = Router.prototype._route | |
Router.prototype._route = (method, path, callbacks...) -> | |
args = [method, path] | |
args.push wrap(callback) for callback in callbacks | |
oldRoute.apply @, args |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment