-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
65 lines (55 loc) · 1.33 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
/**
* @file 功能文件
* @author longze
*/
'use strict';
const assert = require('assert');
const fs = require('fs');
const resolve = require('path').resolve;
const url = require('url');
/**
* Expose `mock()`.
*/
module.exports = mock;
function getData(path, req, res, next) {
let body;
let absolutePath; // = path + '/index.js';
if (fs.existsSync(path + '.js')) {
absolutePath = path + '.js';
}
else if (fs.existsSync(path + '/index.js')) {
absolutePath = path + '/index.js';
}
if (fs.existsSync(absolutePath)) {
try {
body = require(absolutePath)(req, res, next);
delete require.cache[absolutePath];
}
catch (e) {
console.log(e);
}
}
return body;
}
/**
* auto path router from `root`.
*
* @param {string} rootPath mock文件夹根路径
* @return {Function}
* @api public
*/
function mock(rootPath) {
assert(rootPath, 'root path directory is required to serve files');
rootPath = resolve(rootPath);
return function (req, res, next) {
let pathname = url.parse(req.url).pathname;
let path = rootPath + '/' + req.method + pathname;
let body = getData(path, req, res, next);
if (body) {
res.send(body);
}
else {
next();
}
};
}