UNPKG

3.13 kBJavaScriptView Raw
1import "core-js/modules/es6.array.sort";
2import "core-js/modules/es6.regexp.split";
3import "core-js/modules/es6.array.index-of";
4import "core-js/modules/es6.regexp.replace";
5import "core-js/modules/es6.regexp.match";
6import "core-js/modules/es6.string.trim";
7import "core-js/modules/es6.array.map";
8import fs from 'fs';
9import Mock, { Random } from 'mockjs';
10import walkdir from 'node-walkdir';
11var RE = /^\s*\/\*[*\s]+?([^\r\n]+)[\s\S]+?@url\s+([^\n]+)[\s\S]+?\*\//im;
12
13function mock(_opts) {
14 var routes = {};
15
16 _opts.modules.map(function (_dir) {
17 fs.exists(_dir, function (exists) {
18 if (exists) {
19 walkdir(_dir, /\.js(on)?$/i, function (filepath) {
20 var content = String(fs.readFileSync(filepath, 'utf8')).trim() || '{}';
21 var url = filepath;
22 var describe = 'no description';
23 var m = content.match(RE);
24
25 if (m) {
26 url = m[2].trim();
27 describe = m[1].replace(/(^[\s*]+|[\s*]+$)/g, '');
28 }
29
30 if (url[0] !== '/') {
31 url = "/".concat(url);
32 }
33
34 var pathname = url;
35
36 if (pathname.indexOf('?') > -1) {
37 pathname = pathname.split('?')[0];
38 }
39
40 if (mock.debug && routes[pathname]) {
41 console.warn("[Mock Warn]: [".concat(filepath, ": ").concat(pathname, "] already exists and has been covered with new data."));
42 }
43
44 routes[pathname] = {
45 url: url,
46 filepath: filepath,
47 describe: describe
48 };
49
50 if (/\.js$/.test(filepath)) {
51 routes[pathname].data = require(filepath);
52 } else {
53 try {
54 routes[pathname].data = new Function("return (".concat(content, ")"))();
55 } catch (e) {
56 delete routes[pathname];
57 mock.debug && console.warn('[Mock Warn]:', e);
58 }
59 }
60 });
61 }
62 });
63 });
64
65 return function handle(req, res, next) {
66 res.set('Access-Control-Allow-Origin', '*');
67 res.set('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept');
68 res.set('Access-Control-Allow-Methods', 'PUT,POST,GET,DELETE,OPTIONS');
69
70 if (req.method === 'OPTIONS') {
71 return res.send('');
72 }
73
74 var url = req.originalUrl.split('?')[0];
75
76 if (url === '/api') {
77 var host = "".concat(req.protocol, "://").concat(req.headers.host).concat(req.baseUrl);
78 var list = Object.keys(routes).sort().map(function (path) {
79 var route = routes[path];
80 return {
81 title: route.describe,
82 url: host + route.url,
83 file: route.filepath
84 };
85 });
86 res.json(list);
87 }
88
89 var data = (routes[url] || 0).data;
90
91 if (data) {
92 if (typeof data === 'function') {
93 data = data(req, res, Mock);
94 }
95
96 var _mockData = Mock.mock(data);
97
98 if (req.query.callback) {
99 res.end("".concat(req.query.callback, "(").concat(JSON.stringify(_mockData), ")"));
100 } else {
101 res.json(_mockData);
102 }
103 } else {
104 next();
105 }
106 };
107}
108
109export default mock;
\No newline at end of file