forked from tmeasday/meteor-router
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathrouter_server.js
209 lines (176 loc) · 5.56 KB
/
router_server.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
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
(function() {
// Route object taken from page.js
//
// Copyright (c) 2012 TJ Holowaychuk <[email protected]>
//
/**
* Initialize `Route` with the given HTTP `path`, HTTP `method`,
* and an array of `callbacks` and `options`.
*
* Options:
*
* - `sensitive` enable case-sensitive routes
* - `strict` enable strict matching for trailing slashes
*
* @param {String} path
* @param {String} method
* @param {Object} options.
* @api private
*/
function Route(path, method, options) {
options = options || {};
this.path = path;
this.method = method;
this.regexp = pathtoRegexp(path
, this.keys = []
, options.sensitive
, 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
*/
Route.prototype.match = function(path, method, params){
var keys, qsIndex, pathname, m;
if (this.method && this.method.toUpperCase() !== 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;
} else {
params.push(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
var Router = function() {
this._routes = [];
};
// simply match this path to this function
Router.prototype.add = function(path, method, endpoint) {
var self = this;
if (_.isObject(path) && ! _.isRegExp(path)) {
_.each(path, function(endpoint, p) {
self.add(p, endpoint);
});
} else {
if (! endpoint) {
// no http method was supplied so 2nd parameter is the endpoint
endpoint = method;
method = null;
}
if (! _.isFunction(endpoint)) {
endpoint = _.bind(_.identity, null, endpoint);
}
self._routes.push([new Route(path, method), endpoint]);
}
}
Router.prototype.match = function(request, response) {
for (var i = 0; i < this._routes.length; i++) {
var params = [], route = this._routes[i];
if (route[0].match(request.url, request.method, params)) {
context = {request: request, response: response, params: params}
var args = [];
for (key in context.params)
args.push(context.params[key]);
return route[1].apply(context, args);
}
}
return false;
}
// Make the router available
Meteor.Router = new Router();
// hook up the serving
var connect = __meteor_bootstrap__.require("connect");
__meteor_bootstrap__.app
.use(connect.query()) // <- XXX: we can probably assume accounts did this
.use(connect.bodyParser())
.use(function(req, res, next) {
// need to wrap in a fiber in case they do something async
// (e.g. in the database)
Fiber(function() {
var output = Meteor.Router.match(req, res);
if (output === false) {
return next();
} else {
// parse out the various type of response we can have
// array can be
// [content], [status, content], [status, headers, content]
if (_.isArray(output)) {
// copy the array so we aren't actually modifying it!
output = output.slice(0);
if (output.length === 3) {
var headers = output.splice(1, 1)[0];
_.each(headers, function(value, key) {
res.setHeader(key, value);
});
}
if (output.length === 2) {
res.statusCode = output.shift();
}
output = output[0];
}
if (_.isNumber(output)) {
res.statusCode = output;
output = '';
}
return res.end(output);
}
}).run();
});
}())