Inital Commit
[oweals/finalsclub.git] / node_modules / express / lib / router / route.js
1
2 /*!
3  * Express - router - Route
4  * Copyright(c) 2010 TJ Holowaychuk <tj@vision-media.ca>
5  * MIT Licensed
6  */
7
8 /**
9  * Expose `Route`.
10  */
11
12 module.exports = Route;
13
14 /**
15  * Initialize `Route` with the given HTTP `method`, `path`,
16  * and callback `fn` and `options`.
17  *
18  * Options:
19  *
20  *   - `sensitive`    enable case-sensitive routes
21  *   - `strict`       enable strict matching for trailing slashes
22  *   - `middleware`   array of middleware
23  *
24  * @param {String} method
25  * @param {String} path
26  * @param {Function} fn
27  * @param {Object} options.
28  * @api private
29  */
30
31 function Route(method, path, fn, options) {
32   options = options || {};
33   this.callback = fn;
34   this.path = path;
35   this.method = method;
36   this.middleware = options.middleware;
37   this.regexp = normalize(path
38     , this.keys = []
39     , options.sensitive
40     , options.strict);
41 }
42
43 /**
44  * Check if this route matches `path` and return captures made.
45  *
46  * @param {String} path
47  * @return {Array}
48  * @api private
49  */
50
51 Route.prototype.match = function(path){
52   return this.regexp.exec(path);
53 };
54
55 /**
56  * Normalize the given path string,
57  * returning a regular expression.
58  *
59  * An empty array should be passed,
60  * which will contain the placeholder
61  * key names. For example "/user/:id" will
62  * then contain ["id"].
63  *
64  * @param  {String|RegExp} path
65  * @param  {Array} keys
66  * @param  {Boolean} sensitive
67  * @param  {Boolean} strict
68  * @return {RegExp}
69  * @api private
70  */
71
72 function normalize(path, keys, sensitive, strict) {
73   if (path instanceof RegExp) return path;
74   path = path
75     .concat(strict ? '' : '/?')
76     .replace(/\/\(/g, '(?:/')
77     .replace(/(\/)?(\.)?:(\w+)(?:(\(.*?\)))?(\?)?/g, function(_, slash, format, key, capture, optional){
78       keys.push({ name: key, optional: !! optional });
79       slash = slash || '';
80       return ''
81         + (optional ? '' : slash)
82         + '(?:'
83         + (optional ? slash : '')
84         + (format || '') + (capture || '([^/]+?)') + ')'
85         + (optional || '');
86     })
87     .replace(/([\/.])/g, '\\$1')
88     .replace(/\*/g, '(.+)');
89   return new RegExp('^' + path + '$', sensitive ? '' : 'i');
90 }