Skip to content

Commit d263606

Browse files
committed
增加拦截器
1 parent 064b52d commit d263606

File tree

5 files changed

+40
-16
lines changed

5 files changed

+40
-16
lines changed

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -136,6 +136,7 @@ module.exports = {
136136
| rules | object | - | 路由重写规则, 参考 [json-server rewriter](https://github.com/typicode/json-server#rewriter-example) |
137137
| loginUrl | string | - | 登录地址, 如果配置了loginUrl, 那么除登录和public属性为true的接口外, 其它接口必须在登录之后才可以正常执行 |
138138
| logoutUrl | string | - | 退出登录地址 |
139+
| interceptor | function | - | 拦截器, 用于拦截/修改发送的请求 |
139140

140141
mockData 属性, 存放客户端请求api时的返回数据, 以及对返回数据的一些操作
141142
支持的可选操作有:

index.js

Lines changed: 28 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -9,18 +9,18 @@ var Mock = _interopDefault(require('mockjs'));
99
var fs = require('fs');
1010

1111
/*! *****************************************************************************
12-
Copyright (c) Microsoft Corporation. All rights reserved.
13-
Licensed under the Apache License, Version 2.0 (the "License"); you may not use
14-
this file except in compliance with the License. You may obtain a copy of the
15-
License at http://www.apache.org/licenses/LICENSE-2.0
12+
Copyright (c) Microsoft Corporation.
1613
17-
THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
18-
KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
19-
WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
20-
MERCHANTABLITY OR NON-INFRINGEMENT.
14+
Permission to use, copy, modify, and/or distribute this software for any
15+
purpose with or without fee is hereby granted.
2116
22-
See the Apache Version 2.0 License for specific language governing permissions
23-
and limitations under the License.
17+
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
18+
REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
19+
AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
20+
INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
21+
LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
22+
OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
23+
PERFORMANCE OF THIS SOFTWARE.
2424
***************************************************************************** */
2525
/* global Reflect, Promise */
2626

@@ -170,6 +170,12 @@ var Http = /** @class */ (function () {
170170
};
171171
return Http;
172172
}());
173+
var noop = function (func) {
174+
if (typeof func === 'function') {
175+
return func;
176+
}
177+
return function () { };
178+
};
173179
var getInfo = function (req, option, headers) {
174180
var url = req._parsedUrl[/get/i.test(req.method) ? 'pathname' : 'href'].replace(/^\//, '');
175181
return {
@@ -335,15 +341,20 @@ var methodHandler = function (_a, next) {
335341
var server$1 = jsonServer.create();
336342
// 路径从根目录开始?
337343
var router = jsonServer.router(path.resolve(process.cwd(), 'db.json'));
338-
var middlewares = jsonServer.defaults({
339-
static: path.resolve(__dirname, './public')
340-
});
341-
server$1.use(middlewares);
342344
var createServer = function (option, callback) {
343345
var config = option.https;
344346
config = /^(boolean|number)$/.test(typeof config) ? config && {} : config;
345347
var currentServer;
346348
if (config instanceof Object) {
349+
if (typeof config.static === 'function') {
350+
config.static(jsonServer, server$1);
351+
}
352+
else {
353+
var middlewares = jsonServer.defaults({
354+
static: typeof config.static === 'string' ? config.static : path.resolve(process.cwd(), './public')
355+
});
356+
server$1.use(middlewares);
357+
}
347358
if (typeof config.key !== 'string' || typeof config.cert !== 'string' || config.key.length + config.cert.length === 0) {
348359
config.key = fs.readFileSync(path.join(__dirname, 'ssl/key.pem'));
349360
config.cert = fs.readFileSync(path.join(__dirname, 'ssl/cert.pem'));
@@ -397,6 +408,9 @@ var Server$1 = function (option, callback) {
397408
// 路由映射
398409
server$1.use(jsonServer.rewriter(option.rules instanceof Object ? option.rules : rules));
399410
server$1.use(function (req, res, next) {
411+
if (noop(option.interceptor)(req, res, next) === false) {
412+
return;
413+
}
400414
var http = new Http(res);
401415
var _a = getInfo(req, option, config$1.crossDomain), url = _a.url, data = _a.data, method = _a.method, urlKey = _a.urlKey, params = _a.params, headConfig = _a.headConfig;
402416
var result = {};

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.3.3",
3+
"version": "1.3.4",
44
"description": "mock server 模拟后端API接口",
55
"main": "index.js",
66
"scripts": {

src/server.ts

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@ import auth from './auth';
44
import config from './config';
55
import rules from './rules';
66
import * as https from 'https';
7-
import { Http, getInfo, formatResult, mockResult, authHandler, errorHandler, relayHandler, methodHandler } from './utils'
7+
import { Http, noop, getInfo, formatResult, mockResult, authHandler, errorHandler, relayHandler, methodHandler } from './utils'
88
import * as fs from 'fs';
99
import { mock } from '../';
1010
const server = jsonServer.create()
@@ -76,6 +76,9 @@ const Server = (option: mock.anyObject, callback?: Function) => {
7676
jsonServer.rewriter(option.rules instanceof Object ? option.rules : rules)
7777
)
7878
server.use((req, res, next) => {
79+
if (noop(option.interceptor)(req, res, next) === false) {
80+
return ;
81+
}
7982
const http = new Http(res)
8083
let {
8184
url,

src/utils.ts

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,12 @@ export class Http {
1414
this.res.end(typeof body === 'string' ? body : JSON.stringify(mockResult(body)))
1515
}
1616
}
17+
export const noop = (func: Function | any) : Function => {
18+
if (typeof func === 'function') {
19+
return func
20+
}
21+
return () => {}
22+
}
1723
export const getInfo = (req, option, headers) => {
1824
let url = req._parsedUrl[/get/i.test(req.method) ? 'pathname' : 'href'].replace(/^\//, '')
1925
return {

0 commit comments

Comments
 (0)