/
index.js
70 lines (62 loc) · 2.02 KB
/
index.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
var express = require('express')
var router = express.Router()
var jsonfile = require('jsonfile');
var mkdirp = require('mkdirp');
var path = require('path');
var glob = require('glob');
var bodyParser = require('body-parser')
var defaultOptions={
timeout:500,
contextPath:"/"
}
module.exports = function (app,options) {
// parse application/x-www-form-urlencoded
router.use(bodyParser.urlencoded({
extended: false
}));
// parse application/json
router.use(bodyParser.json());
router.use(options.contextPath||defaultOptions.contextPath, express.static(path.join(__dirname, 'stubs-ui')));
router.get('/stubs/allStubs', function (req, res) {
glob('**/*.json*', {
cwd: 'stubs',
}, function (er, files) {
res.json(files.map(function (loc) {
return {
name: path.basename(loc),
path: path.dirname(loc),
fullPath: loc
};
}));
});
});
router.post('/stubs/saveData', function (req, res) {
var file = path.join(process.cwd(),'stubs' , req.body.path);
var obj = req.body.data;
var getDirName = require('path').dirname;
mkdirp(getDirName(file), function (err) {
if (err) return cb(err);
jsonfile.writeFile(file, obj, {
spaces: 2
}, function (err) {
console.error(err);
res.json(err);
});
});
});
router.use(function ( err, req, res, next) {
res.status(404).send('');
});
app.use("/", router);
app.use('/*', function (req, res,next) {
var file = path.join(process.cwd() + '/stubs' + req.baseUrl + '.json');
console.log("Returning stub from file: " +file);
setTimeout(function () {
res.sendFile(file,{},function(err){
if(err){
next();
}
});
}, options.timeout||defaultOptions.timeout);
});
}