-
Notifications
You must be signed in to change notification settings - Fork 3
/
index.ts
81 lines (64 loc) · 1.68 KB
/
index.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
import { isNull } from "./utils/isNull";
import { isString } from "./utils/isString";
type Argument = number | string;
type RouteChildren = Record<string, any>;
interface RouteProps {
[key: string]: any;
path: string;
paramName: string | null;
basePath: string;
}
const Route = function (
this: RouteProps,
path: string,
paramOrChildren: string | RouteChildren,
children?: RouteChildren,
) {
this.path = path;
this.paramName = isString(paramOrChildren)
? paramOrChildren as RouteProps['paramName']
: null;
this.basePath = '';
const updateChildren = (basePath: string): void => {
const paths = isString(paramOrChildren)
? children as RouteChildren
: paramOrChildren as RouteChildren;
if (paths) {
Object.keys(paths).forEach((key) => {
paths[key]().setBase(basePath);
this[key] = paths[key];
});
}
};
const setBase = (base: string): void => {
this.basePath = base;
};
const getArgPath = (arg: Argument): string => {
let argPath = '';
if (arg && !isNull(this.paramName)) {
argPath = `/${arg}`;
}
else if (!arg && !isNull(this.paramName)) {
argPath = `/${this.paramName}`;
}
else if (arg && isNull(this.paramName)) {
throw new Error(`Unexpected value \`${arg}\` provided to not parameterized route`);
}
return argPath;
};
const getPath = (arg: Argument): string => {
let newPath = `${this.basePath}${this.path}`;
newPath += getArgPath(arg);
updateChildren(newPath);
return newPath;
};
updateChildren(this.path);
return (arg: Argument = '') => ({
...this,
path: getPath(arg),
setBase,
});
} as any;
export {
Route,
};