1+ import pathToRegexp from 'path-to-regexp' ;
12import { parseRequest , matchUrl , isNull } from './util' ;
23import Response from './response' ;
34
45class FetchMock {
56 constructor ( required , options = {
67 fetch : ( ) => { } ,
78 exclude : [ ] ,
9+ proxy : [ ] ,
810 } ) {
911 if ( 'object' !== typeof required ) {
1012 throw new Error ( 'There is no required defined.' ) ;
@@ -13,10 +15,13 @@ class FetchMock {
1315 this . urls = [ ] ;
1416 this . raw = options . fetch ;
1517 this . exclude = options . exclude ;
18+ this . proxy = options . proxy ;
1619
1720 this . loadMocks = this . loadMocks . bind ( this ) ;
1821 this . loadMock = this . loadMock . bind ( this ) ;
1922 this . matchReqUrl = this . matchReqUrl . bind ( this ) ;
23+ this . isExclude = this . isExclude . bind ( this ) ;
24+ this . isProxied = this . isProxied . bind ( this ) ;
2025 this . fetch = this . fetch . bind ( this ) ;
2126
2227 this . loadMocks ( required ) ;
@@ -60,7 +65,7 @@ class FetchMock {
6065 }
6166 return false ;
6267 } ) ;
63- if ( ! filters || filters . length == 0 ) throw new Error ( `No url ${ url } is defined.` ) ;
68+ if ( ! filters || filters . length == 0 ) throw new Error ( `No url ${ request . url } is defined.` ) ;
6469 request . urlparams = insideParams ;
6570 return {
6671 request,
@@ -71,14 +76,42 @@ class FetchMock {
7176 isExclude ( url ) {
7277 for ( let i = 0 ; i < this . exclude . length ; i ++ ) {
7378 const excludeUrl = this . exclude [ i ] ;
74- if ( excludeUrl === url || ( excludeUrl instanceof RegExp && excludeUrl . exec ( url ) !== null ) ) {
79+ if ( excludeUrl === url || pathToRegexp ( ` ${ excludeUrl } ` ) . exec ( url ) !== null ) {
7580 return true ;
7681 }
7782 }
7883 return false ;
7984 }
8085
86+ isProxied ( url ) {
87+ if ( this . proxy . length === 0 ) return false ;
88+ const proxied = this . proxy . filter ( item => pathToRegexp ( `${ item . path } ` ) . exec ( url ) !== null ) ;
89+ if ( proxied . length > 1 ) throw new Error ( `${ url } proxied has two proxies, you should specific only one` ) ;
90+
91+ return proxied [ 0 ] ;
92+ }
93+
94+ proxied ( url ) {
95+ // get proxied info
96+ let matches , proxied ;
97+ this . proxy . forEach ( item => {
98+ const tmp = pathToRegexp ( item . path ) . exec ( url ) ;
99+ if ( tmp . length > 1 ) {
100+ matches = tmp ;
101+ proxied = item ;
102+ return false ;
103+ }
104+ } ) ;
105+
106+ return proxied . process ? proxied . process ( proxied , matches ) : `${ proxied . target } /${ matches [ 1 ] } ` ;
107+ }
108+
81109 fetch ( url , options ) {
110+ // using proxy
111+ if ( this . isProxied ( url ) ) {
112+ url = this . proxied ( url ) ;
113+ }
114+
82115 // using raw fetch while match exclude
83116 if ( this . isExclude ( url ) ) {
84117 // using raw fetch
0 commit comments