layer.js 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. /**
  2. * Module dependencies.
  3. */
  4. var pathRegexp = require('path-to-regexp');
  5. var debug = require('debug')('express:router:layer');
  6. /**
  7. * Expose `Layer`.
  8. */
  9. module.exports = Layer;
  10. function Layer(path, options, fn) {
  11. if (!(this instanceof Layer)) {
  12. return new Layer(path, options, fn);
  13. }
  14. debug('new %s', path);
  15. options = options || {};
  16. this.regexp = pathRegexp(path, this.keys = [], options);
  17. this.handle = fn;
  18. }
  19. /**
  20. * Check if this route matches `path`, if so
  21. * populate `.params`.
  22. *
  23. * @param {String} path
  24. * @return {Boolean}
  25. * @api private
  26. */
  27. Layer.prototype.match = function(path){
  28. var keys = this.keys;
  29. var params = this.params = {};
  30. var m = this.regexp.exec(path);
  31. var n = 0;
  32. var key;
  33. var val;
  34. if (!m) return false;
  35. this.path = m[0];
  36. for (var i = 1, len = m.length; i < len; ++i) {
  37. key = keys[i - 1];
  38. try {
  39. val = 'string' == typeof m[i]
  40. ? decodeURIComponent(m[i])
  41. : m[i];
  42. } catch(e) {
  43. var err = new Error("Failed to decode param '" + m[i] + "'");
  44. err.status = 400;
  45. throw err;
  46. }
  47. if (key) {
  48. params[key.name] = val;
  49. } else {
  50. params[n++] = val;
  51. }
  52. }
  53. return true;
  54. };