Skip to content

Commit b50576d

Browse files
committed
Support proxy other servers
* lint code * fix some uint tests
1 parent 3462bc5 commit b50576d

File tree

15 files changed

+410
-35
lines changed

15 files changed

+410
-35
lines changed

.eslintrc.json

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,8 @@
11
{
22
"parser": "babel-eslint",
33
"env": {
4-
"browser": true
4+
"browser": true,
5+
"es6": true
56
},
67
"extends": "eslint:recommended",
78
"rules": {

.gitignore

Lines changed: 0 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -36,8 +36,5 @@ jspm_packages
3636
# Optional REPL history
3737
.node_repl_history
3838

39-
# outpu
40-
dist/
41-
4239
# MACOS
4340
.DS_Store

.npmignore

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,5 @@
22
logs
33
*.log
44
__mocks__
5-
dist
65
node_modules
76
example

README.md

Lines changed: 9 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,7 @@ So, I create one by myself.
1313
## Roadmap
1414
- [x] Combined with Mock.js
1515
- [x] Support exclude for some other path
16-
- [ ] Proxy for other api server
16+
- [x] Proxy for other api server
1717
- [ ] Support RAP system
1818

1919
## Usage
@@ -64,8 +64,15 @@ if (__dev__) {
6464
fetch: global.fetch,
6565
exclude: [
6666
'http://www.google.com',
67-
/^foo(bar)?$/i,
67+
'/foo(.*)',
6868
],
69+
proxy: [{
70+
path: '/path/for/proxy(.*)',
71+
target: 'http://other.proxy.server',
72+
process: (proxied, matches) => {
73+
return `${proxied.target}${matches[1]}`,
74+
},
75+
}],
6976
}).fetch;
7077
}
7178

__mocks__/index.js

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
import { Mock } from '../';
1+
import { Mock } from '../src';
22

33
export default {
44
'/api/users': ({ params }) => {

dist/index.js

Lines changed: 145 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,145 @@
1+
Object.defineProperty(exports,"__esModule",{value:true});exports.Mock=undefined;var _createClass=function(){function defineProperties(target,props){for(var i=0;i<props.length;i++){var descriptor=props[i];descriptor.enumerable=descriptor.enumerable||false;descriptor.configurable=true;if("value"in descriptor)descriptor.writable=true;Object.defineProperty(target,descriptor.key,descriptor);}}return function(Constructor,protoProps,staticProps){if(protoProps)defineProperties(Constructor.prototype,protoProps);if(staticProps)defineProperties(Constructor,staticProps);return Constructor;};}();var _mockjs=require('mockjs');Object.defineProperty(exports,'Mock',{enumerable:true,get:function get(){return _interopRequireDefault(_mockjs).
2+
3+
4+
5+
6+
7+
8+
9+
10+
11+
12+
13+
14+
15+
16+
17+
18+
19+
20+
21+
22+
23+
24+
25+
26+
27+
28+
29+
30+
31+
32+
33+
34+
35+
36+
37+
38+
39+
40+
41+
42+
43+
44+
45+
46+
47+
48+
49+
50+
51+
52+
53+
54+
55+
56+
57+
58+
59+
60+
61+
62+
63+
64+
65+
66+
67+
68+
69+
70+
71+
72+
73+
74+
75+
76+
77+
78+
79+
80+
81+
82+
83+
84+
85+
86+
87+
88+
89+
90+
91+
92+
93+
94+
95+
96+
97+
98+
99+
100+
101+
102+
103+
104+
105+
106+
107+
108+
109+
110+
111+
112+
113+
114+
115+
116+
117+
118+
119+
120+
121+
122+
123+
124+
125+
126+
127+
128+
129+
130+
131+
132+
133+
134+
135+
136+
137+
138+
139+
140+
141+
142+
143+
144+
145+
default;}});var _pathToRegexp=require('path-to-regexp');var _pathToRegexp2=_interopRequireDefault(_pathToRegexp);var _util=require('./util');var _response=require('./response');var _response2=_interopRequireDefault(_response);function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj};}function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor)){throw new TypeError("Cannot call a class as a function");}}var FetchMock=function(){function FetchMock(required){var options=arguments.length>1&&arguments[1]!==undefined?arguments[1]:{fetch:function fetch(){},exclude:[],proxy:[]};_classCallCheck(this,FetchMock);if('object'!==typeof required){throw new Error('There is no required defined.');}this.urls=[];this.raw=options.fetch;this.exclude=options.exclude;this.proxy=options.proxy;this.loadMocks=this.loadMocks.bind(this);this.loadMock=this.loadMock.bind(this);this.matchReqUrl=this.matchReqUrl.bind(this);this.isExclude=this.isExclude.bind(this);this.isProxied=this.isProxied.bind(this);this.fetch=this.fetch.bind(this);this.loadMocks(required);}_createClass(FetchMock,[{key:'loadMocks',value:function loadMocks(required){var _this=this;var __mocks__=required.default||required;var mocks=Object.keys(__mocks__);mocks.forEach(function(key){_this.loadMock(key,__mocks__[key]);});}},{key:'loadMock',value:function loadMock(key,mock){var _this2=this;if('object'!==typeof mock){if('function'===typeof mock){var items=key.split(' ');var method=items.length===2?items[0]:'GET';var url=items.length===2?items[1]:key;this.urls.push({method:method,url:url,func:mock});}return;}var keys=Object.keys(mock);keys.map(function(key){_this2.loadMock(key,mock[key]);});}},{key:'matchReqUrl',value:function matchReqUrl(request){var insideParams=void 0;var filters=this.urls.filter(function(uri){var obj=(0,_util.matchUrl)(uri.url,request.url);if(obj.result&&uri.method.toUpperCase()===request.method.toUpperCase()){insideParams=obj.params;return true;}return false;});if(!filters||filters.length==0)throw new Error('No url '+request.url+' is defined.');request.urlparams=insideParams;return{request:request,mock:filters[0]};}},{key:'isExclude',value:function isExclude(url){for(var i=0;i<this.exclude.length;i++){var excludeUrl=this.exclude[i];if(excludeUrl===url||(0,_pathToRegexp2.default)(''+excludeUrl).exec(url)!==null){return true;}}return false;}},{key:'isProxied',value:function isProxied(url){if(this.proxy.length===0)return false;var proxied=this.proxy.filter(function(item){return(0,_pathToRegexp2.default)(''+item.path).exec(url)!==null;});if(proxied.length>1)throw new Error(url+' proxied has two proxies, you should specific only one');return proxied[0];}},{key:'proxied',value:function proxied(url){var matches=void 0,proxied=void 0;this.proxy.forEach(function(item){var tmp=(0,_pathToRegexp2.default)(item.path).exec(url);if(tmp.length>1){matches=tmp;proxied=item;return false;}});return proxied.process?proxied.process(proxied,matches):proxied.target+'/'+matches[1];}},{key:'fetch',value:function fetch(url,options){if(this.isProxied(url)){url=this.proxied(url);}if(this.isExclude(url)){return this.raw(url,options);}var _matchReqUrl=this.matchReqUrl((0,_util.parseRequest)(url,options)),request=_matchReqUrl.request,mock=_matchReqUrl.mock;if('function'!==typeof mock.func){throw new Error('There is no url defined in __mocks__');}var obj=mock.func(request);if((0,_util.isNull)(obj)){throw'response data should not be undefined or null, it will be an object or an array at least';}if((0,_util.isNull)(obj.status)){obj={status:200,data:obj};}var response=new _response2.default(obj);return Promise.resolve(response);}}]);return FetchMock;}();exports.default=FetchMock;

dist/response.js

Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
Object.defineProperty(exports,"__esModule",{value:true});var _createClass=function(){function defineProperties(target,props){for(var i=0;i<props.length;i++){var descriptor=props[i];descriptor.enumerable=descriptor.enumerable||false;descriptor.configurable=true;if("value"in descriptor)descriptor.writable=true;Object.defineProperty(target,descriptor.key,descriptor);}}return function(Constructor,protoProps,staticProps){if(protoProps)defineProperties(Constructor.prototype,protoProps);if(staticProps)defineProperties(Constructor,staticProps);return Constructor;};}();function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor)){throw new TypeError("Cannot call a class as a function");}}
2+
var _status=Symbol('status');
3+
var _data=Symbol('data');
4+
var _statusText=Symbol('statusText');var
5+
6+
Response=function(){
7+
function Response(_ref)
8+
9+
10+
11+
{var status=_ref.status,_ref$data=_ref.data,data=_ref$data===undefined?{}:_ref$data,_ref$statusText=_ref.statusText,statusText=_ref$statusText===undefined?'':_ref$statusText;_classCallCheck(this,Response);
12+
this[_status]=status;
13+
this[_data]=data;
14+
this[_statusText]=statusText;
15+
}_createClass(Response,[{key:'text',value:function text()
16+
17+
18+
19+
20+
21+
22+
23+
24+
25+
{
26+
try{
27+
return Promise.resolve(JSON.stringify(this[_data]));
28+
}catch(err){
29+
return Promise.reject(new Error('failed text invoke.'));
30+
}
31+
}},{key:'json',value:function json()
32+
33+
{
34+
return this[_data];
35+
}},{key:'status',get:function get(){return this[_status];}},{key:'statusText',get:function get(){return this[_statusText];}}]);return Response;}();exports.default=
36+
37+
38+
39+
Response;

dist/util.js

Lines changed: 131 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,131 @@
1+
Object.defineProperty(exports,"__esModule",{value:true});var _extends=Object.assign||function(target){for(var i=1;i<arguments.length;i++){var source=arguments[i];for(var key in source){if(Object.prototype.hasOwnProperty.call(source,key)){target[key]=source[key];}}}return target;};
2+
var isNull=function isNull(obj){
3+
if('undefined'===typeof obj||obj===null){
4+
return true;
5+
}
6+
7+
return false;
8+
};
9+
10+
var removeProctol=function removeProctol(url){
11+
var index=-1;
12+
if((index=url.indexOf('://'))>-1){
13+
14+
return url.substring(index);
15+
}
16+
return url;
17+
};
18+
19+
var parseParamStr=function parseParamStr(paramStr,isGet){
20+
var params={};
21+
var paramPairs=paramStr.split('&');
22+
for(var i=0;i<paramPairs.length;i++){
23+
var paramPair=paramPairs[i];
24+
if(paramPair.indexOf('=')===-1){
25+
continue;
26+
}
27+
var paramPairArray=paramPair.split('=');
28+
29+
var paramValue=isGet?decodeURI(paramPairArray[1]):paramPairArray[1];
30+
params[paramPairArray[0]]=paramPairArray.length===2?paramValue:null;
31+
}
32+
return params;
33+
};
34+
35+
var parseBody=function parseBody(body){
36+
if('object'===typeof body){
37+
return body;
38+
}
39+
try{
40+
return JSON.parse(body);
41+
}catch(e){
42+
return parseParamStr(body);
43+
}
44+
};
45+
46+
var parseUrl=function parseUrl(url){
47+
var index=url.indexOf('?');
48+
var items=index>-1?url.split('?'):[url];
49+
if(items.length===1){
50+
return{
51+
url:items[0],
52+
params:{}};
53+
54+
}
55+
56+
return{
57+
url:items[0],
58+
params:parseParamStr(items[1],true)};
59+
60+
};
61+
62+
var parseRequest=function parseRequest(url){var options=arguments.length>1&&arguments[1]!==undefined?arguments[1]:{};
63+
var urlObj=parseUrl(url);
64+
var data=parseBody(options.body||{});
65+
return{
66+
method:options.method||'GET',
67+
url:urlObj.url,
68+
headers:options.headers,
69+
params:_extends({},urlObj.params,data)};
70+
71+
};
72+
73+
var prueUrl=function prueUrl(url){
74+
var index=url.indexOf('?');
75+
var result=index>-1?url.substring(0,index):url;
76+
return result;
77+
};
78+
79+
var matchUrl=function matchUrl(sourceUrl,targetUrl){
80+
if(sourceUrl===targetUrl){
81+
return{
82+
result:true,
83+
params:{}};
84+
85+
}
86+
var sourceUrlWithoutProctol=removeProctol(sourceUrl);
87+
var targetUrlWithoutProctol=removeProctol(targetUrl);
88+
var sourceUrlSplits=sourceUrlWithoutProctol.split('/');
89+
var targetUrlSplits=targetUrlWithoutProctol.split('/');
90+
91+
if(sourceUrlSplits.length!==targetUrlSplits.length){
92+
return{
93+
result:false};
94+
95+
}
96+
97+
var params={};
98+
for(var i=0;i<sourceUrlSplits.length;i++){
99+
var sourceUrlSplit=sourceUrlSplits[i];
100+
var targetUrlSplit=targetUrlSplits[i];
101+
if(sourceUrlSplit===targetUrlSplit){
102+
continue;
103+
}
104+
105+
if(sourceUrlSplit.startsWith('{')&&sourceUrlSplit.endsWith('}')){
106+
if(sourceUrlSplit.replace(/[^{]/g,'').length>1||sourceUrlSplit.replace(/[^}]/g,'').length>1){
107+
return{
108+
result:false};
109+
110+
}
111+
112+
params[sourceUrlSplit.substring(1,sourceUrlSplit.length-1)]=targetUrlSplit;
113+
continue;
114+
}
115+
return{
116+
result:false};
117+
118+
}
119+
120+
return{
121+
result:true,
122+
params:params};
123+
124+
};exports.
125+
126+
127+
isNull=isNull;exports.
128+
prueUrl=prueUrl;exports.
129+
parseUrl=parseUrl;exports.
130+
parseRequest=parseRequest;exports.
131+
matchUrl=matchUrl;

index.js

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1 +1 @@
1-
module.exports = require('./src');
1+
module.exports = require('./dist');

0 commit comments

Comments
 (0)