-
Notifications
You must be signed in to change notification settings - Fork 11
/
server.js
503 lines (446 loc) · 18.2 KB
/
server.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
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
"use strict";
var configFile = __dirname + '/config.json',
interfaceFolder = __dirname + '/dist';
var express = require('express'),
app = express(),
router = express.Router(),
proxy = require('express-http-proxy'),
Url = require('url'),
fs = require('fs'),
path = require('path'),
bodyParser = require('body-parser'),
cookieParser = require('cookie-parser'),
rimraf = require('rimraf'),
winston = require('winston'),
SandCastle = require('sandcastle').SandCastle,
sandcastle = new SandCastle(),
async = require('async'),
config = require(configFile);
var argv = require('minimist')(process.argv.slice(2));
if (argv.location) console.log('mocknode installation directory: ', __dirname);else if (argv.export) {
var fse = require('fs-extra'),
tmp_path = path.join(__dirname, 'tmp'),
tar = require('tar-fs');
fse.emptyDirSync(tmp_path);
fse.copySync(__dirname + '/stubs', tmp_path + '/stubs');
fse.copySync(__dirname + '/config.json', tmp_path + '/config.json');
tar.pack(tmp_path).pipe(fs.createWriteStream('mocknode-config.tar'));
console.log('mocknode config has been exported to mocknode-config.tar');
} else if (argv.import) {
var _tar = require('tar-fs');
fs.createReadStream(argv.import).pipe(_tar.extract(__dirname));
console.log('configuration has been imported');
} else {
(function () {
// App starts
var port = process.env.PORT || argv.port || config.port;
// Support for v0.x
var assign = require('object-assign');
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
app.use(cookieParser());
app.use(router);
var sleep = function sleep(milliseconds) {
var start = new Date().getTime();
for (var i = 0; i < 1e7; i++) {
if (new Date().getTime() - start > milliseconds) {
break;
}
}
};
var logger = {
changelog: new winston.Logger({
transports: [new winston.transports.File({
name: 'changelog',
filename: path.join(__dirname, 'logs', 'change.log')
})]
}),
accesslog: new winston.Logger({
transports: [new winston.transports.File({
name: 'accesslog',
filename: path.join(__dirname, 'logs', 'access.log')
})]
})
};
// Global headers and gloabl delay
// currently this is only read from the config file
// TODO: buid and interface for this.
var globalHeaders = function globalHeaders(globalConfig) {
return function (req, res, next) {
Object.keys(globalConfig.headers).map(function (header) {
res.setHeader(header, globalConfig.headers[header]);
});
if (globalConfig.delay) sleep(globalConfig.delay);
return next();
};
};
// Returns a middleware which proxies to the target
// TODO: exception handling for targets which are wrong,
// currently the proxy fails and breaks the server.
var assignNewProxy = function assignNewProxy(target) {
return proxy(target, {
forwardPath: function forwardPath(req, res) {
return Url.parse(req.originalUrl).path;
}
});
};
// Filesystems dont allow '/' in the names of folders / files,
// Converting this character to a '!'
var encodeRoutePath = function encodeRoutePath(route) {
return route.replace(/\//g, "!");
};
var decodeRoutePath = function decodeRoutePath(route) {
return route.replace(/!/g, "/");
};
// Creators and assigners - subtle abstraction : These return middlewares
var createProxyRoute = function createProxyRoute(route, target) {
return router.use(route, assignNewProxy(target));
};
var createStubRoute = function createStubRoute(route, stub) {
return router.use(route, stubHandler(route, stub));
};
var createDynamicStubRoute = function createDynamicStubRoute(route, dynamicStub) {
return router.use(route, dynamicStubHandler(route, dynamicStub));
};
var dynamicStubHandler = function dynamicStubHandler(_route, _name) {
var dynamicObj = void 0;
configLoop: for (var i = 0; i < config.routes.length; i++) {
if (config.routes[i].route == _route) {
for (var j = 0; j < config.routes[i].dynamicStubs.length; j++) {
if (config.routes[i].dynamicStubs[j].name == _name) {
dynamicObj = config.routes[i].dynamicStubs[j];
break configLoop;
}
};
};
}
return dynamicStubRequestHandler(_route, dynamicObj);
};
// Middleware which returns a stub
var stubHandler = function stubHandler(route, stub) {
return function (req, res, next) {
return res.sendFile(path.join(__dirname, 'stubs', encodeRoutePath(route), stub));
};
};
// Middleware which handles the dynamic stubs conditions
// Uses sandcastle to execute evals on a node sanbox.
// The req object parameters are injected into the execution
// runtime, so the eval expressions can access the req object.
var dynamicStubRequestHandler = function dynamicStubRequestHandler(_route, _stub) {
return function (req, res) {
var returnedStub = _stub.defaultStub,
continueLoop = true,
count = 0;
if (_stub.conditions.length) {
async.whilst(function () {
return count < _stub.conditions.length && continueLoop;
}, function (callback) {
var script = sandcastle.createScript('exports.main = function() {\n try {\n if (' + _stub.conditions[count].eval + ')\n exit(\'' + _stub.conditions[count].stub + '\')\n else\n exit(false)\n } catch(e) {\n exit(false)\n }\n }');
count++;
script.on('exit', function (err, output) {
if (output) {
continueLoop = false;
returnedStub = output;
}
callback();
});
script.run({
req: assign({}, {
baseURL: req.baseURL,
body: req.body,
cookies: req.cookies,
headers: req.headers,
hostname: req.hostname,
ip: req.ip,
ips: req.ips,
method: req.method,
originalUrl: req.originalUrl,
params: req.params,
path: req.path,
protocol: req.protocol,
query: req.query,
route: req.route,
signedCookies: req.signedCookies,
stale: req.stale,
subdomains: req.subdomains,
xhr: req.xhr
})
});
}, function (err) {
res.sendFile(path.join(__dirname, 'stubs', encodeRoutePath(_route), returnedStub));
});
} else {
res.sendFile(path.join(__dirname, 'stubs', encodeRoutePath(_route), returnedStub));
}
};
};
// Create and update a route
// TODO: RE-Implement this and make it pretty
var updateRoute = function updateRoute(_req) {
var matchCount = 0;
if (_req.old_route != _req.route) {
if (_req.old_route) deleteroute(_req.old_route);
delete _req.old_route;
} else {
delete _req.old_route;
var _iteratorNormalCompletion = true;
var _didIteratorError = false;
var _iteratorError = undefined;
try {
for (var _iterator = router.stack[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) {
var layer = _step.value;
var match = _req.route.match(layer.regexp);
if (match && match[0] == _req.route) {
layer.handle = _req.handle == "stub" ? stubHandler(_req.route, _req.stub) : _req.handle == "proxy" ? assignNewProxy(_req.proxy) : dynamicStubHandler(_req.route, _req.dynamicStub);
for (var i = 0; i < config.routes.length; i++) {
if (config.routes[i].route == _req.route) {
config.routes[i] = assign({}, config.routes[i], _req);
}
}
matchCount++;
}
}
} catch (err) {
_didIteratorError = true;
_iteratorError = err;
} finally {
try {
if (!_iteratorNormalCompletion && _iterator.return) {
_iterator.return();
}
} finally {
if (_didIteratorError) {
throw _iteratorError;
}
}
}
}
if (matchCount == 0) {
if (_req.handle == "stub") {
createStubRoute(_req.route, _req.stub);
} else if (_req.handle == "proxy") {
createProxyRoute(_req.route, _req.proxy);
} else if (_req.handle == "dynamicStub") {
createDynamicStubRoute(_req.route, _req.dynamicStub);
}
config.routes.push(assign({}, _req, { stubs: [], dynamicStubs: [] }));
var dir = path.join(__dirname, 'stubs', encodeRoutePath(_req.route));
if (!fs.existsSync(dir)) fs.mkdirSync(dir);
}
fs.writeFile(configFile, JSON.stringify(config, null, 2));
};
// Create and update for stubs
var updateStubs = function updateStubs(_req) {
var matchCount = 0;
routeLoop: for (var i = 0; i < config.routes.length; i++) {
if (config.routes[i].route == _req.route) {
for (var j = 0; j < config.routes[i].stubs.length; j++) {
if (config.routes[i].stubs[j].name == _req.oldname || config.routes[i].stubs[j].name == _req.name) {
config.routes[i].stubs[j].name = _req.name;
config.routes[i].stubs[j].description = _req.description;
fs.writeFileSync(path.join(__dirname, 'stubs', encodeRoutePath(_req.route), _req.name), _req.content);
if (_req.oldname) {
fs.rename(path.join(__dirname, 'stubs', encodeRoutePath(_req.route), _req.oldname), path.join(__dirname, 'stubs', encodeRoutePath(_req.route), _req.name));
}
matchCount++;
break routeLoop;
}
}
if (matchCount == 0) {
fs.writeFile(path.join(__dirname, 'stubs', encodeRoutePath(_req.route), _req.name), _req.content);
config.routes[i].stubs.push({ name: _req.name, description: _req.description });
}
}
}
fs.writeFile(configFile, JSON.stringify(config, null, 2));
};
// Create and update for dynamic stubs, this is very similar
// to that of stubs but there is no file associated, only the
// config is updated.
var updateDynamicStubs = function updateDynamicStubs(_req) {
var req = assign({}, _req);
var matchCount = 0,
oldname = req.oldname,
route = req.route;
delete req.oldname;
delete req.route;
routeLoop: for (var i = 0; i < config.routes.length; i++) {
if (config.routes[i].route == route) {
for (var j = 0; j < config.routes[i].dynamicStubs.length; j++) {
if (config.routes[i].dynamicStubs[j].name == oldname || config.routes[i].dynamicStubs[j].name == req.name) {
config.routes[i].dynamicStubs[j] = req;
matchCount++;
break routeLoop;
}
}
if (matchCount == 0) {
config.routes[i].dynamicStubs.push(req);
}
}
}
fs.writeFile(configFile, JSON.stringify(config, null, 2));
};
// Delete a route:
// 1. Remove it from the router stack
// 2. Remote it from config
// 3. Delete the stubs/route folder
var deleteroute = function deleteroute(_route) {
var index = router.stack.map(function (layer) {
return _route.match(layer.regexp);
}).reduce(function (index, item, i) {
return !!item ? i : index;
}, 0);
if (index > -1) {
router.stack.splice(index, 1);
rimraf(path.join(__dirname, 'stubs', encodeRoutePath(_route)), function () {});
}
var newRoutes = config.routes.filter(function (route) {
return route.route != _route;
});
config = assign(config, { routes: newRoutes });
fs.writeFile(configFile, JSON.stringify(config, null, 2));
};
// Delete a stub:
// 1. Delete the file
// 2. Remove the entry from config file
var deletestub = function deletestub(_route, _stub) {
fs.unlinkSync(path.join(__dirname, 'stubs', encodeRoutePath(_route), _stub));
routeLoop: for (var i = 0; i < config.routes.length; i++) {
if (config.routes[i].route == _route) {
for (var j = 0; j < config.routes[i].stubs.length; j++) {
if (config.routes[i].stubs[j].name == _stub) {
config.routes[i].stubs.splice(j, 1);
break routeLoop;
}
}
}
}
fs.writeFile(configFile, JSON.stringify(config, null, 2));
};
// Delete a dynamic stub:
// 1. Remove the entry from config file
var deleteDynamicstub = function deleteDynamicstub(_route, _stub) {
routeLoop: for (var i = 0; i < config.routes.length; i++) {
if (config.routes[i].route == _route) {
for (var j = 0; j < config.routes[i].dynamicStubs.length; j++) {
if (config.routes[i].dynamicStubs[j].name == _stub) {
config.routes[i].dynamicStubs.splice(j, 1);
break routeLoop;
}
}
}
}
fs.writeFile(configFile, JSON.stringify(config, null, 2));
};
// Expects that the dynamic stub properties are updated
// checks if the route is using this dynamic stub and updates its layer.handle
var updateDynamicRoutes = function updateDynamicRoutes(_route, _dynamicStub) {
for (var i = 0; i < config.routes.length; i++) {
if (_route == config.routes[i].route && _dynamicStub == config.routes[i].dynamicStub && "dynamicStub" == config.routes[i].handle) {
var _iteratorNormalCompletion2 = true;
var _didIteratorError2 = false;
var _iteratorError2 = undefined;
try {
for (var _iterator2 = router.stack[Symbol.iterator](), _step2; !(_iteratorNormalCompletion2 = (_step2 = _iterator2.next()).done); _iteratorNormalCompletion2 = true) {
var layer = _step2.value;
var match = config.routes[i].route.match(layer.regexp);
if (match && match[0] == config.routes[i].route) {
layer.handle = dynamicStubHandler(_route, _dynamicStub);
}
}
} catch (err) {
_didIteratorError2 = true;
_iteratorError2 = err;
} finally {
try {
if (!_iteratorNormalCompletion2 && _iterator2.return) {
_iterator2.return();
}
} finally {
if (_didIteratorError2) {
throw _iteratorError2;
}
}
}
}
}
};
var logRequest = function logRequest(_req, _type, _method) {
logger[_type][_method]({
'route': _req.path,
'query_strings': JSON.stringify(_req.query),
'request_body': JSON.stringify(_req.body),
'ip': _req.ip
});
};
// Logs all requests which do not start with '/mocknode/'
router.use('/', function (req, res, next) {
if (/^(?!\/mocknode\/)/.test(req.originalUrl) && /^(?!\/favicon.ico)/.test(req.originalUrl)) logRequest(req, 'accesslog', 'info');
next();
});
// Logs requests that change the configuration of mocknode
router.use('/mocknode/api', function (req, res, next) {
var logList = ['/modifyroute', '/deleteroute', '/modifystub', '/deletestub', '/modifydynamicstub', '/deletedynamicstub'];
if (logList.indexOf(req.path) > -1) logRequest(req, 'changelog', 'info');
next();
});
router.use('/mocknode', express.static(interfaceFolder));
router.use('/mocknode/api/config', function (req, res) {
return res.json(config);
});
router.use('/mocknode/api/stubconfig', function (req, res) {
return res.json(stubConfig);
});
router.use('/mocknode/api/logs', function (req, res) {
res.sendFile(path.join(__dirname, 'logs', req.query.name));
});
router.use('/mocknode/api/getstub', function (req, res) {
res.sendFile(path.join(__dirname, 'stubs', encodeRoutePath(req.query.route), req.query.name));
});
router.use('/mocknode/api/modifyroute', function (req, res, next) {
updateRoute(req.body);
res.send({ success: true });
});
router.use('/mocknode/api/deleteroute', function (req, res, next) {
deleteroute(req.query.route);
res.send({ success: true });
});
router.use('/mocknode/api/modifystub', function (req, res) {
updateStubs(req.body);
res.send({ success: true });
});
router.use('/mocknode/api/deletestub', function (req, res) {
deletestub(req.query.route, req.query.name);
res.send({ success: true });
});
router.use('/mocknode/api/modifydynamicstub', function (req, res) {
updateDynamicStubs(req.body);
updateDynamicRoutes(req.body.route, req.body.name);
res.send({ success: true });
});
router.use('/mocknode/api/deletedynamicstub', function (req, res) {
deleteDynamicstub(req.query.route, req.query.name);
res.send({ success: true });
});
router.use(globalHeaders(config.global));
config.routes.filter(function (configObj) {
return configObj.handle == "proxy";
}).map(function (configObj) {
return createProxyRoute(configObj.route, configObj.proxy);
});
config.routes.filter(function (configObj) {
return configObj.handle == "stub";
}).map(function (configObj) {
return createStubRoute(configObj.route, configObj.stub);
});
config.routes.filter(function (configObj) {
return configObj.handle == "dynamicStub";
}).map(function (configObj) {
return createDynamicStubRoute(configObj.route, configObj.dynamicStub);
});
app.listen(port);
console.log("Mocknode started on port: " + port);
console.log("open 'http://localhost:" + port + "/mocknode' in your browser to configure mocknode");
// App ends
})();
}