forked from annnhan/imitator
-
Notifications
You must be signed in to change notification settings - Fork 0
/
init.js
79 lines (71 loc) · 2.17 KB
/
init.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
/**
* Created by an.han on 15/7/20.
*/
//var Promise = require('es6-promise').Promise;
var imitator = require('./imitator');
var path = require('path');
var fs = require('fs');
var main = {
init: function (app, argv, cwd) {
this.app = app;
this.argv = argv;
this.cwd = cwd;
this.imitator = global.imitator = imitator;
this.extend();
this.customRoute();
this.defaultRoute();
},
extend: function () {
this.imitator.server = app;
},
customRoute: function () {
var argv = this.argv;
var home = process.env[process.platform === 'win32' ? 'USERPROFILE' : 'HOME'];
var defautImitatorFile = path.resolve(home, 'Imitatorfile.js');
var imitatorFile;
if (argv.f) {
if (process.platform === 'win32') {
imitatorFile = path.resolve(this.cwd, this.argv.f);
}
else {
if (argv.f[0] === '/') {
imitatorFile = argv.f;
}
else if(argv.f[0] === '~') {
imitatorFile = path.resolve(home, argv.f.replace(/^~\//, ''));
}
else {
imitatorFile = path.resolve(this.cwd, this.argv.f);
}
}
}
else {
imitatorFile = defautImitatorFile;
}
if (!fs.existsSync(imitatorFile)) {
console.warn('[WARN] imitator file not found!');
}
else {
global.imitatorFilePath = path.resolve(imitatorFile, '..');
require(imitatorFile)(imitator);
}
},
defaultRoute: function () {
var app = this.app;
setTimeout(function () {
app.use(function (req, res, next) {
var err = new Error('Not Found');
err.status = 404;
next(err);
});
app.use(function (err, req, res, next) {
res.json({
status: err.status || 500,
message: err.message,
err: err
});
});
});
}
};
module.exports = main.init.bind(main);