-
Notifications
You must be signed in to change notification settings - Fork 44
/
Copy pathrouteStore.js
108 lines (84 loc) · 2.59 KB
/
routeStore.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
'use strict';
const pareseRoutes = require('./parseRoutes')
, shallowMerge = require('./shallowMerge')
, mergeRoutes = (routeObj, newRoutesObj) => {
const parsed = pareseRoutes(newRoutesObj);
return {
standard: shallowMerge(routeObj.standard, parsed.standard)
, wildcard: shallowMerge(routeObj.wildcard, parsed.wildcard)
};
}
, isWildcard = (route, routes) => {
return Object.keys(routes.wildcard).find((rt) => {
return typeof routes.wildcard[rt] !== 'undefined' &&
route.match(routes.wildcard[rt].regex);
});
}
, notARoute = (route, routes) => {
return typeof routes.wildcard[route] === 'undefined' &&
typeof routes.standard[route] === 'undefined';
}
, cleanupRoute = (route, routesIn) => {
const routes = routesIn;
if (routes.wildcard[route] && routes.wildcard[route].verbs.length === 0) {
routes.wildcard[route] = undefined;
} else if (routes.standard[route] && routes.standard[route].length === 0) {
routes.standard[route] = undefined;
}
return routes;
};
let routes = {
standard: {}
, wildcard: {}
};
module.exports = {
add: (route, verbs) => {
const routeObj = {};
routeObj[route] = [].concat(verbs);
routes = mergeRoutes(routes, routeObj);
return routes;
}
, remove: (route, verbs) => {
const isWildcardRoute = isWildcard(route, routes);
if (notARoute(route, routes)) {
return routes;
}
if (typeof verbs === 'undefined') {
// safe to do this since a route can't be both
// and this is really really cheap
routes.wildcard[route] = undefined;
routes.standard[route] = undefined;
return routes;
}
if (isWildcardRoute) {
// wildcard route to delete here
routes.wildcard[route].verbs = routes.wildcard[route].verbs.filter((verb) => {
return [].concat(verbs).indexOf(verb) === -1;
});
} else {
// standard route to delete here
routes.standard[route] = routes.standard[route].filter((verb) => {
return [].concat(verbs).indexOf(verb) === -1;
});
}
return cleanupRoute(route, routes);
}
, get: () => {
return { wildcard: routes.wildcard, standard: routes.standard };
}
, getStandard: () => {
return routes.standard;
}
, getWildcard: () => {
return routes.wildcard;
}
, clear: () => {
routes = {
standard: {}
, wildcard: {}
};
}
, parse: (routeObj) => {
return mergeRoutes(routes, routeObj);
}
};