-
-
Notifications
You must be signed in to change notification settings - Fork 21
/
Copy pathrouter.ts
459 lines (415 loc) · 11.4 KB
/
router.ts
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
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
import pathToRegexp, { Key } from 'path-to-regexp';
import BrowserHistoryEngine from './engines/BrowserHistoryEngine';
import { Engine } from './engines/Engine';
export interface RouteError extends Error {
statusCode?: number;
}
export interface RouteContext {
/**
* The current path
*/
path: string;
/**
* Set a value in the context
*/
set: (key: string, value: unknown) => void;
[prop: string]: unknown;
}
export interface Request {
/**
* Returns anything passed as params, or query string, in this order. Fallback to null or
* a default value
*/
get: (k: string, def?: string) => string | null | undefined;
/**
* The current path of the request
*/
path: string;
/**
* A object contaning all the definied parameters found when matching the route
*/
params: { [k: string]: string };
/**
* Any parameter with no name
*/
splats: string[];
/**
* The query string keys/values
*/
query: {
[k: string]: string;
};
/**
* Stop execution of other matching routes
*/
stop: () => void;
/**
* Returns true if the route has been stopped
*/
isStopped: () => boolean;
}
export type RouteCallback = (
req: Request,
ctx: RouteContext,
) => void | Promise<void>;
export type AlwaysCallback = (ctx: RouteContext) => void | Promise<void>;
export type ErrorCallback = (
e: Error,
context: RouteContext,
) => void | Promise<void>;
type ExecuteRoutes = (
rs: Route[],
a: AlwaysCallback[],
path: string,
) => Promise<void>;
interface Route {
url: string | RegExp;
path: RegExp;
paramNames: Key[];
callback: RouteCallback;
}
export interface Router {
/**
* Add a new route to the router.
* When the path visited in the browser matches the path definition, the callback is executed
* @see https://github.com/ramiel/router.js#Usage
*/
get: (path: string | RegExp, callback: RouteCallback) => Router;
/**
* Add an handler that runs when a route is left.
* @see https://github.com/ramiel/router.js#Exithandlers
*/
exit: (path: string | RegExp, callback: RouteCallback) => Router;
/**
* This callbacks are executed for any path change, even if the request has been stopped.
* @see https://github.com/ramiel/router.js#Alwayscallbacks
*/
always: (callback: AlwaysCallback) => Router;
/**
* Run the callback when a route produces an error. If the error has
* a `statusCode` attached, it is matched. To catch any error use "*"
* @see https://github.com/ramiel/router.js#Errors
*/
error: (errorCode: number | '*', callback: ErrorCallback) => Router;
/**
* Navigate to a different path (like redirect)
*/
navigate: (path: string) => void;
/**
* Navigate to any path but do not execute route handlers
*/
setLocation: (path: string) => void;
/**
* Go to a specific page in the history
* @param {Number} relative Relative position from the current page which is 0
*/
go: (n?: number) => void;
/**
* Go back in the history
*/
back: () => void;
/**
* GO forward in the history
*/
forward: () => void;
/**
* Start route imediately, without waiting for the first user interaction.
* If path is passed the browser is taken to that path, otherwise the route handler
* relative to current path is executed
*/
run: (path?: string) => Router;
/**
* Remove any listener setup by te router
*/
teardown: () => Router;
/**
*Given a path, returns the correct path considering the basePath if any
*/
buildUrl: (path: string) => string;
/**
* Returns the option with which the router has been created
*/
getOptions: () => Omit<RouterOptions, 'engine'>;
/**
* @deprecated
*/
_getOptions: () => Omit<RouterOptions, 'engine'>;
}
export interface RouterOptions {
engine?: () => Engine;
ignoreCase?: boolean;
basePath?: string;
}
export type RouterFactoryType = (options?: RouterOptions) => Router;
interface CreateRequestOpts {
path: string;
params: { [k: string]: string };
splats: string[];
}
// -------------------------- Implementation
const LEADING_BACKSLASHES_MATCH = /\/*$/;
const createContext = (path: string): RouteContext => {
const context: RouteContext = {
path,
set: (key, value) => {
context[key] = value;
},
};
return context;
};
const createRequest = ({
path,
params,
splats,
}: CreateRequestOpts): Request => {
const [_, queryString] = path.split('?');
const query = (queryString || '').split('&').reduce((acc, q) => {
const [k, v] = q.split('=');
if (!k) return acc;
return {
...acc,
[decodeURIComponent(k)]: decodeURIComponent(v),
};
}, {});
let isStopped = false;
const req: Request = {
get: (key, def) =>
// eslint-disable-next-line no-nested-ternary
req.params && req.params[key] !== undefined
? req.params[key]
: req.query && key in req.query // eslint-disable-line no-nested-ternary
? req.query[key]
: def !== undefined
? def
: undefined,
path,
params,
splats,
query,
stop: () => {
isStopped = true;
},
isStopped: () => isStopped,
};
return req;
};
const createExecuteRoutes = (context: RouteContext) => {
const executeRoutes: ExecuteRoutes = async (matchedRoutes, always, path) => {
if (matchedRoutes.length > 0) {
const route = matchedRoutes[0];
const params: { [p: string]: string } = {};
const splats = [];
const [pathWithoutQuery] = path.split('?');
const match = pathWithoutQuery.match(route.path);
/* istanbul ignore else */
if (match) {
let j = 0;
for (j = 0; j < route.paramNames.length; j++) {
params[route.paramNames[j].name] = match[j + 1];
}
/* If any other match put them in request splat */
/* istanbul ignore else */
if (j < match.length) {
for (let k = j; k < match.length; k++) {
splats.push(match[k]);
}
}
}
const req = createRequest({
path,
params,
splats,
});
await route.callback(req, context);
if (!req.isStopped() && matchedRoutes.length > 1) {
return executeRoutes(matchedRoutes.slice(1), always, path);
}
}
if (always.length > 0) {
await always[0](context);
if (always.length > 1) {
return executeRoutes([], always.slice(1), path);
}
}
return Promise.resolve();
};
return executeRoutes;
};
const defaultOptions = {
ignoreCase: false,
basePath: '/',
engine: BrowserHistoryEngine(),
};
const createRouter: RouterFactoryType = (opt) => {
interface Handlers {
routes: Route[];
exits: Route[];
}
const handlers: Handlers = {
routes: [],
exits: [],
};
const always: AlwaysCallback[] = [];
const errors = new Map<number | '*', ErrorCallback[]>();
const options = { ...defaultOptions, ...opt };
const engine = options.engine();
const cleanBasePath = options.basePath.replace(LEADING_BACKSLASHES_MATCH, '');
const basePathRegExp = new RegExp(`^${cleanBasePath}`);
/* eslint-disable no-console */
errors.set(500, [
(e, context) => {
/* istanbul ignore else */
if (console && console.error) {
console.error(`500 - path: "${context.path}"`);
console.error(e);
}
},
]);
errors.set(404, [
(e, context) => {
/* istanbul ignore else */
if (console && console.warn) {
console.warn(`404 - path: "${context.path}"`);
console.warn(e);
}
},
]);
/* eslint-enable no-console */
const errorThrowerFactory = (context: RouteContext) => (
error: RouteError,
) => {
const { statusCode = 500 } = error;
const callbacks = errors.get(statusCode);
const alwaysCallbacks = errors.get('*');
/* istanbul ignore else */
if (callbacks || alwaysCallbacks) {
if (callbacks && callbacks.length > 0) {
callbacks.forEach((callback) => {
callback(error, context);
});
}
if (alwaysCallbacks && alwaysCallbacks.length > 0) {
alwaysCallbacks.forEach((callback) => {
callback(error, context);
});
}
} else {
throw error;
}
};
const onNavigation = (collectionName: 'routes' | 'exits') => async (
path: string,
): Promise<void> => {
const routes = handlers[collectionName];
const matchedIndexes = [];
// Path without base (contains query parameters)
let cleanPath = path.replace(basePathRegExp, '');
cleanPath = cleanPath === '' ? '/' : cleanPath;
// Path without base and without qurey parameters
let [urlToTest] = path.split('?');
urlToTest = urlToTest.replace(basePathRegExp, '');
urlToTest = urlToTest === '' ? '/' : urlToTest;
for (let i = 0, len = routes.length; i < len; i++) {
const route = routes[i];
if (route.path.test(urlToTest)) {
matchedIndexes.push(i);
}
}
const context: RouteContext = createContext(cleanPath);
if (collectionName === 'routes' && matchedIndexes.length === 0) {
const e: RouteError = new Error(`Path "${cleanPath}" not matched`);
e.statusCode = 404;
errorThrowerFactory(context)(e);
} else {
try {
const executeRoutes = createExecuteRoutes(context);
await executeRoutes(
matchedIndexes.map((i) => routes[i]),
always,
cleanPath,
);
} catch (e) {
errorThrowerFactory(context)(e);
}
}
};
engine.setup();
engine.addRouteChangeHandler(onNavigation('routes'));
engine.addRouteExitHandler(onNavigation('exits'));
const addRouteToCollection = (collectionName: 'routes' | 'exits') => (
path: string | RegExp,
callback: RouteCallback,
): void => {
if (!callback) {
throw new Error(`Missing callback for path "${path}"`);
}
const routes = handlers[collectionName];
const paramNames: Key[] = [];
const finalPath = pathToRegexp(path, paramNames, {
sensitive: !options.ignoreCase,
strict: false,
});
routes.push({
url: path,
path: finalPath,
paramNames,
callback,
});
};
const router: Router = {
get: (path, callback) => {
addRouteToCollection('routes')(path, callback);
return router;
},
exit: (path, callback) => {
addRouteToCollection('exits')(path, callback);
return router;
},
always: (callback) => {
if (!callback) {
throw new Error(
'A callback is mandatory when defining an "always" callback!',
);
}
always.push(callback);
return router;
},
error: (errorCode, callback) => {
errors.set(errorCode, [...(errors.get(errorCode) || []), callback]);
return router;
},
run: (path) => {
engine.run(path);
return router;
},
teardown: () => {
engine.teardown();
return router;
},
navigate: engine.navigate,
go: engine.go,
back: engine.back,
forward: engine.forward,
setLocation: engine.setLocation,
buildUrl: (path) => `${cleanBasePath}${path}`,
getOptions: () => ({
...options,
basePath: cleanBasePath,
engine: undefined,
}),
_getOptions: () => {
// eslint-disable-next-line no-console
console.warn(
'@deprecated _getOptions is deprecated, use getOptions instead',
);
return router.getOptions();
},
// @ts-ignore
_showRoutes: () => {
// eslint-disable-next-line no-console
console.log(handlers);
},
};
return router;
};
export default createRouter;