Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- # 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()
- callback = wrap(callback) if callback.apply
- args.push 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
Add Comment
Please, Sign In to add comment