import { parse } from 'url' ; /**
 * 鉴于Mock.js不支持拦截fetch发起的ajax，本模块即为Mock.js的补充。
 * 兼容Mock.js以下语法：
 * Mock.setup({timeout: 400})
 * Mock.setup({timeout: '200-400'})
 */ function mockFetch ( Mock ) { if ( ! Mock || ! Mock . mock ) { throw new Error ( 'Mock.js is required.' ) ; } const tempFetchName = '__mockFetchRawFetch__' ; if ( window [ tempFetchName ] ) { return ; } window [ tempFetchName ] = window . fetch ; window . fetch = ( url , options ) => { const { method = 'GET' } = options ; if ( Mock . XHR . _settings . debug ) { console . log ( `${ method } ${ url }` , 'options: ' , options ) ; } const { pathname : path } = parse ( url ) ; for ( const key in Mock . _mocked ) { const item = Mock . _mocked [ key ] ; const urlMatch = ( typeof item . rurl === 'string' && path . indexOf ( item . rurl ) >= 0 ) || ( item . rurl instanceof RegExp && item . rurl . test ( path ) ) ; const methodMatch = ! item . rtype || item . rtype === method ; if ( urlMatch && methodMatch ) { let timeout = Mock . XHR . _settings . timeout || '200-400' ; if ( typeof timeout === 'string' ) { const temp = timeout . split ( '-' ) . map ( e => parseInt ( e ) ) ; timeout = temp [ 0 ] + Math . round ( Math . random ( ) * ( temp [ 1 ] - temp [ 0 ] ) ) ; } Object . assign ( options , { url } ) ; return new Promise ( resolve => { const resp = typeof item . template === 'function' ? item . template . call ( this , options ) : Mock . mock ( item . template ) ; setTimeout ( ( ) => { const response = { text ( ) { return Promise . resolve ( JSON . stringify ( resp ) ) ; } , json ( ) { return Promise . resolve ( resp ) ; } , blob ( ) { return Promise . resolve ( resp ) ; } , formData ( ) { return Promise . resolve ( resp ) ; } , arrayBuffer ( ) { return Promise . resolve ( resp ) ; } , } ; resolve ( { status : 200 , clone ( ) { return this ; } , ... response , } ) ; if ( Mock . XHR . _settings . debug ) { console . log ( 'resp: ' , resp ) ; } } , timeout ) ; } ) ; } } return window [ tempFetchName ] ( url , options ) ; } ; } module . exports = mockFetch ;