Skip to content

Commit

Permalink
新增delay实现,替换sleep阻塞进程方式
Browse files Browse the repository at this point in the history
wei.ma1 committed Nov 20, 2021
1 parent bba117c commit c130a07
Showing 21 changed files with 149 additions and 103 deletions.
10 changes: 5 additions & 5 deletions README-CN.md
Original file line number Diff line number Diff line change
@@ -2,7 +2,7 @@
mock数据更友好和强大

* 支持 es6 import/export, import导入库,export输出数据对象
* 支持 request、response、sleep(延迟响应ms)、validate(验证 参数和请求方式)
* 支持 request、response、delay(延迟响应ms)、validate(验证 参数和请求方式)
* 使用 validate 进行params及method校验

params校验规则参考:[node-input-validator](https://www.npmjs.com/package/node-input-validator)
@@ -34,7 +34,7 @@ module.exports = {
// url访问根路径名称
path: '/api',
// add express bodyParser
bodyParserApp: app,
app: app,
// 添加热加载
hotServer: server
}));
@@ -56,7 +56,7 @@ import test1 from './test1';
import test2 from './test2';

// 延迟500ms
sleep(500);
delay(500);

// 校验数据(如果校验不通过,则返回详细的校验错误作为请求响应)
validate({
@@ -96,8 +96,8 @@ export default {

* 在mock文件名称中使用 ```*``````**```,可以与字母组合使用。
* 一个 ```*``` 表示只匹配文件名称,连续 ```**``` 匹配多级路径名称和一个文件名称。
* 通配符与字母组合使用时,注意通配符位置,分为后匹配(```test*.js```) 前匹配(```*test.js```) 前后匹配(```*test*.js```) 全匹配(```*.js```)
* 注意文件名通配符的匹配顺序,无通配符的优先级最高,1个通配符次之(内部根据通配符位置的顺序:后匹配 前匹配 前后匹配 全匹配),然后是2个连续通配符(内部根据通配符位置的顺序:后匹配 前匹配 前后匹配 全匹配)。
* 通配符与字母组合使用时,注意通配符位置,分为前匹配(```test*.js```) 后匹配(```*test.js```) 居中匹配(```*test*.js```) 全匹配(```*.js```)
* 注意文件名通配符的匹配顺序,无通配符的优先级最高,1个通配符次之(内部根据通配符位置的顺序: 前匹配 后匹配 居中匹配 全匹配),然后是2个连续通配符(内部根据通配符位置的顺序:后匹配 前匹配 前后匹配 全匹配)。

如果一个mock文件夹目录存在如下的文件列表:

10 changes: 5 additions & 5 deletions README.md
Original file line number Diff line number Diff line change
@@ -2,7 +2,7 @@
This tool makes mock data friendly and powerful.

* Supports es6 import/export. import module lib, export json data.
* Supports request、response、sleep(delay response time)、validate(validate request params and method)
* Supports request、response、delay(delay response time)、validate(validate request params and method)
* Use Validate validates request params type and method

Params rule references:[node-input-validator](https://www.npmjs.com/package/node-input-validator)
@@ -34,7 +34,7 @@ module.exports = {
// Url root path
path: '/api',
// Add express bodyParser
bodyParserApp: app,
app: app,
// Set Hot Reload
hotServer: server
}));
@@ -56,7 +56,7 @@ import test1 from './test1';
import test2 from './test2';

// Delay response 500ms
sleep(500);
delay(500);

// Validate request (If validate failed, will return validate messages as response)
validate({
@@ -98,8 +98,8 @@ It is necessary to match the appropriate mock file and respond to the content.

* Mock filename use ```*``` and ```**```, these can be used in combination with letters.
* One ```*``` indicates that only match file name, Serie double ```**``` match multi-level pathes and a file name.
* When wildcards are combined with letters, pay attention to the position of wildcards, which are divided into tail matching(```test*.js```) front matching(```*test.js```) front&tail matching(```*test*.js```) whole matching(```*.js```)
* Note the matching order of file name wildcards. The file name without wildcards has the highest priority, then a single wildcard(The order of internal wildcard positions is: tail、front、front&tail、whole matching), and then two consecutive wildcards(The order of internal wildcard positions is: tail、front、front&tail、whole matching).
* When wildcards are combined with letters, pay attention to the position of wildcards, which are divided into front matching(```test*.js```) tail matching(```*test.js```) middle matching(```*test*.js```) whole matching(```*.js```)
* Note the matching order of file name wildcards. The file name without wildcards has the highest priority, then a single wildcard(The order of internal wildcard positions is: front、tail、middle、whole matching), and then two consecutive wildcards(The order of internal wildcard positions is: tail、front、front&tail、whole matching).

If a mock folder directory has the following file list:

3 changes: 1 addition & 2 deletions package.json
Original file line number Diff line number Diff line change
@@ -1,13 +1,12 @@
{
"name": "es6-mock",
"version": "2.5.4",
"version": "2.6.0",
"description": "es6-mock",
"main": "src/index.js",
"scripts": {
"start": "node test/index.js",
"debug": "node --inspect test/index.js",
"pub": "sh publish.sh",
"pubin": "npm publish --registry http://npm-registry.nevint.com/repository/npm-host/",
"puball": "npm run pub && npm run pubin",
"test": "node ./test/test/testAll"
},
34 changes: 23 additions & 11 deletions src/delay.js
Original file line number Diff line number Diff line change
@@ -1,12 +1,24 @@
/**
* 异步延迟
* @param time ms
* @returns {Promise<unknown>}
*/
module.exports = function(time = 0) {
return new Promise((resolve) => {
setTimeout(() => {
resolve(true);
}, time);
})
module.exports = function(time) {
if(global.__request){
global.__request.add(time);
}
};

module.exports.init = function (request) {
request.delay = {
value: 0,
add(time) {
this.value += time;
},
exec(){
if(this.value){
return new Promise((resolve) => {
setTimeout(() => {
resolve(true);
}, this.value);
})
}
return Promise.resolve(true);
}
}
}
9 changes: 9 additions & 0 deletions src/handleResponse.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
module.exports = function (request) {
return request.validate.exec()
.then((result) => {
if (result) {
return request.delay.exec();
}
return false;
})
}
69 changes: 36 additions & 33 deletions src/index.js
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
const path = require('path');
const Mock = require('mockjs');
const bodyParser = require('body-parser');
const requestQueue = require('./requestQueue');
const miniRequire = require('./mini-require');
const sleep = require('./sleep');
const handleResponse = require('./handleResponse');
const delay = require('./delay');
const validate = require('./validate');
const hotReload = require('./hotReload');
@@ -13,47 +13,45 @@ const hotReload = require('./hotReload');
* @param dir
* @param urlPath
* @param bodyParserApp app应用
* @param app app应用
* @param hotServer 热加载服务器
* @returns {(function(*, *, *): void)|*}
*/
module.exports = function ({ dir, path: urlPath, bodyParserApp, hotServer }) {
if (bodyParserApp) {
bodyParserApp.use(bodyParser.urlencoded({extended: false}));
bodyParserApp.use(bodyParser.json());
module.exports = function ({ dir, path: urlPath, bodyParserApp, app, hotServer }) {
app = app || bodyParserApp;
if (app) {
app.use(bodyParser.urlencoded({extended: false}));
app.use(bodyParser.json());
}
if (dir) {
hotReload(hotServer, dir);
}
return function (request, response, next) {
if (request.path.indexOf(urlPath) === 0) {
// 收集请求
requestQueue.push(() => {
const file = path.join('/', dir, `${
request.path.replace(urlPath, '')
.replace(/\.\w+/, '')
.replace(/\/$/, '')}`);
const file = path.join('/', dir, `${
request.path.replace(urlPath, '')
.replace(/\.\w+/, '')
.replace(/\/$/, '')}`);

try {
global.__request = request;
global.__response = response;
Object.assign(module.exports, {
request: global.__request,
response: global.__response,
});
const content = miniRequire(file, path.join(process.cwd(), dir));
// 验证为异步,需要一个等待
return delay(0).then(() => {
// 验证通过时返回值
if (!request.validateFailed) {
response.json(Mock.mock(content || {}));
}
}).catch(() => {});
} catch (e) {
response.status(404).send(e.message);
}
});
// 处理请求
requestQueue.exec();
try {
global.__request = request;
global.__response = response;
Object.assign(module.exports, {
request: global.__request,
response: global.__response,
});
delay.init(request, response);
validate.init(request, response);
const content = miniRequire(file, path.join(process.cwd(), dir));
// 验证和延迟为异步
return handleResponse(request, response).then((result) => {
if (result) {
response.json(Mock.mock(content || {}));
}
}).catch(() => {});
} catch (e) {
response.status(404).send(e.message);
}
} else {
next();
}
@@ -62,7 +60,12 @@ module.exports = function ({ dir, path: urlPath, bodyParserApp, hotServer }) {

Object.assign(module.exports, {
sleep,
validate,
delay: (time) => {
global.__request.delay.add(time);
},
validate: (validates) => {
global.__request.validate.add(validates);
},
request: global.__request,
response: global.__response,
getRequest: function (){
63 changes: 43 additions & 20 deletions src/validate.js
Original file line number Diff line number Diff line change
@@ -9,46 +9,69 @@ const Methods = {
};


module.exports = function (validates) {
__request.validated = true;
if(!validateMethod(validates.method)){
return validateParam(__request.method === Methods.Get ? __request.query : __request.body, validates.param || validates.params);
}
return Promise.resolve(false);
}

/**
* 校验参数
* @param body
* @param param
* @param request
* @param response
* @param validates
*/
function validateParam(body, param) {
const validator = new Validator(body, param);
function validateParam(request, response, validates) {
const validator = new Validator(
request.method === Methods.Get
? request.query
: request.body,
validates.param || validates.params);
return validator.check().then((matched) => {
if (!matched) {
__request.validateFailed = true;
__response.status(422).send(validator.errors);
response.status(422).send(validator.errors);
return false;
}
return true;
});
}

/**
* 验证请求method 'get|post|put|delete|patch'
* @param request
* @param response
* @param method
* @returns {boolean}
*/
function validateMethod(method){
function validateMethod(request, response, method){
if (method) {
const requestMethod = __request.method;
const requestMethod = request.method;
const methods = method.split('|').map(item => item.toUpperCase());
if(!methods.some(method => method === requestMethod)){
__request.validateFailed = true;
__response.status(422).send({
response.status(422).send({
method: `The request method is ${requestMethod}, doesn't support ${method.toUpperCase()}`
});
return true;
return false;
}
}
return true;
}

function validate(request, response, validates) {
if(validateMethod(request, response, validates.method)){
return validateParam(request, response, validates);
}
return Promise.resolve(true);
}

module.exports = validate;

module.exports.init = function (request, response) {
request.validate = {
value: {
param: {},
method: ''
},
add(validates) {
Object.assign(this.value.param, validates.param);
this.value.method = validates.method;
},
exec(){
return validate(request, response, this.value);
}
}
return false;
}
2 changes: 1 addition & 1 deletion test/test/testAll.js
Original file line number Diff line number Diff line change
@@ -2,7 +2,7 @@ const fetch = require('node-fetch');

const urls = [
'http://localhost:8000/api/test/test1?name=xx&&id=ss',
'http://localhost:8000/api/test/test2',
'http://localhost:8000/api/test/test2?name=xx&&id=ss',
'http://localhost:8000/api/test/test3?name=xx&&id=111',
'http://localhost:8000/api/test/wildcard/test',
'http://localhost:8000/api/test/wildcard/111test',
4 changes: 2 additions & 2 deletions test/test1.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { sleep, validate, request } from '../src/index';
import { delay, validate, request } from '../src/index';

// 延迟500ms
sleep(500);
delay(200);

// 校验数据
validate({
4 changes: 2 additions & 2 deletions test/test2.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { sleep, validate, request } from '../src/index';
import { delay, validate, request } from '../src/index';

// 延迟500ms
sleep(500);
delay(300);

// 校验数据
validate({
4 changes: 2 additions & 2 deletions test/test3.js
Original file line number Diff line number Diff line change
@@ -1,14 +1,14 @@
// import 导入工具库
import path from 'path';
import fs from 'fs';
import { sleep, validate, request } from '../src';
import { delay, validate, request } from '../src';

// import 导入其他mock模块
import test1 from './test1';
import test2 from './test2';

// 延迟500ms
sleep(500);
delay(400);

// 校验数据
validate({
4 changes: 2 additions & 2 deletions test/wildcard/**.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { sleep, validate } from '../../src/index';
import { delay, validate } from '../../src/index';

sleep(500);
delay(1300);

validate({
param: {},
4 changes: 2 additions & 2 deletions test/wildcard/**test**.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { sleep, validate } from '../../src/index';
import { delay, validate } from '../../src/index';

sleep(500);
delay(1200);

validate({
param: {},
4 changes: 2 additions & 2 deletions test/wildcard/**test.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { sleep, validate } from '../../src/index';
import { delay, validate } from '../../src/index';

sleep(500);
delay(1100);

validate({
param: {},
4 changes: 2 additions & 2 deletions test/wildcard/*.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { sleep, validate } from '../../src/index';
import { delay, validate } from '../../src/index';

sleep(500);
delay(900);

validate({
param: {},
4 changes: 2 additions & 2 deletions test/wildcard/*test*.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { sleep, validate } from '../../src/index';
import { delay, validate } from '../../src/index';

sleep(500);
delay(800);

validate({
param: {},
4 changes: 2 additions & 2 deletions test/wildcard/*test.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { sleep, validate } from '../../src/index';
import { delay, validate } from '../../src/index';

sleep(500);
delay(700);

validate({
param: {},
4 changes: 2 additions & 2 deletions test/wildcard/list.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { sleep, validate } from '../../src/index';
import { delay, validate } from '../../src/index';

sleep(500);
delay(500);

validate({
param: {},
4 changes: 2 additions & 2 deletions test/wildcard/test**.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { sleep, validate } from '../../src/index';
import { delay, validate } from '../../src/index';

sleep(500);
delay(1000);

validate({
param: {},
4 changes: 2 additions & 2 deletions test/wildcard/test*.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { sleep, validate } from '../../src/index';
import { delay, validate } from '../../src/index';

sleep(500);
delay(600);

validate({
param: {},
4 changes: 2 additions & 2 deletions test/wildcard/test.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { sleep, validate } from '../../src/index';
import { delay, validate } from '../../src/index';

sleep(500);
delay(500);

validate({
param: {},

0 comments on commit c130a07

Please sign in to comment.