diff --git a/README-CN.md b/README-CN.md index adcac05..926237b 100644 --- a/README-CN.md +++ b/README-CN.md @@ -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文件夹目录存在如下的文件列表: diff --git a/README.md b/README.md index 2145a17..b3f11b6 100644 --- a/README.md +++ b/README.md @@ -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: diff --git a/package.json b/package.json index 87af52d..c3d4a30 100644 --- a/package.json +++ b/package.json @@ -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" }, diff --git a/src/delay.js b/src/delay.js index 338b338..de0eb30 100644 --- a/src/delay.js +++ b/src/delay.js @@ -1,12 +1,24 @@ -/** - * 异步延迟 - * @param time ms - * @returns {Promise} - */ -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); + } + } +} diff --git a/src/handleResponse.js b/src/handleResponse.js new file mode 100644 index 0000000..ec991b3 --- /dev/null +++ b/src/handleResponse.js @@ -0,0 +1,9 @@ +module.exports = function (request) { + return request.validate.exec() + .then((result) => { + if (result) { + return request.delay.exec(); + } + return false; + }) +} diff --git a/src/index.js b/src/index.js index c763944..7ffcb4e 100644 --- a/src/index.js +++ b/src/index.js @@ -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 (){ diff --git a/src/validate.js b/src/validate.js index 8d542e2..d65853b 100644 --- a/src/validate.js +++ b/src/validate.js @@ -9,25 +9,22 @@ 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; }); @@ -35,20 +32,46 @@ function validateParam(body, param) { /** * 验证请求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; } diff --git a/test/test/testAll.js b/test/test/testAll.js index fd16135..fa8e83b 100644 --- a/test/test/testAll.js +++ b/test/test/testAll.js @@ -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', diff --git a/test/test1.js b/test/test1.js index cac7af3..ab8bff9 100644 --- a/test/test1.js +++ b/test/test1.js @@ -1,7 +1,7 @@ -import { sleep, validate, request } from '../src/index'; +import { delay, validate, request } from '../src/index'; // 延迟500ms -sleep(500); +delay(200); // 校验数据 validate({ diff --git a/test/test2.js b/test/test2.js index 59efebb..ecd9396 100644 --- a/test/test2.js +++ b/test/test2.js @@ -1,7 +1,7 @@ -import { sleep, validate, request } from '../src/index'; +import { delay, validate, request } from '../src/index'; // 延迟500ms -sleep(500); +delay(300); // 校验数据 validate({ diff --git a/test/test3.js b/test/test3.js index ba3ef19..8d0dda0 100644 --- a/test/test3.js +++ b/test/test3.js @@ -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({ diff --git a/test/wildcard/**.js b/test/wildcard/**.js index 78b0952..8fe4b20 100644 --- a/test/wildcard/**.js +++ b/test/wildcard/**.js @@ -1,6 +1,6 @@ -import { sleep, validate } from '../../src/index'; +import { delay, validate } from '../../src/index'; -sleep(500); +delay(1300); validate({ param: {}, diff --git a/test/wildcard/**test**.js b/test/wildcard/**test**.js index 831a47a..82ee287 100644 --- a/test/wildcard/**test**.js +++ b/test/wildcard/**test**.js @@ -1,6 +1,6 @@ -import { sleep, validate } from '../../src/index'; +import { delay, validate } from '../../src/index'; -sleep(500); +delay(1200); validate({ param: {}, diff --git a/test/wildcard/**test.js b/test/wildcard/**test.js index 91a4669..f7db79c 100644 --- a/test/wildcard/**test.js +++ b/test/wildcard/**test.js @@ -1,6 +1,6 @@ -import { sleep, validate } from '../../src/index'; +import { delay, validate } from '../../src/index'; -sleep(500); +delay(1100); validate({ param: {}, diff --git a/test/wildcard/*.js b/test/wildcard/*.js index 123f465..ebf1982 100644 --- a/test/wildcard/*.js +++ b/test/wildcard/*.js @@ -1,6 +1,6 @@ -import { sleep, validate } from '../../src/index'; +import { delay, validate } from '../../src/index'; -sleep(500); +delay(900); validate({ param: {}, diff --git a/test/wildcard/*test*.js b/test/wildcard/*test*.js index 94a3583..a950b7b 100644 --- a/test/wildcard/*test*.js +++ b/test/wildcard/*test*.js @@ -1,6 +1,6 @@ -import { sleep, validate } from '../../src/index'; +import { delay, validate } from '../../src/index'; -sleep(500); +delay(800); validate({ param: {}, diff --git a/test/wildcard/*test.js b/test/wildcard/*test.js index 94ef42b..a4a7a3e 100644 --- a/test/wildcard/*test.js +++ b/test/wildcard/*test.js @@ -1,6 +1,6 @@ -import { sleep, validate } from '../../src/index'; +import { delay, validate } from '../../src/index'; -sleep(500); +delay(700); validate({ param: {}, diff --git a/test/wildcard/list.js b/test/wildcard/list.js index d6dc83a..c7a0771 100644 --- a/test/wildcard/list.js +++ b/test/wildcard/list.js @@ -1,6 +1,6 @@ -import { sleep, validate } from '../../src/index'; +import { delay, validate } from '../../src/index'; -sleep(500); +delay(500); validate({ param: {}, diff --git a/test/wildcard/test**.js b/test/wildcard/test**.js index 1560145..29d2c88 100644 --- a/test/wildcard/test**.js +++ b/test/wildcard/test**.js @@ -1,6 +1,6 @@ -import { sleep, validate } from '../../src/index'; +import { delay, validate } from '../../src/index'; -sleep(500); +delay(1000); validate({ param: {}, diff --git a/test/wildcard/test*.js b/test/wildcard/test*.js index 2f7e297..a7dc709 100644 --- a/test/wildcard/test*.js +++ b/test/wildcard/test*.js @@ -1,6 +1,6 @@ -import { sleep, validate } from '../../src/index'; +import { delay, validate } from '../../src/index'; -sleep(500); +delay(600); validate({ param: {}, diff --git a/test/wildcard/test.js b/test/wildcard/test.js index 016e79e..6a4487b 100644 --- a/test/wildcard/test.js +++ b/test/wildcard/test.js @@ -1,6 +1,6 @@ -import { sleep, validate } from '../../src/index'; +import { delay, validate } from '../../src/index'; -sleep(500); +delay(500); validate({ param: {},