@@ -90,8 +90,8 @@ export const resolveKyOptions = (): Options => {
90
90
fetch,
91
91
hooks : {
92
92
beforeRequest : [
93
- ( req ) => {
94
- const apiConfig = getApiConfig ( )
93
+ ( req , opt ) => {
94
+ const apiConfig = ( opt as any ) . apiConfig as ApiConfigResolved
95
95
const key = `x-${ apiConfig . endpointId } -access-token`
96
96
if ( req . headers . get ( key ) === '' ) req . headers . delete ( key )
97
97
else if ( apiConfig . accessToken && ! req . headers . has ( key ) )
@@ -144,17 +144,35 @@ export const getAccessToken = () => apiConfig.accessToken
144
144
145
145
let _request : KyInstance
146
146
147
+ const buildProxy = ( targetGetter : ( ) => any ) : any =>
148
+ new Proxy ( ( ) => undefined , {
149
+ get : ( oldTarget , prop , args ) => {
150
+ const target = targetGetter ( )
151
+ if ( ! apiConfig || ! target ) throwNoConfig ( )
152
+
153
+ if ( [ 'get' , 'post' ] . includes ( prop as string ) ) {
154
+ return buildProxy ( ( ) => target [ prop ] )
155
+ }
156
+
157
+ return Reflect . get ( target , prop , args )
158
+ } ,
159
+
160
+ apply : ( oldTarget , prop , args ) => {
161
+ const target = targetGetter ( )
162
+ if ( ! apiConfig || ! target ) throwNoConfig ( )
163
+
164
+ // add apiConfig to request options
165
+ args . slice ( - 1 ) [ 0 ] . apiConfig = apiConfig
166
+
167
+ return Reflect . apply ( target , prop , args )
168
+ } ,
169
+ ownKeys : ( _ , ...args ) => Reflect . ownKeys ( targetGetter ( ) , ...args ) ,
170
+ } )
171
+
147
172
/**
148
173
* API 请求函数,继承自 [ky](https://github.com/sindresorhus/ky)
149
174
*/
150
- export const request = new Proxy ( ( ) => undefined , {
151
- get : ( _ , ...args ) => {
152
- if ( ! apiConfig ) throwNoConfig ( )
153
- return Reflect . get ( _request , ...args )
154
- } ,
155
- apply : ( _ , ...args ) => Reflect . apply ( _request , ...args ) ,
156
- ownKeys : ( _ , ...args ) => Reflect . ownKeys ( _request , ...args ) ,
157
- } ) as unknown as KyInstance
175
+ export const request = buildProxy ( ( ) => _request ) as KyInstance
158
176
159
177
type ResponseMeta = Pick <
160
178
Response ,
0 commit comments