UNPKG

4.62 kBJavaScriptView Raw
1/*!
2 * MOCK数据服务器
3 * https://github.com/hai2007/mock-servicer
4 *
5 * author hai2007 < https://hai2007.gitee.io/sweethome >
6 *
7 * Copyright (c) 2021 hai2007 走一步,再走一步。
8 * Released under the MIT license
9 */
10
11const http = require('http');
12const { log, fullPath } = require('@hai2007/nodejs');
13const fs = require('fs');
14const path = require('path');
15const url = require('url');
16const mineTypes = require('./mime.types.js');
17const responseFileList = require('./tool/responseFileList.js');
18const urlToString = require('./tool/urlToString');
19
20const jsonfile = JSON.parse(fs.readFileSync(path.join(__dirname, './package.json')));
21
22module.exports = function (config) {
23
24 const port = 'port' in config ? config.port : 8080; // 端口号
25 const basePath = fullPath(config.contentBase || "./", process.cwd());// 根路径
26 const mockBasePath = fullPath(config.mockBase || "./", process.cwd());// 根路径
27
28 http.createServer(function (request, response) {
29
30 let urlObject = url.parse(request.url);
31
32 // 获取data
33 require('./tool/getData')(request, data => {
34
35 let options = {
36
37 // 请求方法
38 method: request.method,
39
40 // url
41 url: urlObject.pathname.replace(/^\//, '').replace(/\/$/, ''),
42
43 // 请求参数
44 query: require('./tool/toQuery.js')(urlObject.query),
45
46 // 数据
47 value: data
48
49 };
50
51 // 用于区分这次请求的目的
52 let preUrl = options.url.split('/')[0];
53
54 let contentType = 'application/json';
55 let responseCode = '200';
56 let responseData = JSON.stringify(options);
57
58 // 新增或更新
59 // POST localhost:8080/update?url=XXX&method=XXX
60 if (preUrl == 'update') {
61
62 let datapath = fullPath("./mock-" + urlToString(options.query.url, options.query.method) + ".js", mockBasePath);
63
64 // 写入内容
65 fs.writeFileSync(datapath, `module.exports=function(Mock){
66 return ${options.value};
67};`);
68
69 }
70
71 // 删除
72 // localhost:8080/delete?url=XXX&method=XXX
73 else if (preUrl == 'delete') {
74
75 let datapath = fullPath("./mock-" + urlToString(options.query.url, options.query.method) + ".js", mockBasePath);
76
77 // 删除内容
78 if (fs.existsSync(datapath)) {
79 fs.unlinkSync(datapath);
80 }
81
82 }
83
84 // 查询
85 // localhost:8080/query?url=XXX&method=XXX
86 else if (preUrl == 'query') {
87
88 let datapath = fullPath("./mock-" + urlToString(options.query.url, options.query.method) + ".js", mockBasePath);
89
90 if (fs.existsSync(datapath)) {
91 try {
92 responseData = JSON.stringify(require(datapath)(require('mockjs')));
93 } catch (e) {
94 responseCode = "500";
95 responseData = "" + e;
96 contentType = 'text/plain';
97 }
98 } else {
99 responseCode = "404";
100 }
101
102 }
103
104 // 默认就作为普通的数据服务器
105 else {
106
107 // 请求的文件路径
108 let filePath = fullPath(options.url == "" ? "index.html" : options.url, basePath);
109
110 // 文件后缀名称
111 let dotName = /\./.test(filePath) ? filePath.match(/\.([^.]+)$/)[1] : "";
112
113 // 文件类型
114 if (dotName != "") contentType = mineTypes[dotName];
115
116 // 如果需要读取的文件存在
117 if (fs.existsSync(filePath) && !fs.lstatSync(filePath).isDirectory()) {
118 responseData = fs.readFileSync(filePath);
119 }
120
121 // 如果不存在,就返回404并列举出当前目录内容
122 // 这样的目的是为了方便二次开发
123 else {
124 responseCode = "404";
125 responseData = ('template404' in config ? config.template404 : require('./tool/template404'))(responseFileList(filePath));
126 contentType = "text/html";
127 }
128
129 }
130
131 response.writeHead(responseCode, {
132
133 // 设置跨域
134 "Access-Control-Allow-Origin": "*",// 允许的域
135 "Access-Control-Allow-Headers": "*",// 允许的header类型
136 "Access-Control-Allow-Methods": "*",// 允许的请求方法
137
138 // 标记服务器名称
139 "X-Powered-By": jsonfile.name + " " + jsonfile.version,
140
141 // 响应内容类型
142 "Content-Type": contentType + ";charset=utf-8"
143
144 });
145
146 response.write(responseData);
147
148 response.end();
149
150 });
151
152 })
153
154 // 启动监听
155 .listen(port);
156
157 log(jsonfile.name + ' running on port:' + port);
158
159};
\No newline at end of file