-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcrux.js
263 lines (233 loc) · 9.15 KB
/
crux.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
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
/* =====================================================
crux - requests guided by the constellations
Crux is sensible, composable, data-driven routing.
It is entirely based on the excellent Clojure
router called "Polaris", which is part of the
"Caribou" ecosystem.
caribou: http://let-caribou.in
polaris: https://github.com/caribou/polaris
It is not possible to entirely mimic the behaviour
of polaris, as Clojure web routing is not asynchronous
and involves the concept of "middleware", that wraps
functions that handle web requests. Instead, crux
uses the concept of a middleware pipeline.
(c) Kyle Dawkins, 2015
===================================================== */
var mori = require("mori");
var parser = require("path-to-regexp");
var util = require("util");
var querystring = require("querystring");
function newRoute(key, method, path, route, action) {
return mori.hashMap(":key", key,
":method", method,
":path", path,
":route", route,
":action", action);
}
function newRouteTree(order, mapping) {
return mori.hashMap(":order", order,
":mapping", mapping);
}
function _keywordise(word) {
if (!word.match(/^:/)) {
return ":" + word;
}
return word;
}
function _unkeywordise(keyword) {
if (keyword.match(/^:/)) {
return keyword.replace(/^:/, "");
}
return keyword;
}
var crux = {
emptyRoutes: function() {
return newRouteTree(mori.vector(), mori.hashMap());
},
defaultAction: function(req, res) {
return res.status(500).send("No action defined at this route");
},
sanitiseMethod: function(method) {
method = method || ":all";
return _keywordise(method.toLowerCase());
},
compileRoute: function(path) {
var keys = [];
var re = parser(path, keys);
return mori.hashMap(":keys", keys, ":re", re);
},
mergeRoute: function(routes, key, method, path, action) {
var method = this.sanitiseMethod(method);
var compiledRoute = this.compileRoute(path);
var route = newRoute(key, method, path, compiledRoute, action);
var mapped = mori.assocIn(routes, mori.vector(":mapping", key), route);
return mori.updateIn(mapped, mori.vector(":order"), mori.conj, route);
},
METHOD_TYPES: mori.set(mori.vector(
":all", ":get", ":put", ":post", ":delete", ":options", ":head", ":trace", ":connect", ":patch"
)),
_actionMethods: function(action) {
var self = this;
if (mori.isAssociative(action)) {
return mori.reduce(function(acc, v) {
var k = _keywordise(mori.first(v));
if (mori.hasKey(self.METHOD_TYPES, k)) {
return mori.conj(acc, mori.vector(k, mori.nth(v, 1)));
}
return acc;
}, mori.vector(), action);
}
return mori.vector(mori.vector(":all", action));
},
pipeline: function() {
var funcs = mori.filter(mori.identity, mori.primSeq(arguments));
if (mori.count(funcs) === 0) {
return null;
}
if (mori.count(funcs) === 1) {
return mori.first(funcs);
}
var jsfuncs = mori.toJs(funcs);
return function(req, res, next) {
var _drain = function() {
var f = jsfuncs.shift();
if (f) {
return f(req, res, _drain);
}
return next();
};
_drain();
};
},
buildRoute: function(rootPath, pre, post, route) {
var path = mori.first(route);
var key = mori.nth(route, 1);
var action = mori.nth(route, 2);
var subroutes = mori.get(route, 3, null) || [];
var subPath = path.replace(/^\//, "");
var fullPath = rootPath + "/" + subPath;
fullPath = fullPath.replace(/\/$/, "");
var float = mori.get(action, ":float");
var sink = mori.get(action, ":sink");
var floated = crux.pipeline(float, pre);
var sunk = crux.pipeline(post, sink);
var children = crux.buildRouteTree(fullPath, floated, sunk, subroutes);
var actions = crux._actionMethods(action);
var routes = mori.map(
function(stuff) {
var method = mori.first(stuff);
var action = mori.nth(stuff, 1);
return mori.vector(key, method, fullPath, crux.pipeline(floated, action, sunk));
},
actions
);
return mori.concat(routes, children);
},
buildRouteTree: function(rootPath, pre, post, routeTree) {
var partial = function(route) {
return crux.buildRoute(rootPath, pre, post, route);
};
return mori.mapcat(partial, routeTree);
},
buildRoutes: function(routeTree, rootPath) {
routeTree = mori.toClj(routeTree);
rootPath = rootPath || "";
var routes = crux.emptyRoutes();
var built = crux.buildRouteTree(rootPath, null, null, routeTree);
return mori.reduce(function(routes, route) {
var key = mori.first(route);
var method = mori.nth(route, 1);
var path = mori.nth(route, 2);
var action = mori.nth(route, 3);
return crux.mergeRoute(routes, key, method, path, action);
}, routes, built);
},
// If you're not using express or some other system to match
// URLs to routes, then we can do it for you:
routeMatches: function(req, route) {
var requestMethod = _keywordise((req.method || ":get").toLowerCase());
var compiledRoute = mori.get(route, ":route");
var method = mori.get(route, ":method");
if (method === ":all" || method === requestMethod) {
var matchResult = mori.get(compiledRoute, ":re").exec(req.url);
if (matchResult) {
return mori.vector(route, matchResult);
}
}
return null;
},
findFirst: function(p, s) {
return mori.first(mori.remove(
function(x) { return x === null; },
mori.map(p, s)
));
},
router: function(routes, defaultAction) {
defaultAction = defaultAction || crux.defaultAction;
return function(req, res, next) {
next = next || mori.identity;
var orderedRoutes = mori.get(routes, ":order");
var match = crux.findFirst(mori.partial(crux.routeMatches, req), orderedRoutes);
if (match) {
var route = mori.get(match, 0);
var keys = mori.getIn(route, [":route", ":keys"]);
var result = mori.get(match, 1);
var params = mori.rest(result);
// What is the "legal" way to push things into req.params?
// TODO: this is kind of bent - almost certainly not 100% correct
if (params && !mori.isEmpty(params)) {
var jsParams = mori.toJs(params);
jsParams.forEach(function(p, i) {
var key = keys[i];
req.params[key.name] = p;
});
}
var action = mori.get(route, ":action", defaultAction);
if (action) {
return action.call(null, req, res, next);
}
}
return res.status(404);
};
},
_getPath: function(routes, key) {
var val = mori.getIn(routes, mori.vector(":mapping", _keywordise(key), ":path")) || null;
if (!val) { throw new Error("Route for " + key + " not found"); }
return val;
},
sortRouteParams: function(routes, key, params) {
var path = crux._getPath(routes, key);
var optKeys = mori.keys(params);
var pathParts = path.split(/\//);
var routeKeys = mori.map(_unkeywordise, mori.filter(function(p) {
return p.match(/^\:/);
}, mori.primSeq(pathParts)));
var queryKeys = mori.remove(mori.into(mori.set(), routeKeys), optKeys);
return mori.hashMap(":path", path,
":route", mori.selectKeys(params, routeKeys),
":query", mori.selectKeys(params, queryKeys));
},
reverseRoute: function(routes, key, params, options) {
params = params || {};
options = options || {};
var mparams = mori.toClj(params);
var gripped = crux.sortRouteParams(routes, key, mparams);
var path = mori.get(gripped, ":path");
var routeMatches = mori.get(gripped, ":route");
var queryMatches = mori.get(gripped, ":query");
var optKeys = mori.keys(mparams);
debugger;
var base = mori.reduce(function(s, rep) {
return s.replace(_keywordise(rep), params[rep]);
}, path, mori.keys(routeMatches));
var query = "";
if (!options["noQuery"]) {
query = querystring.stringify(mori.toJs(queryMatches));
if (query.length) {
query = "?" + query;
}
}
return base + query;
}
};
module.exports = crux;