UNPKG

1.65 kBJavaScriptView Raw
1import R from "ramda";
2import { isEmpty } from "./util";
3
4
5const formatMatchValue = (value) => isEmpty(value)
6 ? undefined
7 : value.trim();
8
9
10
11
12/**
13 * Provides an informational facet of a route.
14 */
15const parse = (route) => {
16 // Setup initial conditions.
17 if (isEmpty(route)) { throw new Error("A route string must be specified."); }
18 const parts = route.split("/");
19
20 // URL path.
21 let urlPath = R.takeLast(parts.length - 1, parts).join("/").trim();
22 urlPath = isEmpty(urlPath) ? undefined : urlPath;
23 if (urlPath) {
24 urlPath = urlPath.endsWith("/") ? urlPath : urlPath + "/";
25 }
26
27 return {
28 domain: parts[0].trim(),
29 path: urlPath,
30
31 /**
32 * Determines whether the domain/path values match the route.
33 * @param {string} domain: The domain name to match.
34 * @param {string} path: The URL path to match.
35 * @return {Boolean}
36 */
37 match(domain, path) {
38 domain = formatMatchValue(domain);
39 path = formatMatchValue(path);
40 if (path) { path = path.replace(/^\//, ""); }
41 const isWildcardDomain = this.domain === "*";
42
43 if (!isWildcardDomain) {
44 if (domain !== this.domain) { return false; }
45 }
46
47 if (this.path) {
48 if (!path) { return false; }
49 if (path && !(path + "/").startsWith(this.path)) { return false; }
50 }
51
52 // Finish up.
53 return true;
54 },
55
56
57 /**
58 * Retrieves a string representation of the route,
59 */
60 toString() {
61 return `${ this.domain }/${ this.path || "" }`.replace(/\/$/, "");
62 }
63 };
64};
65
66
67
68
69export default { parse };