mocker-api
Advanced tools
Comparing version 2.8.0 to 2.8.1
#!/usr/bin/env node | ||
"use strict"; | ||
var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault"); | ||
var _regenerator = _interopRequireDefault(require("@babel/runtime/regenerator")); | ||
var _objectSpread2 = _interopRequireDefault(require("@babel/runtime/helpers/objectSpread2")); | ||
var _asyncToGenerator2 = _interopRequireDefault(require("@babel/runtime/helpers/asyncToGenerator")); | ||
var _path = _interopRequireDefault(require("path")); | ||
@@ -28,169 +20,140 @@ | ||
var CWD = process.cwd(); | ||
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } | ||
var PKG_PATH = _path["default"].resolve(CWD, './package.json'); | ||
const CWD = process.cwd(); | ||
var DEFAULT_MOCKER_CONFIG_PATH = _path["default"].resolve(CWD, './mocker.config.json'); | ||
const PKG_PATH = _path.default.resolve(CWD, './package.json'); | ||
var DEFAULT_MOCK_PATH = ['./mock']; | ||
var DEFAULT_CONFIG = { | ||
const DEFAULT_MOCKER_CONFIG_PATH = _path.default.resolve(CWD, './mocker.config.json'); | ||
const DEFAULT_MOCK_PATH = ['./mock']; | ||
const DEFAULT_CONFIG = { | ||
host: '0.0.0.0', | ||
port: 3721 | ||
}; | ||
(0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee() { | ||
var argvs, _require, version, paths, entryFiles, mockConfigPath, mockerConfig, pkgConf, DEFAULT_PORT, DEFAULT_HOST, app; | ||
return _regenerator["default"].wrap(function _callee$(_context) { | ||
while (1) { | ||
switch (_context.prev = _context.next) { | ||
case 0: | ||
argvs = (0, _minimist["default"])(process.argv.slice(2)); | ||
(async () => { | ||
const argvs = (0, _minimist.default)(process.argv.slice(2)); | ||
if (!(argvs.h || argvs.help)) { | ||
_context.next = 14; | ||
break; | ||
} | ||
if (argvs.h || argvs.help) { | ||
console.log('\n Usage: mocker <path> [--config] [--help|h]'); | ||
console.log('\n Displays help information.'); | ||
console.log('\n Options:'); | ||
console.log(' --config <path>', 'Simple configuration'); | ||
console.log('\n Example:'); | ||
console.log(' mocker mock/index.js'); | ||
console.log(' mocker mock/index.js --port 7788'); | ||
console.log(' mocker mock/index.js --host 0.0.0.0'); | ||
console.log(' mocker mock/m1.js test/m2.js'); | ||
console.log(' mocker mock/m1.js --config mocker.config.json'); | ||
console.log('\n'); | ||
return; | ||
} // Fix type errors | ||
console.log('\n Usage: mocker <path> [--config] [--help|h]'); | ||
console.log('\n Displays help information.'); | ||
console.log('\n Options:'); | ||
console.log(' --config <path>', 'Simple configuration'); | ||
console.log('\n Example:'); | ||
console.log(' mocker mock/index.js'); | ||
console.log(' mocker mock/index.js --port 7788'); | ||
console.log(' mocker mock/index.js --host 0.0.0.0'); | ||
console.log(' mocker mock/m1.js test/m2.js'); | ||
console.log(' mocker mock/m1.js --config mocker.config.json'); | ||
console.log('\n'); | ||
return _context.abrupt("return"); | ||
case 14: | ||
// Fix type errors | ||
_require = require('../../package.json'), version = _require.version; | ||
const { | ||
version | ||
} = require('../../package.json'); | ||
if (!(argvs.v || argvs.version)) { | ||
_context.next = 18; | ||
break; | ||
} | ||
if (argvs.v || argvs.version) { | ||
console.log(version); | ||
return; | ||
} | ||
console.log(version); | ||
return _context.abrupt("return"); | ||
const paths = argvs['_']; | ||
case 18: | ||
paths = argvs['_']; | ||
if (paths.length === 0) { | ||
console.log(_safe.default.red('Error: Need to pass parameters!')); | ||
console.log(`E.g: ${_safe.default.yellow('mocker <File path>')}\n`); | ||
return; | ||
} | ||
if (!(paths.length === 0)) { | ||
_context.next = 23; | ||
break; | ||
} | ||
const entryFiles = paths || DEFAULT_MOCK_PATH; | ||
let mockConfigPath = argvs.config || DEFAULT_MOCKER_CONFIG_PATH; | ||
let mockerConfig = DEFAULT_CONFIG; | ||
console.log(_safe["default"].red('Error: Need to pass parameters!')); | ||
console.log("E.g: ".concat(_safe["default"].yellow('mocker <File path>'), "\n")); | ||
return _context.abrupt("return"); | ||
if (argvs.config) { | ||
mockConfigPath = argvs.config; | ||
} | ||
case 23: | ||
entryFiles = paths || DEFAULT_MOCK_PATH; | ||
mockConfigPath = argvs.config || DEFAULT_MOCKER_CONFIG_PATH; | ||
mockerConfig = DEFAULT_CONFIG; | ||
if (!(0, _fs.existsSync)(_path.default.resolve(mockConfigPath))) { | ||
mockerConfig.host = process.env.HOST ? process.env.HOST : mockerConfig.host; | ||
mockerConfig.port = await (0, _detectPort.default)(mockerConfig.port); | ||
} else { | ||
mockerConfig = require(_path.default.resolve(mockConfigPath)); | ||
} | ||
/** | ||
* Support setting configuration on package.json | ||
* https://github.com/jaywcjlove/mocker-api/issues/144 | ||
*/ | ||
if (argvs.config) { | ||
mockConfigPath = argvs.config; | ||
} | ||
if ((0, _fs.existsSync)(_path["default"].resolve(mockConfigPath))) { | ||
_context.next = 34; | ||
break; | ||
} | ||
if ((0, _fs.existsSync)(PKG_PATH)) { | ||
const pkgConf = require(PKG_PATH); | ||
mockerConfig.host = process.env.HOST ? process.env.HOST : mockerConfig.host; | ||
_context.next = 31; | ||
return (0, _detectPort["default"])(mockerConfig.port); | ||
if (pkgConf.mocker) { | ||
Object.assign(mockerConfig, pkgConf.mocker); | ||
} | ||
} | ||
case 31: | ||
mockerConfig.port = _context.sent; | ||
_context.next = 35; | ||
break; | ||
if (argvs.host) { | ||
mockerConfig.host = argvs.host; | ||
} | ||
case 34: | ||
mockerConfig = require(_path["default"].resolve(mockConfigPath)); | ||
if (argvs.port) { | ||
mockerConfig.port = argvs.port; | ||
} | ||
case 35: | ||
/** | ||
* Support setting configuration on package.json | ||
* https://github.com/jaywcjlove/mocker-api/issues/144 | ||
*/ | ||
if ((0, _fs.existsSync)(PKG_PATH)) { | ||
pkgConf = require(PKG_PATH); | ||
const DEFAULT_PORT = mockerConfig.port; | ||
const DEFAULT_HOST = mockerConfig.host; | ||
const app = (0, _express.default)(); | ||
app.all('/*', (req, res, next) => { | ||
console.log(`${_safe.default.green(req.method)} - ${req.url}`); | ||
res.header('Access-Control-Allow-Origin', '*'); | ||
res.header('Access-Control-Allow-Headers', 'Content-Type,Content-Length,Authorization,Accept,X-Requested-With'); | ||
res.header('Access-Control-Allow-Methods', 'PUT,POST,GET,DELETE,OPTIONS'); | ||
next(); | ||
}); | ||
delete mockerConfig.port; | ||
delete mockerConfig.host; | ||
(0, _.default)(app, entryFiles, { ...mockerConfig | ||
}); | ||
app.listen(DEFAULT_PORT, () => { | ||
const localIpUrl = (0, _prepareUrls.default)({ | ||
protocol: 'http', | ||
host: DEFAULT_HOST, | ||
port: DEFAULT_PORT | ||
}); | ||
console.log(`> Server Listening at Local: ${_safe.default.green(localIpUrl.localUrl)}`); | ||
console.log(`> On Your Network: ${_safe.default.green(localIpUrl.lanUrl)}\n`); | ||
}); | ||
/** | ||
* Event listener for HTTP server "error" event. | ||
*/ | ||
if (pkgConf.mocker) { | ||
Object.assign(mockerConfig, pkgConf.mocker); | ||
} | ||
} | ||
app.on('error', error => { | ||
if (error.syscall !== 'listen') { | ||
throw error; | ||
} | ||
if (argvs.host) { | ||
mockerConfig.host = argvs.host; | ||
} | ||
const bind = typeof DEFAULT_PORT === 'string' ? `Pipe ${DEFAULT_PORT}` : `Port ${DEFAULT_PORT}`; // handle specific listen errors with friendly messages | ||
if (argvs.port) { | ||
mockerConfig.port = argvs.port; | ||
} | ||
switch (error.code) { | ||
case 'EACCES': | ||
console.error(`${bind} requires elevated privileges`); // eslint-disable-line | ||
DEFAULT_PORT = mockerConfig.port; | ||
DEFAULT_HOST = mockerConfig.host; | ||
app = (0, _express["default"])(); | ||
app.all('/*', function (req, res, next) { | ||
console.log("".concat(_safe["default"].green(req.method), " - ").concat(req.url)); | ||
res.header('Access-Control-Allow-Origin', '*'); | ||
res.header('Access-Control-Allow-Headers', 'Content-Type,Content-Length,Authorization,Accept,X-Requested-With'); | ||
res.header('Access-Control-Allow-Methods', 'PUT,POST,GET,DELETE,OPTIONS'); | ||
next(); | ||
}); | ||
delete mockerConfig.port; | ||
delete mockerConfig.host; | ||
(0, _["default"])(app, entryFiles, (0, _objectSpread2["default"])({}, mockerConfig)); | ||
app.listen(DEFAULT_PORT, function () { | ||
var localIpUrl = (0, _prepareUrls["default"])({ | ||
protocol: 'http', | ||
host: DEFAULT_HOST, | ||
port: DEFAULT_PORT | ||
}); | ||
console.log("> Server Listening at Local: ".concat(_safe["default"].green(localIpUrl.localUrl))); | ||
console.log("> On Your Network: ".concat(_safe["default"].green(localIpUrl.lanUrl), "\n")); | ||
}); | ||
/** | ||
* Event listener for HTTP server "error" event. | ||
*/ | ||
process.exit(1); | ||
break; | ||
app.on('error', function (error) { | ||
if (error.syscall !== 'listen') { | ||
throw error; | ||
} | ||
case 'EADDRINUSE': | ||
console.error(`${bind} is already in use`); // eslint-disable-line | ||
var bind = typeof DEFAULT_PORT === 'string' ? "Pipe ".concat(DEFAULT_PORT) : "Port ".concat(DEFAULT_PORT); // handle specific listen errors with friendly messages | ||
process.exit(1); | ||
break; | ||
switch (error.code) { | ||
case 'EACCES': | ||
console.error("".concat(bind, " requires elevated privileges")); // eslint-disable-line | ||
process.exit(1); | ||
break; | ||
case 'EADDRINUSE': | ||
console.error("".concat(bind, " is already in use")); // eslint-disable-line | ||
process.exit(1); | ||
break; | ||
default: | ||
throw error; | ||
} | ||
}); | ||
case 47: | ||
case "end": | ||
return _context.stop(); | ||
} | ||
default: | ||
throw error; | ||
} | ||
}, _callee); | ||
}))(); | ||
}); | ||
})(); | ||
//# sourceMappingURL=mocker.js.map |
@@ -6,3 +6,3 @@ "use strict"; | ||
}); | ||
exports["default"] = delay; | ||
exports.default = delay; | ||
@@ -27,7 +27,6 @@ /** | ||
*/ | ||
function delay(proxy) { | ||
var timer = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 0; | ||
var mockApi = {}; | ||
Object.keys(proxy).forEach(function (key) { | ||
var result = proxy[key]; | ||
function delay(proxy, timer = 0) { | ||
const mockApi = {}; | ||
Object.keys(proxy).forEach(key => { | ||
const result = proxy[key]; | ||
@@ -38,3 +37,3 @@ if (Object.prototype.toString.call(result) === '[object String]' && /^http/.test(result) || key === '_proxy' || timer === 0) { | ||
mockApi[key] = function (req, res) { | ||
var foo; | ||
let foo; | ||
@@ -44,3 +43,3 @@ if (Object.prototype.toString.call(result) === '[object Function]') { | ||
} else { | ||
foo = function foo(_req, _res) { | ||
foo = (_req, _res) => { | ||
return _res.json(result); | ||
@@ -50,3 +49,3 @@ }; | ||
setTimeout(function () { | ||
setTimeout(() => { | ||
foo(req, res); | ||
@@ -53,0 +52,0 @@ }, timer); |
116
lib/index.js
"use strict"; | ||
var _interopRequireWildcard = require("@babel/runtime/helpers/interopRequireWildcard"); | ||
var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault"); | ||
Object.defineProperty(exports, "__esModule", { | ||
value: true | ||
}); | ||
exports["default"] = _default; | ||
exports.default = _default; | ||
var _objectSpread2 = _interopRequireDefault(require("@babel/runtime/helpers/objectSpread2")); | ||
var _path = _interopRequireDefault(require("path")); | ||
@@ -28,14 +22,15 @@ | ||
var pathToRegexp = toRegexp.pathToRegexp; | ||
var mocker = {}; | ||
function _getRequireWildcardCache() { if (typeof WeakMap !== "function") return null; var cache = new WeakMap(); _getRequireWildcardCache = function () { return cache; }; return cache; } | ||
function _default(app, watchFile) { | ||
var conf = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {}; | ||
var watchFiles = (Array.isArray(watchFile) ? watchFile : typeof watchFile === 'string' ? [watchFile] : []).map(function (str) { | ||
return _path["default"].resolve(str); | ||
}); | ||
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } return newObj; } | ||
if (watchFiles.some(function (file) { | ||
return !file; | ||
})) { | ||
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } | ||
const pathToRegexp = toRegexp.pathToRegexp; | ||
let mocker = {}; | ||
function _default(app, watchFile, conf = {}) { | ||
const watchFiles = (Array.isArray(watchFile) ? watchFile : typeof watchFile === 'string' ? [watchFile] : []).map(str => _path.default.resolve(str)); | ||
if (watchFiles.some(file => !file)) { | ||
throw new Error('Mocker file does not exist!.'); | ||
@@ -49,9 +44,7 @@ } | ||
var isWatchFilePath = Array.isArray(watchFile) && watchFile.every(function (val) { | ||
return typeof val === 'string'; | ||
}) || typeof watchFile === 'string'; | ||
const isWatchFilePath = Array.isArray(watchFile) && watchFile.every(val => typeof val === 'string') || typeof watchFile === 'string'; | ||
mocker = isWatchFilePath ? getConfig() : watchFile; | ||
if (!mocker) { | ||
return function (req, res, next) { | ||
return (req, res, next) => { | ||
next(); | ||
@@ -61,4 +54,6 @@ }; | ||
var options = (0, _objectSpread2["default"])((0, _objectSpread2["default"])({}, conf), mocker._proxy || {}); | ||
var defaultOptions = { | ||
let options = { ...conf, | ||
...(mocker._proxy || {}) | ||
}; | ||
const defaultOptions = { | ||
changeHost: true, | ||
@@ -79,3 +74,5 @@ pathRewrite: {}, | ||
}; | ||
options = (0, _objectSpread2["default"])((0, _objectSpread2["default"])({}, defaultOptions), options); // changeHost = true, | ||
options = { ...defaultOptions, | ||
...options | ||
}; // changeHost = true, | ||
// pathRewrite = {}, | ||
@@ -95,7 +92,5 @@ // proxy: proxyConf = {}, | ||
// 加上require.resolve,保证 `./mock/`能够找到`./mock/index.js`,要不然就要监控到上一级目录了 | ||
var watcher = _chokidar["default"].watch(watchFiles.map(function (watchFile) { | ||
return _path["default"].dirname(require.resolve(watchFile)); | ||
}), options.watchOptions); | ||
const watcher = _chokidar.default.watch(watchFiles.map(watchFile => _path.default.dirname(require.resolve(watchFile))), options.watchOptions); | ||
watcher.on('all', function (event, path) { | ||
watcher.on('all', (event, path) => { | ||
if (event === 'change' || event === 'add') { | ||
@@ -105,14 +100,14 @@ try { | ||
cleanCache(path); | ||
watchFiles.forEach(function (file) { | ||
return cleanCache(file); | ||
}); | ||
watchFiles.forEach(file => cleanCache(file)); | ||
mocker = getConfig(); | ||
if (mocker._proxy) { | ||
options = (0, _objectSpread2["default"])((0, _objectSpread2["default"])({}, options), mocker._proxy); | ||
options = { ...options, | ||
...mocker._proxy | ||
}; | ||
} | ||
console.log("".concat(_safe["default"].green_b.black(' Done: '), " Hot Mocker ").concat(_safe["default"].green(path.replace(process.cwd(), '')), " file replacement success!")); | ||
console.log(`${_safe.default.green_b.black(' Done: ')} Hot Mocker ${_safe.default.green(path.replace(process.cwd(), ''))} file replacement success!`); | ||
} catch (ex) { | ||
console.error("".concat(_safe["default"].red_b.black(' Failed: '), " Hot Mocker ").concat(_safe["default"].red(path.replace(process.cwd(), '')), " file replacement failed!!")); | ||
console.error(`${_safe.default.red_b.black(' Failed: ')} Hot Mocker ${_safe.default.red(path.replace(process.cwd(), ''))} file replacement failed!!`); | ||
} | ||
@@ -125,7 +120,7 @@ } | ||
app.all('/*', function (req, res, next) { | ||
app.all('/*', (req, res, next) => { | ||
/** | ||
* Get Proxy key | ||
*/ | ||
var proxyKey = Object.keys(options.proxy).find(function (kname) { | ||
const proxyKey = Object.keys(options.proxy).find(kname => { | ||
return !!pathToRegexp(kname.replace(new RegExp('^' + req.method + ' '), '')).exec(req.path); | ||
@@ -139,3 +134,3 @@ }); | ||
var mockerKey = Object.keys(mocker).find(function (kname) { | ||
const mockerKey = Object.keys(mocker).find(kname => { | ||
return !!pathToRegexp(kname.replace(new RegExp('^' + req.method + ' '), '')).exec(req.path); | ||
@@ -148,9 +143,10 @@ }); | ||
var accessOptions = (0, _objectSpread2["default"])({ | ||
const accessOptions = { | ||
'Access-Control-Allow-Origin': req.get('Origin') || '*', | ||
'Access-Control-Allow-Methods': 'POST, GET, OPTIONS, PUT, DELETE', | ||
'Access-Control-Allow-Headers': 'Content-Type, X-Requested-With,' + (req.header('access-control-request-headers') || ''), | ||
'Access-Control-Allow-Credentials': 'true' | ||
}, options.header); | ||
Object.keys(accessOptions).forEach(function (keyName) { | ||
'Access-Control-Allow-Credentials': 'true', | ||
...options.header | ||
}; | ||
Object.keys(accessOptions).forEach(keyName => { | ||
res.setHeader(keyName, accessOptions[keyName]); | ||
@@ -160,5 +156,3 @@ }); // fix issue 34 https://github.com/jaywcjlove/mocker-api/issues/34 | ||
if (!mockerKey && req.method.toLocaleUpperCase() === 'OPTIONS' && Object.keys(mocker).find(function (kname) { | ||
return !!pathToRegexp(kname.replace(new RegExp('^(PUT|POST|GET|DELETE) '), '')).exec(req.path); | ||
})) { | ||
if (!mockerKey && req.method.toLocaleUpperCase() === 'OPTIONS' && Object.keys(mocker).find(kname => !!pathToRegexp(kname.replace(new RegExp('^(PUT|POST|GET|DELETE) '), '')).exec(req.path))) { | ||
return res.sendStatus(200); | ||
@@ -174,8 +168,8 @@ } | ||
return (0, _mockerHandle.mockerHandle)({ | ||
req: req, | ||
res: res, | ||
next: next, | ||
mocker: mocker, | ||
options: options, | ||
mockerKey: mockerKey | ||
req, | ||
res, | ||
next, | ||
mocker, | ||
options, | ||
mockerKey | ||
}); | ||
@@ -190,8 +184,8 @@ } else if (proxyKey && options.proxy[proxyKey]) { | ||
return (0, _mockerHandle.mockerHandle)({ | ||
req: req, | ||
res: res, | ||
next: next, | ||
mocker: mocker, | ||
options: options, | ||
mockerKey: mockerKey | ||
req, | ||
res, | ||
next, | ||
mocker, | ||
options, | ||
mockerKey | ||
}); | ||
@@ -224,3 +218,3 @@ } | ||
(0, _clearModule["default"])(modulePath); | ||
(0, _clearModule.default)(modulePath); | ||
} | ||
@@ -233,10 +227,10 @@ /** | ||
function getConfig() { | ||
return watchFiles.reduce(function (mocker, file) { | ||
var mockerItem = require(file); | ||
return watchFiles.reduce((mocker, file) => { | ||
const mockerItem = require(file); | ||
return Object.assign(mocker, mockerItem["default"] ? mockerItem["default"] : mockerItem); | ||
return Object.assign(mocker, mockerItem.default ? mockerItem.default : mockerItem); | ||
}, {}); | ||
} | ||
return function (req, res, next) { | ||
return (req, res, next) => { | ||
next(); | ||
@@ -243,0 +237,0 @@ }; |
"use strict"; | ||
var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault"); | ||
Object.defineProperty(exports, "__esModule", { | ||
@@ -10,4 +8,2 @@ value: true | ||
var _objectSpread2 = _interopRequireDefault(require("@babel/runtime/helpers/objectSpread2")); | ||
var _url = _interopRequireDefault(require("url")); | ||
@@ -19,13 +15,16 @@ | ||
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } | ||
function mockerHandle(param) { | ||
var _ref = param || {}, | ||
_ref$options = _ref.options, | ||
options = _ref$options === void 0 ? {} : _ref$options, | ||
req = _ref.req, | ||
res = _ref.res, | ||
next = _ref.next, | ||
mocker = _ref.mocker, | ||
mockerKey = _ref.mockerKey; | ||
const { | ||
options = {}, | ||
req, | ||
res, | ||
next, | ||
mocker, | ||
mockerKey | ||
} = param || {}; | ||
var bodyParserMethd = _bodyParser["default"].json((0, _objectSpread2["default"])({}, options.bodyParserJSON)); // 默认使用json解析 | ||
let bodyParserMethd = _bodyParser.default.json({ ...options.bodyParserJSON | ||
}); // 默认使用json解析 | ||
@@ -38,3 +37,3 @@ /** | ||
var contentType = req.get('Content-Type'); | ||
let contentType = req.get('Content-Type'); | ||
contentType = contentType && contentType.replace(/;.*$/, ''); | ||
@@ -47,17 +46,21 @@ | ||
case 'raw': | ||
bodyParserMethd = _bodyParser["default"].raw((0, _objectSpread2["default"])({}, options.bodyParserRaw)); | ||
bodyParserMethd = _bodyParser.default.raw({ ...options.bodyParserRaw | ||
}); | ||
break; | ||
case 'text': | ||
bodyParserMethd = _bodyParser["default"].text((0, _objectSpread2["default"])({}, options.bodyParserText)); | ||
bodyParserMethd = _bodyParser.default.text({ ...options.bodyParserText | ||
}); | ||
break; | ||
case 'urlencoded': | ||
bodyParserMethd = _bodyParser["default"].urlencoded((0, _objectSpread2["default"])({ | ||
extended: false | ||
}, options.bodyParserUrlencoded)); | ||
bodyParserMethd = _bodyParser.default.urlencoded({ | ||
extended: false, | ||
...options.bodyParserUrlencoded | ||
}); | ||
break; | ||
case 'json': | ||
bodyParserMethd = _bodyParser["default"].json((0, _objectSpread2["default"])({}, options.bodyParserJSON)); | ||
bodyParserMethd = _bodyParser.default.json({ ...options.bodyParserJSON | ||
}); | ||
//使用json解析 break; | ||
@@ -70,13 +73,16 @@ } | ||
case 'text/plain': | ||
bodyParserMethd = _bodyParser["default"].raw((0, _objectSpread2["default"])({}, options.bodyParserRaw)); | ||
bodyParserMethd = _bodyParser.default.raw({ ...options.bodyParserRaw | ||
}); | ||
break; | ||
case 'text/html': | ||
bodyParserMethd = _bodyParser["default"].text((0, _objectSpread2["default"])({}, options.bodyParserText)); | ||
bodyParserMethd = _bodyParser.default.text({ ...options.bodyParserText | ||
}); | ||
break; | ||
case 'application/x-www-form-urlencoded': | ||
bodyParserMethd = _bodyParser["default"].urlencoded((0, _objectSpread2["default"])({ | ||
extended: false | ||
}, options.bodyParserUrlencoded)); | ||
bodyParserMethd = _bodyParser.default.urlencoded({ | ||
extended: false, | ||
...options.bodyParserUrlencoded | ||
}); | ||
break; | ||
@@ -87,6 +93,6 @@ } | ||
bodyParserMethd(req, res, function () { | ||
var result = mocker[mockerKey]; | ||
const result = mocker[mockerKey]; | ||
if (typeof result === 'function') { | ||
var rgxStr = ~mockerKey.indexOf(' ') ? ' ' : ''; | ||
const rgxStr = ~mockerKey.indexOf(' ') ? ' ' : ''; | ||
req.params = (0, _utils.pathMatch)({ | ||
@@ -96,3 +102,3 @@ sensitive: false, | ||
end: false | ||
})(mockerKey.split(new RegExp(rgxStr))[1])(_url["default"].parse(req.url).pathname); | ||
})(mockerKey.split(new RegExp(rgxStr))[1])(_url.default.parse(req.url).pathname); | ||
result(req, res, next); | ||
@@ -99,0 +105,0 @@ } else { |
"use strict"; | ||
var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault"); | ||
Object.defineProperty(exports, "__esModule", { | ||
@@ -16,9 +14,9 @@ value: true | ||
function proxyHandle(req, res) { | ||
var options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {}; | ||
var proxyKey = arguments.length > 3 ? arguments[3] : undefined; | ||
var currentProxy = options.proxy[proxyKey]; | ||
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } | ||
var url = _url["default"].parse(currentProxy); | ||
function proxyHandle(req, res, options = {}, proxyKey) { | ||
const currentProxy = options.proxy[proxyKey]; | ||
const url = _url.default.parse(currentProxy); | ||
if (options.changeHost) { | ||
@@ -28,7 +26,6 @@ req.headers.host = url.host; | ||
var _options$httpProxy = options.httpProxy, | ||
_options$httpProxy$op = _options$httpProxy.options, | ||
proxyOptions = _options$httpProxy$op === void 0 ? {} : _options$httpProxy$op, | ||
_options$httpProxy$li = _options$httpProxy.listeners, | ||
proxyListeners = _options$httpProxy$li === void 0 ? {} : _options$httpProxy$li; | ||
const { | ||
options: proxyOptions = {}, | ||
listeners: proxyListeners = {} | ||
} = options.httpProxy; | ||
/** | ||
@@ -39,5 +36,5 @@ * rewrite target's url path. Object-keys will be used as RegExp to match paths. | ||
Object.keys(options.pathRewrite).forEach(function (rgxStr) { | ||
var rePath = req.path.replace(new RegExp(rgxStr), options.pathRewrite[rgxStr]); | ||
var currentPath = [rePath]; | ||
Object.keys(options.pathRewrite).forEach(rgxStr => { | ||
const rePath = req.path.replace(new RegExp(rgxStr), options.pathRewrite[rgxStr]); | ||
const currentPath = [rePath]; | ||
@@ -48,12 +45,12 @@ if (req.url.indexOf('?') > 0) { | ||
req.query = _url["default"].parse(req.url, true).query; | ||
req.query = _url.default.parse(req.url, true).query; | ||
req.url = req.originalUrl = currentPath.join('?'); | ||
}); | ||
var proxyHTTP = _httpProxy["default"].createProxyServer({}); | ||
const proxyHTTP = _httpProxy.default.createProxyServer({}); | ||
proxyHTTP.on('error', function (err) { | ||
console.error("".concat(_safe["default"].red_b.black(" Proxy Failed: ".concat(err.name)), " ").concat(err.message || '', " ").concat(err.stack || '', " !!")); | ||
proxyHTTP.on('error', err => { | ||
console.error(`${_safe.default.red_b.black(` Proxy Failed: ${err.name}`)} ${err.message || ''} ${err.stack || ''} !!`); | ||
}); | ||
Object.keys(proxyListeners).forEach(function (event) { | ||
Object.keys(proxyListeners).forEach(event => { | ||
proxyHTTP.on(event, proxyListeners[event]); | ||
@@ -60,0 +57,0 @@ }); |
"use strict"; | ||
var _interopRequireWildcard = require("@babel/runtime/helpers/interopRequireWildcard"); | ||
Object.defineProperty(exports, "__esModule", { | ||
@@ -12,4 +10,8 @@ value: true | ||
var pathToRegexp = toRegexp.pathToRegexp; | ||
function _getRequireWildcardCache() { if (typeof WeakMap !== "function") return null; var cache = new WeakMap(); _getRequireWildcardCache = function () { return cache; }; return cache; } | ||
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } return newObj; } | ||
const pathToRegexp = toRegexp.pathToRegexp; | ||
function pathMatch(options) { | ||
@@ -16,0 +18,0 @@ options = options || {}; |
{ | ||
"name": "mocker-api", | ||
"version": "2.8.0", | ||
"version": "2.8.1", | ||
"description": "This is dev support mock RESTful API.", | ||
@@ -5,0 +5,0 @@ "bin": { |
@@ -1,11 +0,33 @@ | ||
<h2><p align="center"><b>Mocker API</b></p></h2> | ||
<p align="center"> | ||
<a href="https://uiwjs.github.io/npm-unpkg/#/pkg/mocker-api/file/README.md"> | ||
<img alt="Mocker API LOGO" src="https://user-images.githubusercontent.com/1680273/105850254-79939d00-601c-11eb-9450-b4f8aad62972.png"> | ||
</a> | ||
</p> | ||
[![](https://img.shields.io/github/issues/jaywcjlove/mocker-api.svg)](https://github.com/jaywcjlove/mocker-api/issues) | ||
[![](https://img.shields.io/github/forks/jaywcjlove/mocker-api.svg)](https://github.com/jaywcjlove/mocker-api/network) | ||
[![](https://img.shields.io/github/stars/jaywcjlove/mocker-api.svg)](https://github.com/jaywcjlove/mocker-api/stargazers) | ||
[![](https://img.shields.io/github/release/jaywcjlove/mocker-api)](https://github.com/jaywcjlove/mocker-api/releases) | ||
[![NPM version](https://img.shields.io/npm/v/mocker-api.svg)](https://www.npmjs.com/package/mocker-api) | ||
[![Build and Deploy](https://github.com/jaywcjlove/mocker-api/workflows/Build%20and%20Deploy/badge.svg)](https://github.com/jaywcjlove/mocker-api/actions) | ||
<p align="center"> | ||
<a href="https://github.com/jaywcjlove/mocker-api/actions"> | ||
<img alt="Build & Deploy" src="https://github.com/jaywcjlove/mocker-api/workflows/Build%20and%20Deploy/badge.svg"> | ||
</a> | ||
<a href="https://github.com/jaywcjlove/mocker-api/issues"> | ||
<img alt="Issues" src="https://img.shields.io/github/issues/jaywcjlove/mocker-api.svg"> | ||
</a> | ||
<a href="https://github.com/jaywcjlove/mocker-api/network"> | ||
<img alt="Forks" src="https://img.shields.io/github/forks/jaywcjlove/mocker-api.svg"> | ||
</a> | ||
<a href="https://github.com/jaywcjlove/mocker-api/stargazers"> | ||
<img alt="Stars" src="https://img.shields.io/github/stars/jaywcjlove/mocker-api.svg"> | ||
</a> | ||
<a href="https://uiwjs.github.io/npm-unpkg/#/pkg/mocker-api/file/README.md"> | ||
<img src="https://img.shields.io/badge/Open%20in-unpkg-blue" alt="Open in unpkg"> | ||
</a> | ||
<a href="https://gitee.com/jaywcjlove/mocker-api"> | ||
<img alt="Release" src="https://jaywcjlove.github.io/sb/ico/gitee.svg"> | ||
</a> | ||
<a href="https://www.npmjs.com/package/mocker-api"> | ||
<img alt="npm version" src="https://img.shields.io/npm/v/mocker-api.svg"> | ||
</a> | ||
</p> | ||
[中文](https://github.com/jaywcjlove/mocker-api/blob/master/README-zh.md) · [Quick Start](#quick-start) · [Usage](#usage) · [Options](#options) · [Delayed](#delayed-response) · [Example](#example) · [License](#license) | ||
@@ -236,3 +258,3 @@ | ||
"devDependencies": { | ||
+ "mocker-api": "2.8.0" | ||
+ "mocker-api": "2.8.1" | ||
}, | ||
@@ -392,3 +414,3 @@ + "mocker": { | ||
"devDependencies": { | ||
+ "mocker-api": "2.8.0" | ||
+ "mocker-api": "2.8.1" | ||
}, | ||
@@ -395,0 +417,0 @@ .... |
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
License Policy Violation
LicenseThis package is not allowed per your license policy. Review the package's license to ensure compliance.
Found 1 instance in 1 package
Dynamic require
Supply chain riskDynamic require can indicate the package is performing dangerous or unsafe dynamic code execution.
Found 1 instance in 1 package
License Policy Violation
LicenseThis package is not allowed per your license policy. Review the package's license to ensure compliance.
Found 1 instance in 1 package
Dynamic require
Supply chain riskDynamic require can indicate the package is performing dangerous or unsafe dynamic code execution.
Found 1 instance in 1 package
431
103404
1299