Skip to content

Commit 0208526

Browse files
committed
fix: data race
1 parent b46f9f0 commit 0208526

File tree

1 file changed

+28
-10
lines changed

1 file changed

+28
-10
lines changed

src/request.ts

Lines changed: 28 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -90,8 +90,8 @@ export const resolveKyOptions = (): Options => {
9090
fetch,
9191
hooks: {
9292
beforeRequest: [
93-
(req) => {
94-
const apiConfig = getApiConfig()
93+
(req, opt) => {
94+
const apiConfig = (opt as any).apiConfig as ApiConfigResolved
9595
const key = `x-${apiConfig.endpointId}-access-token`
9696
if (req.headers.get(key) === '') req.headers.delete(key)
9797
else if (apiConfig.accessToken && !req.headers.has(key))
@@ -144,17 +144,35 @@ export const getAccessToken = () => apiConfig.accessToken
144144

145145
let _request: KyInstance
146146

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+
147172
/**
148173
* API 请求函数,继承自 [ky](https://github.com/sindresorhus/ky)
149174
*/
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
158176

159177
type ResponseMeta = Pick<
160178
Response,

0 commit comments

Comments
 (0)