Skip to content

Commit b712f7b

Browse files
committed
调整结构,修复转发地址出错
1 parent 2c69cf5 commit b712f7b

File tree

8 files changed

+1725
-1604
lines changed

8 files changed

+1725
-1604
lines changed

README.md

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -65,6 +65,7 @@ module.exports = {
6565
// 异步
6666
return new Promise((resolve, reject) => {
6767
setTimeout(() => {
68+
// reject(result)
6869
resolve(result)
6970
}, 1e4)
7071
})
@@ -194,13 +195,17 @@ mockData 属性, 存放客户端请求api时的返回数据, 以及对返回数
194195
* @param {object} params 请求参数
195196
* @param {any} result 默认返回结果的副本
196197
* @desc relay 可以是一个url字符串
197-
* @returns 参数数组, 会通过 apply 传给 request 模块, 参数说明参考 request 模块, (预置了最后一个函数参数, 建议不要传这个参数)
198+
* @returns 参数数组, 会通过 apply 传给 request 模块, 参数说明参考 request 模块, (预置了最后一个函数参数, 建议不要传这个参数) request中的传参字段: get为qs, post为form
198199
*/
199200
relay: (method, params, result) => {
200201
return ['url', {}, () => {}]
201202
},
203+
202204
// 请求方法, 返回数据
203205
// 返回数据可以使用 mockjs 来填充数据, 也可以直接写json
206+
207+
// 请求方法为函数时, 参数与其它方法一致, 但result为空对象, 返回值作为返回数据
208+
// get: (method, params, result) => {}
204209
get: {
205210
// ...
206211
},

index.js

Lines changed: 167 additions & 122 deletions
Original file line numberDiff line numberDiff line change
@@ -156,6 +156,20 @@ var rules = {
156156
'/api/*': '$1'
157157
};
158158

159+
var request = require('request');
160+
var Http = /** @class */ (function () {
161+
function Http(res) {
162+
this.res = null;
163+
this.res = res;
164+
}
165+
Http.prototype.writeHead = function (code, header) {
166+
this.res.writeHead(code, header);
167+
};
168+
Http.prototype.end = function (body) {
169+
this.res.end(typeof body === 'string' ? body : JSON.stringify(mockResult(body)));
170+
};
171+
return Http;
172+
}());
159173
var getInfo = function (req, option, headers) {
160174
var url = req._parsedUrl[/get/i.test(req.method) ? 'pathname' : 'href'].replace(/^\//, '');
161175
return {
@@ -175,21 +189,121 @@ var getInfo = function (req, option, headers) {
175189
var mockResult = function (result) {
176190
return result instanceof Object ? Mock.mock(result) : result;
177191
};
178-
var Http = /** @class */ (function () {
179-
function Http(res) {
180-
this.res = null;
181-
this.res = res;
192+
var errorHandler = function (_a) {
193+
var url = _a.url, http = _a.http, data = _a.data, method = _a.method, params = _a.params, result = _a.result, headConfig = _a.headConfig;
194+
if (typeof data.error === 'function') {
195+
var errResult = data.error(method, params, result, { url: url });
196+
if (errResult) {
197+
// 返回函数时, 可以在data.error得到两个参数res, headConfig, 方便进行自定义的错误输出
198+
if (typeof errResult === 'function') {
199+
errResult(http, headConfig);
200+
// 返回对象时, 将其作为错误信息输出
201+
}
202+
else if (typeof errResult === 'object') {
203+
http.writeHead(400, headConfig);
204+
http.end(errResult);
205+
// 输出默认错误信息
206+
}
207+
else {
208+
http.writeHead(400, headConfig);
209+
http.end({
210+
code: 400,
211+
message: typeof errResult === 'string' ? errResult : '请求出错'
212+
});
213+
}
214+
return false;
215+
}
182216
}
183-
Http.prototype.writeHead = function (code, header) {
184-
this.res.writeHead(code, header);
185-
};
186-
Http.prototype.end = function (body) {
187-
this.res.end(typeof body === 'string' ? body : JSON.stringify(mockResult(body)));
188-
};
189-
return Http;
190-
}());
217+
};
218+
var relayHandler = function (_a) {
219+
var req = _a.req, url = _a.url, http = _a.http, urlKey = _a.urlKey, data = _a.data, method = _a.method, params = _a.params, option = _a.option, headConfig = _a.headConfig;
220+
if (data.relay && /(string|function)/.test(typeof data.relay) || data.relay instanceof Object) {
221+
var relay = typeof data.relay === 'function' ? data.relay(method, params, data[method], { url: url }) : data.relay;
222+
if (!Array.isArray(relay)) {
223+
relay = [relay];
224+
}
225+
if (relay.length) {
226+
var url_1 = typeof relay[0] === 'string' ? relay[0] : relay[0] instanceof Object ? relay[0].url : '';
227+
if (url_1 && !/(http(s)|\/\/)/.test(url_1)) {
228+
var protocol = req.headers.referer.split(':')[0] + ':';
229+
if (typeof relay[0] == 'string') {
230+
relay[0] = protocol + '//' + (req.headers.host + relay[0]).replace(/\/+/g, '/');
231+
}
232+
else if (relay[0] instanceof Object) {
233+
relay[0].url = protocol + '//' + (req.headers.host + relay[0].url).replace(/\/+/g, '/');
234+
}
235+
}
236+
}
237+
request.apply(request, relay.concat(function (error, response, body) {
238+
if (!error) {
239+
try {
240+
if (response.statusCode === 200) {
241+
http.writeHead(200, headConfig);
242+
http.end(body);
243+
}
244+
else {
245+
http.writeHead(response.statusCode, headConfig);
246+
http.end(body);
247+
}
248+
// 如果是登录入口请求成功
249+
if (method === 'post' && urlKey === option.loginUrl) {
250+
auth.login(params);
251+
}
252+
}
253+
catch (e) {
254+
console.log(e);
255+
}
256+
}
257+
else {
258+
http.writeHead(400, headConfig);
259+
http.end({
260+
code: 400,
261+
message: "请求失败"
262+
});
263+
console.log(error);
264+
}
265+
}));
266+
return false;
267+
}
268+
};
269+
var methodHandler = function (_a, next) {
270+
var req = _a.req, url = _a.url, http = _a.http, urlKey = _a.urlKey, data = _a.data, method = _a.method, params = _a.params, option = _a.option, headConfig = _a.headConfig, result = _a.result, transfer = _a.transfer;
271+
// 请求成功的链接是登录入口, 没有被上面的错误拦截, 则视为登录成功
272+
if (urlKey === option.loginUrl) {
273+
auth.login(params);
274+
}
275+
if (urlKey === option.logoutUrl) {
276+
auth.logout();
277+
}
278+
// 如果存在当前的请求方法, 先根据配置进行处理, 再判断是否需要转交给 json-server
279+
var formatResult = data[method] && data.format ? data.format(method, params, result, { url: url }) : undefined;
280+
if (formatResult) {
281+
result = formatResult;
282+
}
283+
else if (transfer) {
284+
// 如果没有配置当前的请求方法, 则后续操作由json-server控制
285+
next();
286+
return false;
287+
}
288+
if (result instanceof Promise) {
289+
try {
290+
result.then(function (data) {
291+
http.writeHead(200, headConfig);
292+
http.end(data);
293+
}).catch(function (e) {
294+
http.writeHead(500, headConfig);
295+
http.end(e);
296+
});
297+
}
298+
catch (e) { }
299+
return false;
300+
}
301+
else {
302+
http.writeHead(200, headConfig);
303+
}
304+
return true;
305+
};
191306

192-
var request = require('request');
193307
var server$1 = jsonServer.create();
194308
// 路径从根目录开始?
195309
var router = jsonServer.router(path.resolve(process.cwd(), 'db.json'));
@@ -231,6 +345,23 @@ var createServer = function (option, callback) {
231345
createServer(option, callback);
232346
});
233347
};
348+
var formatResult = function (_a) {
349+
var data = _a.data, method = _a.method, params = _a.params, result = _a.result;
350+
try {
351+
result = JSON.parse(JSON.stringify(typeof data[method] == 'function'
352+
? data[method](method, params, result)
353+
: data[method] instanceof Object
354+
? data[method]
355+
: {}));
356+
}
357+
catch (e) {
358+
result = {};
359+
}
360+
if (!(result instanceof Object)) {
361+
result = {};
362+
}
363+
return result;
364+
};
234365
/**
235366
* 启动mock服务
236367
* @func
@@ -263,17 +394,25 @@ var Server$1 = function (option, callback) {
263394
// 1. 验证用户请求的api地址是否有数据
264395
if (data || transfer) {
265396
data = data || {};
266-
try {
267-
result = JSON.parse(JSON.stringify(typeof data[method] == 'function'
268-
? data[method](method, params, result)
269-
: data[method] instanceof Object
270-
? data[method]
271-
: {}));
272-
}
273-
catch (e) { }
274-
if (!(result instanceof Object)) {
275-
result = {};
276-
}
397+
result = formatResult({
398+
data: data,
399+
method: method,
400+
params: params,
401+
result: result
402+
});
403+
var allOption = {
404+
req: req,
405+
url: url,
406+
http: http,
407+
urlKey: urlKey,
408+
data: data,
409+
method: method,
410+
params: params,
411+
option: option,
412+
headConfig: headConfig,
413+
result: result,
414+
transfer: transfer
415+
};
277416
// 2. 处理鉴权
278417
// 当前链接不是登录入口 && 启用了鉴权功能 && 当前api需要鉴权 && 用户未能通过鉴权
279418
if (urlKey !== option.loginUrl && option.bounded && !data.public && !auth.verify()) {
@@ -285,112 +424,18 @@ var Server$1 = function (option, callback) {
285424
return;
286425
}
287426
// 3. 处理错误
288-
if (data.error && typeof data.error === 'function') {
289-
var errResult = data.error(method, params, result, { url: url });
290-
if (errResult) {
291-
// 返回函数时, 可以在data.error得到两个参数res, headConfig, 方便进行自定义的错误输出
292-
if (typeof errResult === 'function') {
293-
errResult(http, headConfig);
294-
// 返回对象时, 将其作为错误信息输出
295-
}
296-
else if (typeof errResult === 'object') {
297-
http.writeHead(400, headConfig);
298-
http.end(errResult);
299-
// 输出默认错误信息
300-
}
301-
else {
302-
http.writeHead(400, headConfig);
303-
http.end({
304-
code: 400,
305-
message: typeof errResult === 'string' ? errResult : '请求出错'
306-
});
307-
}
308-
return;
309-
}
427+
if (errorHandler(allOption) === false) {
428+
return;
310429
}
311430
// 4. 处理转发请求
312-
if (data.relay) {
313-
var relay = typeof data.relay === 'function' ? data.relay(method, params, data[method], { url: url }) : data.relay;
314-
if (!Array.isArray(relay)) {
315-
relay = [relay];
316-
}
317-
if (relay.length) {
318-
if (!/(http(s)|\/\/)/.test(relay[0])) {
319-
var protocol = req.headers.referer.split(':')[0] + ':';
320-
if (typeof relay[0] == 'string') {
321-
relay[0] = protocol + '//' + (req.headers.host + relay[0]).replace(/\/+/g, '/');
322-
}
323-
else if (relay[0] instanceof Object) {
324-
relay[0].url = protocol + '//' + (req.headers.host + relay[0].url).replace(/\/+/g, '/');
325-
}
326-
}
327-
}
328-
request.apply(request, relay.concat(function (error, response, body) {
329-
if (!error) {
330-
try {
331-
if (response.statusCode === 200) {
332-
http.writeHead(200, headConfig);
333-
http.end(body);
334-
}
335-
else {
336-
http.writeHead(response.statusCode, headConfig);
337-
http.end(body);
338-
}
339-
// 如果是登录入口请求成功
340-
if (method === 'post' && urlKey === option.loginUrl) {
341-
auth.login(params);
342-
}
343-
}
344-
catch (e) {
345-
console.log(e);
346-
}
347-
}
348-
else {
349-
http.writeHead(400, headConfig);
350-
http.end({
351-
code: 400,
352-
message: "请求失败"
353-
});
354-
console.log(error);
355-
}
356-
}));
431+
if (relayHandler(allOption) === false) {
357432
return;
358433
}
359434
// 5. 验证请求方法是否存在
360435
if (data[method] || transfer) {
361-
// 请求成功的链接是登录入口, 没有被上面的错误拦截, 则视为登录成功
362-
if (urlKey === option.loginUrl) {
363-
auth.login(params);
364-
}
365-
if (urlKey === option.logoutUrl) {
366-
auth.logout();
367-
}
368-
// 如果存在当前的请求方法, 先根据配置进行处理, 再判断是否需要转交给 json-server
369-
var formatResult = data[method] && data.format ? data.format(method, params, result, { url: url }) : undefined;
370-
if (formatResult) {
371-
result = formatResult;
372-
}
373-
else if (transfer) {
374-
// 如果没有配置当前的请求方法, 则后续操作由json-server控制
375-
next();
436+
if (methodHandler(allOption, next) === false) {
376437
return;
377438
}
378-
if (result instanceof Promise) {
379-
try {
380-
result.then(function (data) {
381-
http.writeHead(200, headConfig);
382-
http.end(data);
383-
}).catch(function (e) {
384-
http.writeHead(500, headConfig);
385-
http.end(e);
386-
});
387-
}
388-
catch (e) { }
389-
return;
390-
}
391-
else {
392-
http.writeHead(200, headConfig);
393-
}
394439
}
395440
else {
396441
http.writeHead(405, headConfig);

package.json

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
{
22
"name": "ks-mock",
3-
"version": "1.2.3",
3+
"version": "1.3.0",
44
"description": "mock server 模拟后端API接口",
55
"main": "index.js",
66
"scripts": {

public/datas.js

Lines changed: 10 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -41,12 +41,15 @@ exports.logout = {
4141
};
4242
exports.relay = {
4343
relay: function (method, params, result) {
44-
return {
45-
url: config.retryUrl,
46-
method: method,
47-
form: params,
48-
json: true
49-
};
44+
var _a;
45+
var key = /get/i.test(method) ? 'qs' : 'form';
46+
return _a = {
47+
url: config.retryUrl,
48+
method: method
49+
},
50+
_a[key] = params,
51+
_a.json = true,
52+
_a;
5053
}
5154
};
5255
exports.info = {
@@ -59,7 +62,7 @@ exports.info = {
5962
result.message = 'hello ' + (params.username || 'world');
6063
return new Promise(function (resolve, reject) {
6164
setTimeout(function () {
62-
reject(result);
65+
resolve(result);
6366
}, 1e4);
6467
});
6568
// 不返回, 那么修改无效

0 commit comments

Comments
 (0)