forked from mCaptcha/mCaptcha
-
Notifications
You must be signed in to change notification settings - Fork 0
/
router.ts
91 lines (80 loc) · 1.95 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
// Copyright (C) 2022 Aravinth Manivannan <[email protected]>
// SPDX-FileCopyrightText: 2023 Aravinth Manivannan <[email protected]>
//
// SPDX-License-Identifier: AGPL-3.0-or-later
/** Removes trailing slash from URI */
const normalizeUri = (uri: string) => {
uri = uri.trim();
if (uri.length == 0) {
throw new Error("uri is empty");
}
const uriLength = uri.length;
if (uri[uriLength - 1] == "/") {
uri = uri.slice(0, uriLength - 1);
}
return uri;
};
/** URI<-> Fn mapping type */
type routeTuple = {
pattern: RegExp;
fn: () => void;
};
/**
* Router that selectively executes fucntions
* based on window.location.pathname
* */
export class Router {
routes: Array<routeTuple>;
constructor() {
this.routes = [];
}
/**
* registers a route-function pair with Router
* @param {string} uri - route to be registered
* @param {function} fn: - function to be registered when window.locatin.path
* matches uri
* */
register(uri: string, fn: () => void): void {
uri = normalizeUri(uri);
const pattern = new RegExp(`^${uri}$`);
const patterString = pattern.toString();
if (
this.routes.find((route) => {
if (route.pattern.toString() == patterString) {
return true;
} else {
return false;
}
})
) {
throw new Error("URI exists");
}
const route: routeTuple = {
pattern,
fn,
};
this.routes.push(route);
}
/**
* executes registered function with route
* matches window.pathname.location
* */
route(): void {
const path = normalizeUri(window.location.pathname);
let fn: undefined | (() => void);
if (
this.routes.find((route) => {
if (path.match(route.pattern)) {
fn = route.fn;
return true;
}
})
) {
if (fn === undefined) {
throw new Error("Route isn't registered");
} else {
return fn();
}
}
}
}