-
Notifications
You must be signed in to change notification settings - Fork 757
/
utils.js
116 lines (109 loc) · 2.98 KB
/
utils.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
"use strict";
var fs = require("fs");
var filePath = require("path");
var serveIndex = require("serve-index");
var serveStatic = require("serve-static");
var _ = require("lodash");
var http = require("http");
var https = require("https");
var Immutable = require("immutable");
var isList = Immutable.List.isList;
var snippetUtils = require("./../snippet").utils;
var utils = {
/**
* @param app
* @param middleware
* @returns {*}
*/
addMiddleware: function (app, middleware) {
middleware.forEach(function (item) {
app.use(item);
});
return app;
},
/**
* @param app
* @param base
* @param opts
*/
addBaseDir: function (app, base, opts) {
opts = opts.toJS();
if (isList(base)) {
base.forEach(function (item) {
app.use(serveStatic(filePath.resolve(item), opts));
});
} else {
if (_.isString(base)) {
app.use(serveStatic(filePath.resolve(base), opts));
}
}
},
/**
* @param app
* @param base
*/
addDirectory: function (app, base) {
if (isList(base)) {
base = base.get(0);
}
app.use(serveIndex(filePath.resolve(base), {icons:true}));
},
/**
* @param app
* @param {Object} routes
*/
addRoutes: function (app, routes) {
Object.keys(routes).forEach(function (key) {
if (_.isString(key) && _.isString(routes[key])) {
app.use(key, serveStatic(filePath.resolve(routes[key])));
}
});
},
/**
* @param options
* @returns {{key, cert}}
*/
getKeyAndCert: function (options) {
return {
key: fs.readFileSync(options.getIn(["https", "key"]) || filePath.join(__dirname, "certs/server.key")),
cert: fs.readFileSync(options.getIn(["https", "cert"]) || filePath.join(__dirname, "certs/server.crt"))
};
},
/**
* @param filePath
* @returns {{pfx}}
*/
getPFX: function (filePath) {
return {
pfx: fs.readFileSync(filePath)
};
},
/**
* @param req
* @param res
* @param next
* @returns {*}
*/
handleOldIE: function (req, res, next) {
snippetUtils.isOldIe(req);
return next();
},
/**
* Get either an http or https server
*/
getServer: function (app, options) {
return {
server: (function () {
if (options.get("scheme") === "https") {
var pfxPath = options.getIn(["https", "pfx"]);
return pfxPath ?
https.createServer(utils.getPFX(pfxPath), app) :
https.createServer(utils.getKeyAndCert(options), app);
}
return http.createServer(app);
})(),
app: app
};
}
};
module.exports = utils;