Guest User

Untitled

a guest
Oct 19th, 2018
90
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.25 KB | None | 0 0
  1. # Adding context for req/res cycle for Express.js.
  2. # With context it would be possible to write more terse code:
  3. #
  4. # app.use ->
  5. # @user = {name: 'Anonymous'}
  6. # @next()
  7. #
  8. # app.get '/', ->
  9. # @res.end "Hello, #{@user.name}"
  10. #
  11. # Instead of:
  12. #
  13. # app.use (req, res, next) ->
  14. # req.user = {name: 'Anonymous'}
  15. # next()
  16. #
  17. # app.get '/', (req, res) ->
  18. # res.end "Hello, #{req.user.name}"
  19. #
  20. # It's also backward compatible, You still can use original API if You wish.
  21. express = require 'express'
  22. Router = require 'express/lib/router'
  23.  
  24. # Context for req/res cycle.
  25. express.Context = (@req, @res) ->
  26.  
  27. # Wrapping every callback to be executed within context.
  28. wrap = (callback) ->
  29. (req, res, next) ->
  30. context = (req.context ?= new express.Context(req, res))
  31. context.next = next
  32. callback.apply context, [req, res, next]
  33.  
  34. oldUse = express.HTTPServer.prototype.use
  35. express.HTTPServer.prototype.use = (args...) ->
  36. callback = args.pop()
  37. callback = wrap(callback) if callback.apply
  38. args.push callback
  39. oldUse.apply @, args
  40.  
  41. oldRoute = Router.prototype._route
  42. Router.prototype._route = (method, path, callbacks...) ->
  43. args = [method, path]
  44. args.push wrap(callback) for callback in callbacks
  45. oldRoute.apply @, args
Add Comment
Please, Sign In to add comment