Skip to content

Instantly share code, notes, and snippets.

@al6x
Created March 28, 2012 20:36
Show Gist options
  • Save al6x/2230304 to your computer and use it in GitHub Desktop.
Save al6x/2230304 to your computer and use it in GitHub Desktop.
Adding context for Express.js req/res cycle
# 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