Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
akupiec
GitHub Repository: akupiec/mad-proxy
Path: blob/master/src/server.js
115 views
1
const express = require('express');
2
const bodyParser = require('body-parser');
3
// const cookieParser = require('cookie-parser');
4
const mockData = require('./middlewares/mockData');
5
const bodyDataInterceptor = require('./middlewares/bodyDataInterceptor');
6
const reverseProxy = require('./middlewares/reverseProxy');
7
const mockGetter = require('./middlewares/mockGeter');
8
const mockSaver = require('./middlewares/mockSaver');
9
const config = require('./config/config');
10
const path = require('path');
11
const fs = require('fs');
12
const LOGGER = require('./config/logger');
13
14
15
function isUrl(target = '') {
16
return target.match(/https?:\/\/.*/i);
17
}
18
function isDirectory(target = '') {
19
return fs.lstatSync(path.normalize(target)).isDirectory();
20
}
21
22
function isFile(target = '') {
23
return fs.lstatSync(path.normalize(target)).isFile();
24
}
25
26
module.exports = function () {
27
const app = express();
28
// app.use(cookieParser());
29
app.use(bodyParser.raw({type: '*/*'}));
30
31
config.proxies.map(confProxy => {
32
if(isUrl(confProxy.target)) {
33
LOGGER.info(`Binding reverse proxy on: ${confProxy.path} to ${confProxy.target}${confProxy.path}`);
34
app.use(confProxy.path, mockData(confProxy));
35
app.use(confProxy.path, bodyDataInterceptor(confProxy));
36
app.use(confProxy.path, mockSaver(confProxy));
37
app.use(confProxy.path, mockGetter(confProxy));
38
app.all(confProxy.path + '(/*)?', reverseProxy(confProxy));
39
40
} else if (isDirectory(confProxy.target)) {
41
const target = path.join(process.cwd(), confProxy.path, confProxy.target);
42
LOGGER.info(`Binding static hosting on: ${confProxy.path} to ${target}`);
43
app.use(confProxy.path, express.static(confProxy.target));
44
} else if (isFile(confProxy.target)) {
45
const target = path.join(process.cwd(), confProxy.path, confProxy.target);
46
LOGGER.info(`Binding static hosting on: ${confProxy.path} to ${target}`);
47
app.use(confProxy.path, function(req, res) {
48
res.sendFile(target);
49
});
50
} else {
51
LOGGER.error(`Can not bind host on: ${confProxy.path} to ${confProxy.target}, target should be: url, local directory or local file`);
52
}
53
});
54
55
// app.use(function (err, req, res, next) {
56
// console.error(err.stack);
57
// res.status(500).send('Something broke!');
58
// });
59
60
return app.listen(config.server.port, function () {
61
LOGGER.info(`LOCAL PROXY SERVER: listening on http://localhost:${config.server.port}\n\n`);
62
});
63
};
64
65