@@ -3,6 +3,7 @@ import { HttpService } from '@opentiny/tiny-engine'
33import { useBroadcastChannel } from '@vueuse/core'
44import { constants } from '@opentiny/tiny-engine-utils'
55import Login from './Login.vue'
6+ import mockConfig from './mockConfig'
67
78const LOGIN_EXPIRED_CODE = 401
89const { BROADCAST_CHANNEL } = constants
@@ -36,6 +37,72 @@ const preRequest = (config) => {
3637 config . baseURL = ''
3738 }
3839
40+ // 检查是否需要 mock - 纯前端项目,拦截 /api/user/me 接口
41+ const fullUrl = ( config . baseURL || '' ) + ( config . url || '' )
42+ const urlToCheck = config . url || ''
43+
44+ // 检查是否是 /api/user/me 或 /user/me 请求
45+ const isMeRequest = / \/ a p i \/ u s e r \/ m e $ | \/ u s e r \/ m e $ / . test ( fullUrl ) ||
46+ / \/ a p i \/ u s e r \/ m e $ | \/ u s e r \/ m e $ / . test ( urlToCheck )
47+
48+ if ( isMeRequest && ( config . method || 'GET' ) . toUpperCase ( ) === 'GET' ) {
49+
50+ // 找到对应的 mock 配置
51+ const mockRoute = mockConfig . find ( ( route ) => {
52+ const urlMatch = typeof route . url === 'string'
53+ ? fullUrl . includes ( route . url ) || urlToCheck . includes ( route . url )
54+ : route . url . test ( fullUrl ) || route . url . test ( urlToCheck )
55+ const methodMatch = ! route . method ||
56+ route . method . toUpperCase ( ) === ( config . method || 'GET' ) . toUpperCase ( )
57+ return urlMatch && methodMatch
58+ } )
59+
60+ if ( mockRoute ) {
61+ // 直接调用 mock 的 response 函数
62+ const mockResult = mockRoute . response ( config )
63+
64+ // 如果返回的是 Promise,等待 resolve
65+ if ( mockResult && typeof mockResult . then === 'function' ) {
66+ return mockResult . then ( ( [ status , data ] ) => {
67+ console . info ( '222222222222222222222222' , data )
68+ // 返回一个模拟的响应对象
69+ // 注意:axios 请求拦截器返回的应该是 config,但我们可以通过返回一个特殊对象来阻止请求
70+ // 实际上,我们需要修改 config,让它不会发送真实请求
71+ config . adapter = ( ) => {
72+ // 返回一个 Promise,resolve 一个模拟的响应
73+ return Promise . resolve ( {
74+ data : {
75+ data,
76+ error : null
77+ } ,
78+ status,
79+ statusText : 'OK' ,
80+ headers : { } ,
81+ config
82+ } )
83+ }
84+ return config
85+ } )
86+ } else {
87+ // 如果 response 不是异步的,直接处理
88+ const [ status , data ] = mockResult
89+ config . adapter = ( ) => {
90+ return Promise . resolve ( {
91+ data : {
92+ data,
93+ error : null
94+ } ,
95+ status,
96+ statusText : 'OK' ,
97+ headers : { } ,
98+ config
99+ } )
100+ }
101+ return config
102+ }
103+ }
104+ }
105+
39106 return config
40107}
41108
@@ -124,7 +191,9 @@ const customizeHttpService = () => {
124191 interceptors : {
125192 request : [ preRequest ] ,
126193 response : [ [ preResponse , errorResponse ] ]
127- }
194+ } ,
195+ mockConfig,
196+ enableMock : true
128197 }
129198
130199 HttpService . apis . setOptions ( options )
0 commit comments