You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

55 lines
1.2 KiB

  1. /*!
  2. * Connect - timeout
  3. * Ported from https://github.com/LearnBoost/connect-timeout
  4. * MIT Licensed
  5. */
  6. /**
  7. * Module dependencies.
  8. */
  9. var debug = require('debug')('connect:timeout');
  10. /**
  11. * Timeout:
  12. *
  13. * Times out the request in `ms`, defaulting to `5000`. The
  14. * method `req.clearTimeout()` is added to revert this behaviour
  15. * programmatically within your application's middleware, routes, etc.
  16. *
  17. * The timeout error is passed to `next()` so that you may customize
  18. * the response behaviour. This error has the `.timeout` property as
  19. * well as `.status == 408`.
  20. *
  21. * @param {Number} ms
  22. * @return {Function}
  23. * @api public
  24. */
  25. module.exports = function timeout(ms) {
  26. ms = ms || 5000;
  27. return function(req, res, next) {
  28. var id = setTimeout(function(){
  29. req.emit('timeout', ms);
  30. }, ms);
  31. req.on('timeout', function(){
  32. if (res.headerSent) return debug('response started, cannot timeout');
  33. var err = new Error('Response timeout');
  34. err.timeout = ms;
  35. err.status = 503;
  36. next(err);
  37. });
  38. req.clearTimeout = function(){
  39. clearTimeout(id);
  40. };
  41. res.on('header', function(){
  42. clearTimeout(id);
  43. });
  44. next();
  45. };
  46. };