-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathrouter.js
273 lines (248 loc) · 7.88 KB
/
router.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
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
// Inspired by express.js and path.js
var noOp = function (){};
// # Router
// _Note the router is async and will never trigger synchronously._
// ## Example
// ### Setup
//
// var router = new Router();
// router
// .map( '/a/:b/' )
// .to( function ( route, next ) {
// next();
// })
// .to( function ( route ) {
// console.log( "b", route.params.b );
// })
// .map( '/a/:b/:c', 'GET' )
// .to( function ( route ) {
//
// })
// .map( '/a/:b/:c', [ 'POST', 'PUT' ] )
// .to( function ( route, next ) {
// next();
// })
// .whenMethod( 'POST', route, next, function () {
// next();
// })
// .whenMethod( ['POST', 'PUT'], route, next, function () {
// next();
// })
// .map( 'extra args' )
// .to( function ( route, x, y, z ) {
//
// })
// .noMatch( function ( route, extra ) {
// console.log( 'no route for', route.path );
// });
// ### Triggering
//
// With `onDone` as trigger will happen in next tick
//
// router.trigger( '/a/10/' ).onDone( function () {} );
//
// With method
//
// router.trigger( '/a/1/2/' ).withMethod( 'GET' );
//
// With extra arguments
//
// router.trigger( '/a/1/2/', 1, 2, 3 );
function Router () {
this.routes = [];
this.noMatch = function () {};
}
// ## Trigger
// Arguments:
// * path <String:URL/Pattern>
// * args...
Router.prototype.trigger = function (path) {
var self = this;
var triggerArguments = arguments;
var promise = new RouterTriggerPromise(noOp,noOp);
setTimeout((function (promise) {
return function () {
// Route detection
var matchingRoute;
var i = 0;
while ( i < self.routes.length ) {
if ( self.routes[i].method === promise.method && self.routes[i].match(path) ) {
matchingRoute = self.routes[i];
break;
}
++i;
}
if (matchingRoute) {
// convert the array with keys back to an object
var route = {
method : promise.method,
params : {},
path : path
};
Object.keys(matchingRoute.params).forEach(function (key) {
route.params[key] = matchingRoute.params[key];
});
var args = [route];
for (var j=1; j<triggerArguments.length; j++) {
args.push(triggerArguments[j]);
}
args.push( null ); // holder for next
// Action all sequentally
W.loop(matchingRoute.callbacks.length, function ( i, next, end ) {
var callback = matchingRoute.callbacks[ i ];
// Updated the
args[ args.length - 1 ] = next;
callback.apply(this, args);
}, function () {
promise.allCallbacksDidNext();
});
promise.done();
} else {
var route = {
method : promise.method,
params : {},
path : path
};
var args = [route];
for (var j=1; j<triggerArguments.length; j++) {
args.push(triggerArguments[j]);
}
self.noMatch.apply(this, args);
promise.done();
}
};
}(promise)),0);
return promise;
};
Router.prototype.map = function ( path, methods ) {
var routerContext = this;
var routes = [];
if ( typeof methods === 'undefined' || methods === null ) { methods = ['none']; }
if ( typeof methods === 'string' ) { methods = [methods]; }
methods.forEach(function (method) {
routes.push( new Route(method, path, [], {sensitive:true, strict:true}) );
});
this.routes = this.routes.concat(routes);
return new RouterMapPromise(routes, routerContext);
};
function RouterTriggerPromise(allCallbacksDidNext, onNoMatch) {
this.allCallbacksDidNext = allCallbacksDidNext;
this.onAllCallbacksDidNext = function ( fn ) {
this.allCallbacksDidNext = fn;
return this;
};
this.done = noOp;
this.onDone = function ( fn ) {
this.done = fn;
return this;
};
this.method = 'none';
this.withMethod = function ( method ) {
this.method = method;
return this;
};
}
function RouterMapPromise(routes, routerContext) {
var self = this;
this.to = function (fn) {
routes.forEach(function (route) {
route.callbacks.push(fn);
});
return self;
};
this.toWhenMethod = function (methods, fn) {
if ( !(methods instanceof Array) ) {
methods = [methods];
}
routes.forEach(function (route) {
route.callbacks.push(function (req) {
if ( methods.indexOf( req.method ) > -1 ) {
fn.apply( this, arguments );
} else {
// take the last argument, which is next and call it
arguments[ arguments.length-1 ]();
}
});
});
return self;
};
this.map = function () {
return routerContext.map.apply(routerContext, arguments);
};
this.trigger = function () {
return routerContext.trigger.apply(routerContext, arguments);
};
this.noMatch = function ( fn ) {
routerContext.noMatch = fn;
return this;
};
return this;
}
/**
* Initialize `Route` with the given HTTP `method`, `path`,
* and an array of `callbacks` and `options`.
*
* Options:
*
* - `sensitive` enable case-sensitive routes
* - `strict` enable strict matching for trailing slashes
*
* @param {String} method
* @param {String} path
* @param {Array} callbacks
* @param {Object} options.
* @api private
*/
function Route(method, path, callbacks, options) {
options = options || {};
this.path = path;
this.method = method;
this.callbacks = callbacks;
this.regexp = pathRegexp(path, this.keys = [], options.sensitive, options.strict);
}
/**
* Check if this route matches `path`, if so
* populate `.params`.
*
* @param {String} path
* @return {Boolean}
* @api private
*/
Route.prototype.match = function(path){
var keys = this.keys;
var params = this.params = [];
var m = this.regexp.exec(path);
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] = val;
} else {
params.push(val);
}
}
return true;
};
// Borrowed from express utils
function pathRegexp(path, keys, sensitive, strict) {
if (''+path == '[object RegExp]') return path;
if (Array.isArray(path)) path = '(' + path.join('|') + ')';
path = path
.concat(strict ? '' : '/?')
.replace(/\/\(/g, '(?:/')
.replace(/(\/)?(\.)?:(\w+)(?:(\(.*?\)))?(\?)?(\*)?/g, function(_, slash, format, key, capture, optional, star){
keys.push({ name: key, optional: !! optional });
slash = slash || '';
return ''
+ (optional ? '' : slash)
+ '(?:'
+ (optional ? slash : '')
+ (format || '') + (capture || (format && '([^/.]+?)' || '([^/]+?)')) + ')'
+ (optional || '')
+ (star ? '(/*)?' : '');
})
.replace(/([\/.])/g, '\\$1')
.replace(/\*/g, '(.*)');
return new RegExp('^' + path + '$', sensitive ? '' : 'i');
}