blob: a3219faf1655133652bfe0886eb0deca796b676b (
plain)
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
|
var specificity = require('route-order')();
var slash = require('express-slash');
function OKServer(options) {
if (!(this instanceof OKServer)) return new OKServer(options);
options = options || {};
if (!options.express)
throw new Error('No Express provided to OKServer');
if (!options.app)
throw new Error('No Express app provided to OKServer')
if (!options.views)
throw new Error('No views provided to OKServer');
var views = options.views;
var express = options.express;
var app = this._app = options.app;
Object.keys(views)
.sort(specificity)
.forEach(function(route) {
// We want to enforce trailing slashes for middleware
routeNoSlash = route.charAt(route.length - 1) === '/' ?
route.slice(0, route.length - 1) : route;
app.all(routeNoSlash, redirect(routeNoSlash));
app.use(routeNoSlash + '/', views[route].middleware());
});
// This enforces trailing slashes for stuff that isn't middleware
app.use(slash());
/**
* Create a handler which redirect all requests to
* the same route with a trailing slash appended
*/
function redirect(routeNoSlash) {
return function(req, res) {
res.redirect(301, routeNoSlash + '/');
}
}
}
OKServer.prototype.listen = function listen(port) {
this._app.listen(port || 1337);
return this;
};
module.exports = OKServer;
|