-
-
Notifications
You must be signed in to change notification settings - Fork 68
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
1 parent
be543dd
commit 0594f83
Showing
5 changed files
with
151 additions
and
93 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,53 @@ | ||
import URL from 'url'; | ||
import bodyParser from 'body-parser'; | ||
import { Request, Response, NextFunction } from 'express'; | ||
import { MockerOption, MockerProxyRoute } from '.'; | ||
import { pathMatch } from './utils'; | ||
|
||
type MockerHandleOptions = { | ||
req: Request; | ||
res: Response; | ||
next: NextFunction; | ||
options: MockerOption; | ||
mocker: MockerProxyRoute; | ||
mockerKey: string; | ||
} | ||
|
||
export function mockerHandle(param: MockerHandleOptions) { | ||
const { options = {}, req, res, next, mocker, mockerKey } = param || {}; | ||
let bodyParserMethd = bodyParser.json({ ...options.bodyParserJSON }); // 默认使用json解析 | ||
/** | ||
* `application/x-www-form-urlencoded; charset=UTF-8` => `application/x-www-form-urlencoded` | ||
* Issue: https://github.com/jaywcjlove/mocker-api/issues/50 | ||
*/ | ||
let contentType = req.get('Content-Type'); | ||
contentType = contentType && contentType.replace(/;.*$/, ''); | ||
if(options.bodyParserConf && options.bodyParserConf[contentType]) { | ||
// 如果存在options.bodyParserConf配置 {'text/plain': 'text','text/html': 'text'} | ||
switch(options.bodyParserConf[contentType]){// 获取bodyParser的方法 | ||
case 'raw': bodyParserMethd = bodyParser.raw({...options.bodyParserRaw }); break; | ||
case 'text': bodyParserMethd = bodyParser.text({...options.bodyParserText }); break; | ||
case 'urlencoded': bodyParserMethd = bodyParser.urlencoded({extended: false, ...options.bodyParserUrlencoded }); break; | ||
case 'json': bodyParserMethd = bodyParser.json({ ...options.bodyParserJSON });//使用json解析 break; | ||
} | ||
} else { | ||
// 兼容原来的代码,默认解析 | ||
// Compatible with the original code, default parsing | ||
switch(contentType){ | ||
case 'text/plain': bodyParserMethd = bodyParser.raw({...options.bodyParserRaw }); break; | ||
case 'text/html': bodyParserMethd = bodyParser.text({...options.bodyParserText }); break; | ||
case 'application/x-www-form-urlencoded': bodyParserMethd = bodyParser.urlencoded({extended: false, ...options.bodyParserUrlencoded }); break; | ||
} | ||
} | ||
|
||
bodyParserMethd(req, res, function () { | ||
const result = mocker[mockerKey]; | ||
if (typeof result === 'function') { | ||
const rgxStr = ~mockerKey.indexOf(' ') ? ' ' : ''; | ||
req.params = pathMatch({ sensitive: false, strict: false, end: false })(mockerKey.split(new RegExp(rgxStr))[1])(URL.parse(req.url).pathname); | ||
result(req, res, next); | ||
} else { | ||
res.json(result); | ||
} | ||
}); | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,37 @@ | ||
import URL from 'url'; | ||
import httpProxy from 'http-proxy'; | ||
import { Request, Response } from 'express'; | ||
import color from 'colors-cli/safe'; | ||
import { MockerOption, HttpProxyListeners } from '.'; | ||
|
||
export function proxyHandle(req: Request, res: Response, options: MockerOption = {}, proxyKey: string) { | ||
const currentProxy = options.proxy[proxyKey]; | ||
const url = URL.parse(currentProxy); | ||
if (options.changeHost) { | ||
req.headers.host = url.host; | ||
} | ||
const { options: proxyOptions = {}, listeners: proxyListeners = {} as HttpProxyListeners }: MockerOption['httpProxy'] = options.httpProxy; | ||
/** | ||
* rewrite target's url path. Object-keys will be used as RegExp to match paths. | ||
* https://github.com/jaywcjlove/mocker-api/issues/62 | ||
*/ | ||
Object.keys(options.pathRewrite).forEach(rgxStr => { | ||
const rePath = req.path.replace(new RegExp(rgxStr), options.pathRewrite[rgxStr]); | ||
const currentPath = [rePath]; | ||
if (req.url.indexOf('?') > 0) { | ||
currentPath.push(req.url.replace(/(.*)\?/, '')); | ||
} | ||
req.query = URL.parse(req.url, true).query; | ||
req.url = req.originalUrl = currentPath.join('?'); | ||
}); | ||
|
||
const proxyHTTP = httpProxy.createProxyServer({}); | ||
proxyHTTP.on('error', (err) => { | ||
console.error(`${color.red_b.black(` Proxy Failed: ${err.name}`)} ${err.message || ''} ${err.stack || ''} !!`); | ||
}); | ||
Object.keys(proxyListeners).forEach(event => { | ||
proxyHTTP.on(event, proxyListeners[event]); | ||
}); | ||
|
||
proxyHTTP.web(req, res, Object.assign({ target: url.href }, proxyOptions)); | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,28 @@ | ||
|
||
import * as toRegexp from 'path-to-regexp'; | ||
import { TokensToRegexpOptions, ParseOptions, Key } from 'path-to-regexp'; | ||
|
||
const pathToRegexp = toRegexp.pathToRegexp; | ||
|
||
export function pathMatch(options: TokensToRegexpOptions & ParseOptions) { | ||
options = options || {}; | ||
return function (path: string) { | ||
var keys: (Key & TokensToRegexpOptions & ParseOptions & { repeat: boolean })[] = []; | ||
var re = pathToRegexp(path, keys, options); | ||
return function (pathname: string, params?: any) { | ||
var m = re.exec(pathname); | ||
if (!m) return false; | ||
params = params || {}; | ||
var key, param; | ||
for (var i = 0; i < keys.length; i++) { | ||
key = keys[i]; | ||
param = m[i + 1]; | ||
if (!param) continue; | ||
params[key.name] = decodeURIComponent(param); | ||
if (key.repeat) params[key.name] = params[key.name].split(key.delimiter) | ||
} | ||
return params; | ||
} | ||
} | ||
} | ||
|