-
Notifications
You must be signed in to change notification settings - Fork 8
/
routing.js
167 lines (139 loc) · 4.26 KB
/
routing.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
// Route object taken from page.js, slightly stripped down
//
// Copyright (c) 2012 TJ Holowaychuk <tj@vision-media.ca>
//
/**
* Initialize `Route` with the given HTTP `path`, and an array of `options`.
*
* Options:
*
* - `methods` the allowed methods. string ("POST") or array (["POST", "GET"]).
* - `sensitive` enable case-sensitive routes
* - `strict` enable strict matching for trailing slashes
*
* @param {String} path
* @param {Object} options.
* @api private
*/
RESTstop.Route = function(realPath, original, options) {
this.options = options || {};
this.originalPath = original;
this.path = realPath + original;
this.method = this.options.method;
if(this.method && !_.isArray(this.method)) {
this.method = [this.method];
}
if(this.method) {
this.method = _.map(this.method, function(s){ return s.toUpperCase(); });
}
this.regexp = pathtoRegexp(this.path
, this.keys = []
, this.options.sensitive
, this.options.strict);
}
/**
* Check if this route matches `path` and optional `method`, if so
* populate `params`.
*
* @param {String} path
* @param {String} method
* @param {Array} params
* @return {Boolean}
* @api private
*/
RESTstop.Route.prototype.match = function(path, method, params){
var keys, qsIndex, pathname, m;
if(this.method && !_.contains(this.method, method)) return false;
keys = this.keys;
qsIndex = path.indexOf('?');
pathname = ~qsIndex ? path.slice(0, qsIndex) : path;
m = this.regexp.exec(pathname);
if (!m) return false;
for (var i = 1, len = m.length; i < len; ++i) {
var key = keys[i - 1];
var val = 'string' == typeof m[i]
? decodeURIComponent(m[i])
: m[i];
if (key) {
params[key.name] = undefined !== params[key.name]
? params[key.name]
: val;
}
}
return true;
};
/**
* Normalize the given path string,
* returning a regular expression.
*
* An empty array should be passed,
* which will contain the placeholder
* key names. For example "/user/:id" will
* then contain ["id"].
*
* @param {String|RegExp|Array} path
* @param {Array} keys
* @param {Boolean} sensitive
* @param {Boolean} strict
* @return {RegExp}
* @api private
*/
function pathtoRegexp(path, keys, sensitive, strict) {
if (path instanceof RegExp) return path;
if (path instanceof Array) path = '(' + path.join('|') + ')';
path = path
.concat(strict ? '' : '/?')
.replace(/\/\(/g, '(?:/')
.replace(/\+/g, '__plus__')
.replace(/(\/)?(\.)?:(\w+)(?:(\(.*?\)))?(\?)?/g, function(_, slash, format, key, capture, optional){
keys.push({ name: key, optional: !! optional });
slash = slash || '';
return ''
+ (optional ? '' : slash)
+ '(?:'
+ (optional ? slash : '')
+ (format || '') + (capture || (format && '([^/.]+?)' || '([^/]+?)')) + ')'
+ (optional || '');
})
.replace(/([\/.])/g, '\\$1')
.replace(/__plus__/g, '(.+)')
.replace(/\*/g, '(.*)');
return new RegExp('^' + path + '$', sensitive ? '' : 'i');
};
/// END Route object
// Added by tom, lifted from mini-pages, with some modifications
/**
Given a context object, returns a url path with the values of the context
object mapped over the path.
Alternatively, supply the named parts of the paths as discrete arguments.
@method pathWithContext
@param [context] {Object} An optional context object to use for
interpolation.
@example
// given a page with a path of "/posts/:_id/edit"
var path = page.pathWithContext({ _id: 123 });
// > /posts/123/edit
*/
RESTstop.Route.prototype.pathWithContext = function (context) {
var self = this,
path = self.path,
parts,
args = arguments;
/* get an array of keys from the path to replace with context values.
/* XXX Right now this comes from page-js. Remove dependency.
*/
parts = self.regexp.exec(self.path).slice(1);
context = context || {};
var replacePathPartWithContextValue = function (part, i) {
var re = new RegExp(part, "g"),
prop = part.replace(":", ""),
val;
if (_.isObject(context))
val = context[prop]
else
val = args[i];
path = path.replace(re, val || '');
};
_.each(parts, replacePathPartWithContextValue);
return path;
}